code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.io.Serializable;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.ParseException;
/**
* Basic implementation of {@link Header}.
*
* @since 4.0
*/
public class BasicHeader implements Header, Cloneable, Serializable {
private static final long serialVersionUID = -5427236326487562174L;
private final String name;
private final String value;
/**
* Constructor with name and value
*
* @param name the header name
* @param value the header value
*/
public BasicHeader(final String name, final String value) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
public String toString() {
// no need for non-default formatting in toString()
return BasicLineFormatter.DEFAULT.formatHeader(null, this).toString();
}
public HeaderElement[] getElements() throws ParseException {
if (this.value != null) {
// result intentionally not cached, it's probably not used again
return BasicHeaderValueParser.parseElements(this.value, null);
} else {
return new HeaderElement[] {};
}
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Interface for formatting elements of a header value.
* This is the complement to {@link HeaderValueParser}.
* Instances of this interface are expected to be stateless and thread-safe.
*
* <p>
* All formatting methods accept an optional buffer argument.
* If a buffer is passed in, the formatted element will be appended
* and the modified buffer is returned. If no buffer is passed in,
* a new buffer will be created and filled with the formatted element.
* In both cases, the caller is allowed to modify the returned buffer.
* </p>
*
* @since 4.0
*/
public interface HeaderValueFormatter {
/**
* Formats an array of header elements.
*
* @param buffer the buffer to append to, or
* <code>null</code> to create a new buffer
* @param elems the header elements to format
* @param quote <code>true</code> to always format with quoted values,
* <code>false</code> to use quotes only when necessary
*
* @return a buffer with the formatted header elements.
* If the <code>buffer</code> argument was not <code>null</code>,
* that buffer will be used and returned.
*/
CharArrayBuffer formatElements(CharArrayBuffer buffer,
HeaderElement[] elems,
boolean quote);
/**
* Formats one header element.
*
* @param buffer the buffer to append to, or
* <code>null</code> to create a new buffer
* @param elem the header element to format
* @param quote <code>true</code> to always format with quoted values,
* <code>false</code> to use quotes only when necessary
*
* @return a buffer with the formatted header element.
* If the <code>buffer</code> argument was not <code>null</code>,
* that buffer will be used and returned.
*/
CharArrayBuffer formatHeaderElement(CharArrayBuffer buffer,
HeaderElement elem,
boolean quote);
/**
* Formats the parameters of a header element.
* That's a list of name-value pairs, to be separated by semicolons.
* This method will <i>not</i> generate a leading semicolon.
*
* @param buffer the buffer to append to, or
* <code>null</code> to create a new buffer
* @param nvps the parameters (name-value pairs) to format
* @param quote <code>true</code> to always format with quoted values,
* <code>false</code> to use quotes only when necessary
*
* @return a buffer with the formatted parameters.
* If the <code>buffer</code> argument was not <code>null</code>,
* that buffer will be used and returned.
*/
CharArrayBuffer formatParameters(CharArrayBuffer buffer,
NameValuePair[] nvps,
boolean quote);
/**
* Formats one name-value pair, where the value is optional.
*
* @param buffer the buffer to append to, or
* <code>null</code> to create a new buffer
* @param nvp the name-value pair to format
* @param quote <code>true</code> to always format with a quoted value,
* <code>false</code> to use quotes only when necessary
*
* @return a buffer with the formatted name-value pair.
* If the <code>buffer</code> argument was not <code>null</code>,
* that buffer will be used and returned.
*/
CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer,
NameValuePair nvp,
boolean quote);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.io.Serializable;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* This class represents a raw HTTP header whose content is parsed 'on demand'
* only when the header value needs to be consumed.
*
* @since 4.0
*/
public class BufferedHeader implements FormattedHeader, Cloneable, Serializable {
private static final long serialVersionUID = -2768352615787625448L;
/**
* Header name.
*/
private final String name;
/**
* The buffer containing the entire header line.
*/
private final CharArrayBuffer buffer;
/**
* The beginning of the header value in the buffer
*/
private final int valuePos;
/**
* Creates a new header from a buffer.
* The name of the header will be parsed immediately,
* the value only if it is accessed.
*
* @param buffer the buffer containing the header to represent
*
* @throws ParseException in case of a parse error
*/
public BufferedHeader(final CharArrayBuffer buffer)
throws ParseException {
super();
if (buffer == null) {
throw new IllegalArgumentException
("Char array buffer may not be null");
}
int colon = buffer.indexOf(':');
if (colon == -1) {
throw new ParseException
("Invalid header: " + buffer.toString());
}
String s = buffer.substringTrimmed(0, colon);
if (s.length() == 0) {
throw new ParseException
("Invalid header: " + buffer.toString());
}
this.buffer = buffer;
this.name = s;
this.valuePos = colon + 1;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.buffer.substringTrimmed(this.valuePos, this.buffer.length());
}
public HeaderElement[] getElements() throws ParseException {
ParserCursor cursor = new ParserCursor(0, this.buffer.length());
cursor.updatePos(this.valuePos);
return BasicHeaderValueParser.DEFAULT
.parseElements(this.buffer, cursor);
}
public int getValuePos() {
return this.valuePos;
}
public CharArrayBuffer getBuffer() {
return this.buffer;
}
public String toString() {
return this.buffer.toString();
}
public Object clone() throws CloneNotSupportedException {
// buffer is considered immutable
// no need to make a copy of it
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Basic implementation for formatting header value elements.
* Instances of this class are stateless and thread-safe.
* Derived classes are expected to maintain these properties.
*
* @since 4.0
*/
public class BasicHeaderValueFormatter implements HeaderValueFormatter {
/**
* A default instance of this class, for use as default or fallback.
* Note that {@link BasicHeaderValueFormatter} is not a singleton, there
* can be many instances of the class itself and of derived classes.
* The instance here provides non-customized, default behavior.
*/
public final static
BasicHeaderValueFormatter DEFAULT = new BasicHeaderValueFormatter();
/**
* Special characters that can be used as separators in HTTP parameters.
* These special characters MUST be in a quoted string to be used within
* a parameter value .
*/
public final static String SEPARATORS = " ;,:@()<>\\\"/[]?={}\t";
/**
* Unsafe special characters that must be escaped using the backslash
* character
*/
public final static String UNSAFE_CHARS = "\"\\";
// public default constructor
/**
* Formats an array of header elements.
*
* @param elems the header elements to format
* @param quote <code>true</code> to always format with quoted values,
* <code>false</code> to use quotes only when necessary
* @param formatter the formatter to use, or <code>null</code>
* for the {@link #DEFAULT default}
*
* @return the formatted header elements
*/
public final static
String formatElements(final HeaderElement[] elems,
final boolean quote,
HeaderValueFormatter formatter) {
if (formatter == null)
formatter = BasicHeaderValueFormatter.DEFAULT;
return formatter.formatElements(null, elems, quote).toString();
}
// non-javadoc, see interface HeaderValueFormatter
public CharArrayBuffer formatElements(CharArrayBuffer buffer,
final HeaderElement[] elems,
final boolean quote) {
if (elems == null) {
throw new IllegalArgumentException
("Header element array must not be null.");
}
int len = estimateElementsLen(elems);
if (buffer == null) {
buffer = new CharArrayBuffer(len);
} else {
buffer.ensureCapacity(len);
}
for (int i=0; i<elems.length; i++) {
if (i > 0) {
buffer.append(", ");
}
formatHeaderElement(buffer, elems[i], quote);
}
return buffer;
}
/**
* Estimates the length of formatted header elements.
*
* @param elems the header elements to format, or <code>null</code>
*
* @return a length estimate, in number of characters
*/
protected int estimateElementsLen(final HeaderElement[] elems) {
if ((elems == null) || (elems.length < 1))
return 0;
int result = (elems.length-1) * 2; // elements separated by ", "
for (int i=0; i<elems.length; i++) {
result += estimateHeaderElementLen(elems[i]);
}
return result;
}
/**
* Formats a header element.
*
* @param elem the header element to format
* @param quote <code>true</code> to always format with quoted values,
* <code>false</code> to use quotes only when necessary
* @param formatter the formatter to use, or <code>null</code>
* for the {@link #DEFAULT default}
*
* @return the formatted header element
*/
public final static
String formatHeaderElement(final HeaderElement elem,
boolean quote,
HeaderValueFormatter formatter) {
if (formatter == null)
formatter = BasicHeaderValueFormatter.DEFAULT;
return formatter.formatHeaderElement(null, elem, quote).toString();
}
// non-javadoc, see interface HeaderValueFormatter
public CharArrayBuffer formatHeaderElement(CharArrayBuffer buffer,
final HeaderElement elem,
final boolean quote) {
if (elem == null) {
throw new IllegalArgumentException
("Header element must not be null.");
}
int len = estimateHeaderElementLen(elem);
if (buffer == null) {
buffer = new CharArrayBuffer(len);
} else {
buffer.ensureCapacity(len);
}
buffer.append(elem.getName());
final String value = elem.getValue();
if (value != null) {
buffer.append('=');
doFormatValue(buffer, value, quote);
}
final int parcnt = elem.getParameterCount();
if (parcnt > 0) {
for (int i=0; i<parcnt; i++) {
buffer.append("; ");
formatNameValuePair(buffer, elem.getParameter(i), quote);
}
}
return buffer;
}
/**
* Estimates the length of a formatted header element.
*
* @param elem the header element to format, or <code>null</code>
*
* @return a length estimate, in number of characters
*/
protected int estimateHeaderElementLen(final HeaderElement elem) {
if (elem == null)
return 0;
int result = elem.getName().length(); // name
final String value = elem.getValue();
if (value != null) {
// assume quotes, but no escaped characters
result += 3 + value.length(); // ="value"
}
final int parcnt = elem.getParameterCount();
if (parcnt > 0) {
for (int i=0; i<parcnt; i++) {
result += 2 + // ; <param>
estimateNameValuePairLen(elem.getParameter(i));
}
}
return result;
}
/**
* Formats a set of parameters.
*
* @param nvps the parameters to format
* @param quote <code>true</code> to always format with quoted values,
* <code>false</code> to use quotes only when necessary
* @param formatter the formatter to use, or <code>null</code>
* for the {@link #DEFAULT default}
*
* @return the formatted parameters
*/
public final static
String formatParameters(final NameValuePair[] nvps,
final boolean quote,
HeaderValueFormatter formatter) {
if (formatter == null)
formatter = BasicHeaderValueFormatter.DEFAULT;
return formatter.formatParameters(null, nvps, quote).toString();
}
// non-javadoc, see interface HeaderValueFormatter
public CharArrayBuffer formatParameters(CharArrayBuffer buffer,
NameValuePair[] nvps,
boolean quote) {
if (nvps == null) {
throw new IllegalArgumentException
("Parameters must not be null.");
}
int len = estimateParametersLen(nvps);
if (buffer == null) {
buffer = new CharArrayBuffer(len);
} else {
buffer.ensureCapacity(len);
}
for (int i = 0; i < nvps.length; i++) {
if (i > 0) {
buffer.append("; ");
}
formatNameValuePair(buffer, nvps[i], quote);
}
return buffer;
}
/**
* Estimates the length of formatted parameters.
*
* @param nvps the parameters to format, or <code>null</code>
*
* @return a length estimate, in number of characters
*/
protected int estimateParametersLen(final NameValuePair[] nvps) {
if ((nvps == null) || (nvps.length < 1))
return 0;
int result = (nvps.length-1) * 2; // "; " between the parameters
for (int i=0; i<nvps.length; i++) {
result += estimateNameValuePairLen(nvps[i]);
}
return result;
}
/**
* Formats a name-value pair.
*
* @param nvp the name-value pair to format
* @param quote <code>true</code> to always format with a quoted value,
* <code>false</code> to use quotes only when necessary
* @param formatter the formatter to use, or <code>null</code>
* for the {@link #DEFAULT default}
*
* @return the formatted name-value pair
*/
public final static
String formatNameValuePair(final NameValuePair nvp,
final boolean quote,
HeaderValueFormatter formatter) {
if (formatter == null)
formatter = BasicHeaderValueFormatter.DEFAULT;
return formatter.formatNameValuePair(null, nvp, quote).toString();
}
// non-javadoc, see interface HeaderValueFormatter
public CharArrayBuffer formatNameValuePair(CharArrayBuffer buffer,
final NameValuePair nvp,
final boolean quote) {
if (nvp == null) {
throw new IllegalArgumentException
("NameValuePair must not be null.");
}
int len = estimateNameValuePairLen(nvp);
if (buffer == null) {
buffer = new CharArrayBuffer(len);
} else {
buffer.ensureCapacity(len);
}
buffer.append(nvp.getName());
final String value = nvp.getValue();
if (value != null) {
buffer.append('=');
doFormatValue(buffer, value, quote);
}
return buffer;
}
/**
* Estimates the length of a formatted name-value pair.
*
* @param nvp the name-value pair to format, or <code>null</code>
*
* @return a length estimate, in number of characters
*/
protected int estimateNameValuePairLen(final NameValuePair nvp) {
if (nvp == null)
return 0;
int result = nvp.getName().length(); // name
final String value = nvp.getValue();
if (value != null) {
// assume quotes, but no escaped characters
result += 3 + value.length(); // ="value"
}
return result;
}
/**
* Actually formats the value of a name-value pair.
* This does not include a leading = character.
* Called from {@link #formatNameValuePair formatNameValuePair}.
*
* @param buffer the buffer to append to, never <code>null</code>
* @param value the value to append, never <code>null</code>
* @param quote <code>true</code> to always format with quotes,
* <code>false</code> to use quotes only when necessary
*/
protected void doFormatValue(final CharArrayBuffer buffer,
final String value,
boolean quote) {
if (!quote) {
for (int i = 0; (i < value.length()) && !quote; i++) {
quote = isSeparator(value.charAt(i));
}
}
if (quote) {
buffer.append('"');
}
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (isUnsafe(ch)) {
buffer.append('\\');
}
buffer.append(ch);
}
if (quote) {
buffer.append('"');
}
}
/**
* Checks whether a character is a {@link #SEPARATORS separator}.
*
* @param ch the character to check
*
* @return <code>true</code> if the character is a separator,
* <code>false</code> otherwise
*/
protected boolean isSeparator(char ch) {
return SEPARATORS.indexOf(ch) >= 0;
}
/**
* Checks whether a character is {@link #UNSAFE_CHARS unsafe}.
*
* @param ch the character to check
*
* @return <code>true</code> if the character is unsafe,
* <code>false</code> otherwise
*/
protected boolean isUnsafe(char ch) {
return UNSAFE_CHARS.indexOf(ch) >= 0;
}
} // class BasicHeaderValueFormatter
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.LangUtils;
/**
* Basic implementation of {@link HeaderElement}
*
* @since 4.0
*/
public class BasicHeaderElement implements HeaderElement, Cloneable {
private final String name;
private final String value;
private final NameValuePair[] parameters;
/**
* Constructor with name, value and parameters.
*
* @param name header element name
* @param value header element value. May be <tt>null</tt>
* @param parameters header element parameters. May be <tt>null</tt>.
* Parameters are copied by reference, not by value
*/
public BasicHeaderElement(
final String name,
final String value,
final NameValuePair[] parameters) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
this.name = name;
this.value = value;
if (parameters != null) {
this.parameters = parameters;
} else {
this.parameters = new NameValuePair[] {};
}
}
/**
* Constructor with name and value.
*
* @param name header element name
* @param value header element value. May be <tt>null</tt>
*/
public BasicHeaderElement(final String name, final String value) {
this(name, value, null);
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
public NameValuePair[] getParameters() {
return (NameValuePair[])this.parameters.clone();
}
public int getParameterCount() {
return this.parameters.length;
}
public NameValuePair getParameter(int index) {
// ArrayIndexOutOfBoundsException is appropriate
return this.parameters[index];
}
public NameValuePair getParameterByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
NameValuePair found = null;
for (int i = 0; i < this.parameters.length; i++) {
NameValuePair current = this.parameters[ i ];
if (current.getName().equalsIgnoreCase(name)) {
found = current;
break;
}
}
return found;
}
public boolean equals(final Object object) {
if (this == object) return true;
if (object instanceof HeaderElement) {
BasicHeaderElement that = (BasicHeaderElement) object;
return this.name.equals(that.name)
&& LangUtils.equals(this.value, that.value)
&& LangUtils.equals(this.parameters, that.parameters);
} else {
return false;
}
}
public int hashCode() {
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.name);
hash = LangUtils.hashCode(hash, this.value);
for (int i = 0; i < this.parameters.length; i++) {
hash = LangUtils.hashCode(hash, this.parameters[i]);
}
return hash;
}
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(64);
buffer.append(this.name);
if (this.value != null) {
buffer.append("=");
buffer.append(this.value);
}
for (int i = 0; i < this.parameters.length; i++) {
buffer.append("; ");
buffer.append(this.parameters[i]);
}
return buffer.toString();
}
public Object clone() throws CloneNotSupportedException {
// parameters array is considered immutable
// no need to make a copy of it
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.io.Serializable;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.LangUtils;
/**
* Basic implementation of {@link NameValuePair}.
*
* @since 4.0
*/
public class BasicNameValuePair implements NameValuePair, Cloneable, Serializable {
private static final long serialVersionUID = -6437800749411518984L;
private final String name;
private final String value;
/**
* Default Constructor taking a name and a value. The value may be null.
*
* @param name The name.
* @param value The value.
*/
public BasicNameValuePair(final String name, final String value) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
public String toString() {
// don't call complex default formatting for a simple toString
if (this.value == null) {
return name;
} else {
int len = this.name.length() + 1 + this.value.length();
CharArrayBuffer buffer = new CharArrayBuffer(len);
buffer.append(this.name);
buffer.append("=");
buffer.append(this.value);
return buffer.toString();
}
}
public boolean equals(final Object object) {
if (this == object) return true;
if (object instanceof NameValuePair) {
BasicNameValuePair that = (BasicNameValuePair) object;
return this.name.equals(that.name)
&& LangUtils.equals(this.value, that.value);
} else {
return false;
}
}
public int hashCode() {
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.name);
hash = LangUtils.hashCode(hash, this.value);
return hash;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.util.Iterator;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderIterator;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Basic implementation of {@link HttpMessage}.
*
* @since 4.0
*/
public abstract class AbstractHttpMessage implements HttpMessage {
protected HeaderGroup headergroup;
protected HttpParams params;
protected AbstractHttpMessage(final HttpParams params) {
super();
this.headergroup = new HeaderGroup();
this.params = params;
}
protected AbstractHttpMessage() {
this(null);
}
// non-javadoc, see interface HttpMessage
public boolean containsHeader(String name) {
return this.headergroup.containsHeader(name);
}
// non-javadoc, see interface HttpMessage
public Header[] getHeaders(final String name) {
return this.headergroup.getHeaders(name);
}
// non-javadoc, see interface HttpMessage
public Header getFirstHeader(final String name) {
return this.headergroup.getFirstHeader(name);
}
// non-javadoc, see interface HttpMessage
public Header getLastHeader(final String name) {
return this.headergroup.getLastHeader(name);
}
// non-javadoc, see interface HttpMessage
public Header[] getAllHeaders() {
return this.headergroup.getAllHeaders();
}
// non-javadoc, see interface HttpMessage
public void addHeader(final Header header) {
this.headergroup.addHeader(header);
}
// non-javadoc, see interface HttpMessage
public void addHeader(final String name, final String value) {
if (name == null) {
throw new IllegalArgumentException("Header name may not be null");
}
this.headergroup.addHeader(new BasicHeader(name, value));
}
// non-javadoc, see interface HttpMessage
public void setHeader(final Header header) {
this.headergroup.updateHeader(header);
}
// non-javadoc, see interface HttpMessage
public void setHeader(final String name, final String value) {
if (name == null) {
throw new IllegalArgumentException("Header name may not be null");
}
this.headergroup.updateHeader(new BasicHeader(name, value));
}
// non-javadoc, see interface HttpMessage
public void setHeaders(final Header[] headers) {
this.headergroup.setHeaders(headers);
}
// non-javadoc, see interface HttpMessage
public void removeHeader(final Header header) {
this.headergroup.removeHeader(header);
}
// non-javadoc, see interface HttpMessage
public void removeHeaders(final String name) {
if (name == null) {
return;
}
for (Iterator i = this.headergroup.iterator(); i.hasNext(); ) {
Header header = (Header) i.next();
if (name.equalsIgnoreCase(header.getName())) {
i.remove();
}
}
}
// non-javadoc, see interface HttpMessage
public HeaderIterator headerIterator() {
return this.headergroup.iterator();
}
// non-javadoc, see interface HttpMessage
public HeaderIterator headerIterator(String name) {
return this.headergroup.iterator(name);
}
// non-javadoc, see interface HttpMessage
public HttpParams getParams() {
if (this.params == null) {
this.params = new BasicHttpParams();
}
return this.params;
}
// non-javadoc, see interface HttpMessage
public void setParams(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.params = params;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* This class represents a context of a parsing operation:
* <ul>
* <li>the current position the parsing operation is expected to start at</li>
* <li>the bounds limiting the scope of the parsing operation</li>
* </ul>
*
* @since 4.0
*/
public class ParserCursor {
private final int lowerBound;
private final int upperBound;
private int pos;
public ParserCursor(int lowerBound, int upperBound) {
super();
if (lowerBound < 0) {
throw new IndexOutOfBoundsException("Lower bound cannot be negative");
}
if (lowerBound > upperBound) {
throw new IndexOutOfBoundsException("Lower bound cannot be greater then upper bound");
}
this.lowerBound = lowerBound;
this.upperBound = upperBound;
this.pos = lowerBound;
}
public int getLowerBound() {
return this.lowerBound;
}
public int getUpperBound() {
return this.upperBound;
}
public int getPos() {
return this.pos;
}
public void updatePos(int pos) {
if (pos < this.lowerBound) {
throw new IndexOutOfBoundsException("pos: "+pos+" < lowerBound: "+this.lowerBound);
}
if (pos > this.upperBound) {
throw new IndexOutOfBoundsException("pos: "+pos+" > upperBound: "+this.upperBound);
}
this.pos = pos;
}
public boolean atEnd() {
return this.pos >= this.upperBound;
}
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append('[');
buffer.append(Integer.toString(this.lowerBound));
buffer.append('>');
buffer.append(Integer.toString(this.pos));
buffer.append('>');
buffer.append(Integer.toString(this.upperBound));
buffer.append(']');
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.util.List;
import java.util.NoSuchElementException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderIterator;
/**
* Implementation of a {@link HeaderIterator} based on a {@link List}.
* For use by {@link HeaderGroup}.
*
* @since 4.0
*/
public class BasicListHeaderIterator implements HeaderIterator {
/**
* A list of headers to iterate over.
* Not all elements of this array are necessarily part of the iteration.
*/
protected final List allHeaders;
/**
* The position of the next header in {@link #allHeaders allHeaders}.
* Negative if the iteration is over.
*/
protected int currentIndex;
/**
* The position of the last returned header.
* Negative if none has been returned so far.
*/
protected int lastIndex;
/**
* The header name to filter by.
* <code>null</code> to iterate over all headers in the array.
*/
protected String headerName;
/**
* Creates a new header iterator.
*
* @param headers a list of headers over which to iterate
* @param name the name of the headers over which to iterate, or
* <code>null</code> for any
*/
public BasicListHeaderIterator(List headers, String name) {
if (headers == null) {
throw new IllegalArgumentException
("Header list must not be null.");
}
this.allHeaders = headers;
this.headerName = name;
this.currentIndex = findNext(-1);
this.lastIndex = -1;
}
/**
* Determines the index of the next header.
*
* @param from one less than the index to consider first,
* -1 to search for the first header
*
* @return the index of the next header that matches the filter name,
* or negative if there are no more headers
*/
protected int findNext(int from) {
if (from < -1)
return -1;
final int to = this.allHeaders.size()-1;
boolean found = false;
while (!found && (from < to)) {
from++;
found = filterHeader(from);
}
return found ? from : -1;
}
/**
* Checks whether a header is part of the iteration.
*
* @param index the index of the header to check
*
* @return <code>true</code> if the header should be part of the
* iteration, <code>false</code> to skip
*/
protected boolean filterHeader(int index) {
if (this.headerName == null)
return true;
// non-header elements, including null, will trigger exceptions
final String name = ((Header)this.allHeaders.get(index)).getName();
return this.headerName.equalsIgnoreCase(name);
}
// non-javadoc, see interface HeaderIterator
public boolean hasNext() {
return (this.currentIndex >= 0);
}
/**
* Obtains the next header from this iteration.
*
* @return the next header in this iteration
*
* @throws NoSuchElementException if there are no more headers
*/
public Header nextHeader()
throws NoSuchElementException {
final int current = this.currentIndex;
if (current < 0) {
throw new NoSuchElementException("Iteration already finished.");
}
this.lastIndex = current;
this.currentIndex = findNext(current);
return (Header) this.allHeaders.get(current);
}
/**
* Returns the next header.
* Same as {@link #nextHeader nextHeader}, but not type-safe.
*
* @return the next header in this iteration
*
* @throws NoSuchElementException if there are no more headers
*/
public final Object next()
throws NoSuchElementException {
return nextHeader();
}
/**
* Removes the header that was returned last.
*/
public void remove()
throws UnsupportedOperationException {
if (this.lastIndex < 0) {
throw new IllegalStateException("No header to remove.");
}
this.allHeaders.remove(this.lastIndex);
this.lastIndex = -1;
this.currentIndex--; // adjust for the removed element
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.util.Locale;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.ReasonPhraseCatalog;
import org.apache.ogt.http.StatusLine;
/**
* Basic implementation of {@link HttpResponse}.
*
* @since 4.0
*/
public class BasicHttpResponse extends AbstractHttpMessage
implements HttpResponse {
private StatusLine statusline;
private HttpEntity entity;
private ReasonPhraseCatalog reasonCatalog;
private Locale locale;
/**
* Creates a new response.
* This is the constructor to which all others map.
*
* @param statusline the status line
* @param catalog the reason phrase catalog, or
* <code>null</code> to disable automatic
* reason phrase lookup
* @param locale the locale for looking up reason phrases, or
* <code>null</code> for the system locale
*/
public BasicHttpResponse(final StatusLine statusline,
final ReasonPhraseCatalog catalog,
final Locale locale) {
super();
if (statusline == null) {
throw new IllegalArgumentException("Status line may not be null.");
}
this.statusline = statusline;
this.reasonCatalog = catalog;
this.locale = (locale != null) ? locale : Locale.getDefault();
}
/**
* Creates a response from a status line.
* The response will not have a reason phrase catalog and
* use the system default locale.
*
* @param statusline the status line
*/
public BasicHttpResponse(final StatusLine statusline) {
this(statusline, null, null);
}
/**
* Creates a response from elements of a status line.
* The response will not have a reason phrase catalog and
* use the system default locale.
*
* @param ver the protocol version of the response
* @param code the status code of the response
* @param reason the reason phrase to the status code, or
* <code>null</code>
*/
public BasicHttpResponse(final ProtocolVersion ver,
final int code,
final String reason) {
this(new BasicStatusLine(ver, code, reason), null, null);
}
// non-javadoc, see interface HttpMessage
public ProtocolVersion getProtocolVersion() {
return this.statusline.getProtocolVersion();
}
// non-javadoc, see interface HttpResponse
public StatusLine getStatusLine() {
return this.statusline;
}
// non-javadoc, see interface HttpResponse
public HttpEntity getEntity() {
return this.entity;
}
// non-javadoc, see interface HttpResponse
public Locale getLocale() {
return this.locale;
}
// non-javadoc, see interface HttpResponse
public void setStatusLine(final StatusLine statusline) {
if (statusline == null) {
throw new IllegalArgumentException("Status line may not be null");
}
this.statusline = statusline;
}
// non-javadoc, see interface HttpResponse
public void setStatusLine(final ProtocolVersion ver, final int code) {
// arguments checked in BasicStatusLine constructor
this.statusline = new BasicStatusLine(ver, code, getReason(code));
}
// non-javadoc, see interface HttpResponse
public void setStatusLine(final ProtocolVersion ver, final int code,
final String reason) {
// arguments checked in BasicStatusLine constructor
this.statusline = new BasicStatusLine(ver, code, reason);
}
// non-javadoc, see interface HttpResponse
public void setStatusCode(int code) {
// argument checked in BasicStatusLine constructor
ProtocolVersion ver = this.statusline.getProtocolVersion();
this.statusline = new BasicStatusLine(ver, code, getReason(code));
}
// non-javadoc, see interface HttpResponse
public void setReasonPhrase(String reason) {
if ((reason != null) && ((reason.indexOf('\n') >= 0) ||
(reason.indexOf('\r') >= 0))
) {
throw new IllegalArgumentException("Line break in reason phrase.");
}
this.statusline = new BasicStatusLine(this.statusline.getProtocolVersion(),
this.statusline.getStatusCode(),
reason);
}
// non-javadoc, see interface HttpResponse
public void setEntity(final HttpEntity entity) {
this.entity = entity;
}
// non-javadoc, see interface HttpResponse
public void setLocale(Locale loc) {
if (loc == null) {
throw new IllegalArgumentException("Locale may not be null.");
}
this.locale = loc;
final int code = this.statusline.getStatusCode();
this.statusline = new BasicStatusLine
(this.statusline.getProtocolVersion(), code, getReason(code));
}
/**
* Looks up a reason phrase.
* This method evaluates the currently set catalog and locale.
* It also handles a missing catalog.
*
* @param code the status code for which to look up the reason
*
* @return the reason phrase, or <code>null</code> if there is none
*/
protected String getReason(int code) {
return (this.reasonCatalog == null) ?
null : this.reasonCatalog.getReason(code, this.locale);
}
public String toString() {
return this.statusline + " " + this.headergroup;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.message;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderIterator;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* A class for combining a set of headers.
* This class allows for multiple headers with the same name and
* keeps track of the order in which headers were added.
*
*
* @since 4.0
*/
public class HeaderGroup implements Cloneable, Serializable {
private static final long serialVersionUID = 2608834160639271617L;
/** The list of headers for this group, in the order in which they were added */
private final List headers;
/**
* Constructor for HeaderGroup.
*/
public HeaderGroup() {
this.headers = new ArrayList(16);
}
/**
* Removes any contained headers.
*/
public void clear() {
headers.clear();
}
/**
* Adds the given header to the group. The order in which this header was
* added is preserved.
*
* @param header the header to add
*/
public void addHeader(Header header) {
if (header == null) {
return;
}
headers.add(header);
}
/**
* Removes the given header.
*
* @param header the header to remove
*/
public void removeHeader(Header header) {
if (header == null) {
return;
}
headers.remove(header);
}
/**
* Replaces the first occurence of the header with the same name. If no header with
* the same name is found the given header is added to the end of the list.
*
* @param header the new header that should replace the first header with the same
* name if present in the list.
*/
public void updateHeader(Header header) {
if (header == null) {
return;
}
for (int i = 0; i < this.headers.size(); i++) {
Header current = (Header) this.headers.get(i);
if (current.getName().equalsIgnoreCase(header.getName())) {
this.headers.set(i, header);
return;
}
}
this.headers.add(header);
}
/**
* Sets all of the headers contained within this group overriding any
* existing headers. The headers are added in the order in which they appear
* in the array.
*
* @param headers the headers to set
*/
public void setHeaders(Header[] headers) {
clear();
if (headers == null) {
return;
}
for (int i = 0; i < headers.length; i++) {
this.headers.add(headers[i]);
}
}
/**
* Gets a header representing all of the header values with the given name.
* If more that one header with the given name exists the values will be
* combined with a "," as per RFC 2616.
*
* <p>Header name comparison is case insensitive.
*
* @param name the name of the header(s) to get
* @return a header with a condensed value or <code>null</code> if no
* headers by the given name are present
*/
public Header getCondensedHeader(String name) {
Header[] headers = getHeaders(name);
if (headers.length == 0) {
return null;
} else if (headers.length == 1) {
return headers[0];
} else {
CharArrayBuffer valueBuffer = new CharArrayBuffer(128);
valueBuffer.append(headers[0].getValue());
for (int i = 1; i < headers.length; i++) {
valueBuffer.append(", ");
valueBuffer.append(headers[i].getValue());
}
return new BasicHeader(name.toLowerCase(Locale.ENGLISH), valueBuffer.toString());
}
}
/**
* Gets all of the headers with the given name. The returned array
* maintains the relative order in which the headers were added.
*
* <p>Header name comparison is case insensitive.
*
* @param name the name of the header(s) to get
*
* @return an array of length >= 0
*/
public Header[] getHeaders(String name) {
ArrayList headersFound = new ArrayList();
for (int i = 0; i < headers.size(); i++) {
Header header = (Header) headers.get(i);
if (header.getName().equalsIgnoreCase(name)) {
headersFound.add(header);
}
}
return (Header[]) headersFound.toArray(new Header[headersFound.size()]);
}
/**
* Gets the first header with the given name.
*
* <p>Header name comparison is case insensitive.
*
* @param name the name of the header to get
* @return the first header or <code>null</code>
*/
public Header getFirstHeader(String name) {
for (int i = 0; i < headers.size(); i++) {
Header header = (Header) headers.get(i);
if (header.getName().equalsIgnoreCase(name)) {
return header;
}
}
return null;
}
/**
* Gets the last header with the given name.
*
* <p>Header name comparison is case insensitive.
*
* @param name the name of the header to get
* @return the last header or <code>null</code>
*/
public Header getLastHeader(String name) {
// start at the end of the list and work backwards
for (int i = headers.size() - 1; i >= 0; i--) {
Header header = (Header) headers.get(i);
if (header.getName().equalsIgnoreCase(name)) {
return header;
}
}
return null;
}
/**
* Gets all of the headers contained within this group.
*
* @return an array of length >= 0
*/
public Header[] getAllHeaders() {
return (Header[]) headers.toArray(new Header[headers.size()]);
}
/**
* Tests if headers with the given name are contained within this group.
*
* <p>Header name comparison is case insensitive.
*
* @param name the header name to test for
* @return <code>true</code> if at least one header with the name is
* contained, <code>false</code> otherwise
*/
public boolean containsHeader(String name) {
for (int i = 0; i < headers.size(); i++) {
Header header = (Header) headers.get(i);
if (header.getName().equalsIgnoreCase(name)) {
return true;
}
}
return false;
}
/**
* Returns an iterator over this group of headers.
*
* @return iterator over this group of headers.
*
* @since 4.0
*/
public HeaderIterator iterator() {
return new BasicListHeaderIterator(this.headers, null);
}
/**
* Returns an iterator over the headers with a given name in this group.
*
* @param name the name of the headers over which to iterate, or
* <code>null</code> for all headers
*
* @return iterator over some headers in this group.
*
* @since 4.0
*/
public HeaderIterator iterator(final String name) {
return new BasicListHeaderIterator(this.headers, name);
}
/**
* Returns a copy of this object
*
* @return copy of this object
*
* @since 4.0
*/
public HeaderGroup copy() {
HeaderGroup clone = new HeaderGroup();
clone.headers.addAll(this.headers);
return clone;
}
public Object clone() throws CloneNotSupportedException {
HeaderGroup clone = (HeaderGroup) super.clone();
clone.headers.clear();
clone.headers.addAll(this.headers);
return clone;
}
public String toString() {
return this.headers.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.params;
/**
* Thread-safe extension of the {@link BasicHttpParams}.
*
* @since 4.1
*/
public class SyncBasicHttpParams extends BasicHttpParams {
private static final long serialVersionUID = 5387834869062660642L;
public SyncBasicHttpParams() {
super();
}
public synchronized boolean removeParameter(final String name) {
return super.removeParameter(name);
}
public synchronized HttpParams setParameter(final String name, final Object value) {
return super.setParameter(name, value);
}
public synchronized Object getParameter(final String name) {
return super.getParameter(name);
}
public synchronized boolean isParameterSet(final String name) {
return super.isParameterSet(name);
}
public synchronized boolean isParameterSetLocally(final String name) {
return super.isParameterSetLocally(name);
}
public synchronized void setParameters(final String[] names, final Object value) {
super.setParameters(names, value);
}
public synchronized void clear() {
super.clear();
}
public synchronized Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.protocol.HTTP;
/**
* Utility class for accessing protocol parameters in {@link HttpParams}.
*
* @since 4.0
*
* @see CoreProtocolPNames
*/
public final class HttpProtocolParams implements CoreProtocolPNames {
private HttpProtocolParams() {
super();
}
/**
* Obtains value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter.
* If not set, defaults to <code>US-ASCII</code>.
*
* @param params HTTP parameters.
* @return HTTP element charset.
*/
public static String getHttpElementCharset(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
String charset = (String) params.getParameter
(CoreProtocolPNames.HTTP_ELEMENT_CHARSET);
if (charset == null) {
charset = HTTP.DEFAULT_PROTOCOL_CHARSET;
}
return charset;
}
/**
* Sets value of the {@link CoreProtocolPNames#HTTP_ELEMENT_CHARSET} parameter.
*
* @param params HTTP parameters.
* @param charset HTTP element charset.
*/
public static void setHttpElementCharset(final HttpParams params, final String charset) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, charset);
}
/**
* Obtains value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter.
* If not set, defaults to <code>ISO-8859-1</code>.
*
* @param params HTTP parameters.
* @return HTTP content charset.
*/
public static String getContentCharset(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
String charset = (String) params.getParameter
(CoreProtocolPNames.HTTP_CONTENT_CHARSET);
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
return charset;
}
/**
* Sets value of the {@link CoreProtocolPNames#HTTP_CONTENT_CHARSET} parameter.
*
* @param params HTTP parameters.
* @param charset HTTP content charset.
*/
public static void setContentCharset(final HttpParams params, final String charset) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset);
}
/**
* Obtains value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter.
* If not set, defaults to {@link HttpVersion#HTTP_1_1}.
*
* @param params HTTP parameters.
* @return HTTP protocol version.
*/
public static ProtocolVersion getVersion(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Object param = params.getParameter
(CoreProtocolPNames.PROTOCOL_VERSION);
if (param == null) {
return HttpVersion.HTTP_1_1;
}
return (ProtocolVersion)param;
}
/**
* Sets value of the {@link CoreProtocolPNames#PROTOCOL_VERSION} parameter.
*
* @param params HTTP parameters.
* @param version HTTP protocol version.
*/
public static void setVersion(final HttpParams params, final ProtocolVersion version) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, version);
}
/**
* Obtains value of the {@link CoreProtocolPNames#USER_AGENT} parameter.
* If not set, returns <code>null</code>.
*
* @param params HTTP parameters.
* @return User agent string.
*/
public static String getUserAgent(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return (String) params.getParameter(CoreProtocolPNames.USER_AGENT);
}
/**
* Sets value of the {@link CoreProtocolPNames#USER_AGENT} parameter.
*
* @param params HTTP parameters.
* @param useragent User agent string.
*/
public static void setUserAgent(final HttpParams params, final String useragent) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setParameter(CoreProtocolPNames.USER_AGENT, useragent);
}
/**
* Obtains value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter.
* If not set, returns <code>false</code>.
*
* @param params HTTP parameters.
* @return User agent string.
*/
public static boolean useExpectContinue(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter
(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
}
/**
* Sets value of the {@link CoreProtocolPNames#USE_EXPECT_CONTINUE} parameter.
*
* @param params HTTP parameters.
* @param b expect-continue flag.
*/
public static void setUseExpectContinue(final HttpParams params, boolean b) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, b);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
/**
* HttpParams interface represents a collection of immutable values that define
* a runtime behavior of a component. HTTP parameters should be simple objects:
* integers, doubles, strings, collections and objects that remain immutable
* at runtime. HttpParams is expected to be used in 'write once - read many' mode.
* Once initialized, HTTP parameters are not expected to mutate in
* the course of HTTP message processing.
* <p>
* The purpose of this interface is to define a behavior of other components.
* Usually each complex component has its own HTTP parameter collection.
* <p>
* Instances of this interface can be linked together to form a hierarchy.
* In the simplest form one set of parameters can use content of another one
* to obtain default values of parameters not present in the local set.
*
* @see DefaultedHttpParams
*
* @since 4.0
*/
public interface HttpParams {
/**
* Obtains the value of the given parameter.
*
* @param name the parent name.
*
* @return an object that represents the value of the parameter,
* <code>null</code> if the parameter is not set or if it
* is explicitly set to <code>null</code>
*
* @see #setParameter(String, Object)
*/
Object getParameter(String name);
/**
* Assigns the value to the parameter with the given name.
*
* @param name parameter name
* @param value parameter value
*/
HttpParams setParameter(String name, Object value);
/**
* Creates a copy of these parameters.
*
* @return a new set of parameters holding the same values as this one
*
* @deprecated
*/
HttpParams copy();
/**
* Removes the parameter with the specified name.
*
* @param name parameter name
*
* @return true if the parameter existed and has been removed, false else.
*/
boolean removeParameter(String name);
/**
* Returns a {@link Long} parameter value with the given name.
* If the parameter is not explicitly set, the default value is returned.
*
* @param name the parent name.
* @param defaultValue the default value.
*
* @return a {@link Long} that represents the value of the parameter.
*
* @see #setLongParameter(String, long)
*/
long getLongParameter(String name, long defaultValue);
/**
* Assigns a {@link Long} to the parameter with the given name
*
* @param name parameter name
* @param value parameter value
*/
HttpParams setLongParameter(String name, long value);
/**
* Returns an {@link Integer} parameter value with the given name.
* If the parameter is not explicitly set, the default value is returned.
*
* @param name the parent name.
* @param defaultValue the default value.
*
* @return a {@link Integer} that represents the value of the parameter.
*
* @see #setIntParameter(String, int)
*/
int getIntParameter(String name, int defaultValue);
/**
* Assigns an {@link Integer} to the parameter with the given name
*
* @param name parameter name
* @param value parameter value
*/
HttpParams setIntParameter(String name, int value);
/**
* Returns a {@link Double} parameter value with the given name.
* If the parameter is not explicitly set, the default value is returned.
*
* @param name the parent name.
* @param defaultValue the default value.
*
* @return a {@link Double} that represents the value of the parameter.
*
* @see #setDoubleParameter(String, double)
*/
double getDoubleParameter(String name, double defaultValue);
/**
* Assigns a {@link Double} to the parameter with the given name
*
* @param name parameter name
* @param value parameter value
*/
HttpParams setDoubleParameter(String name, double value);
/**
* Returns a {@link Boolean} parameter value with the given name.
* If the parameter is not explicitly set, the default value is returned.
*
* @param name the parent name.
* @param defaultValue the default value.
*
* @return a {@link Boolean} that represents the value of the parameter.
*
* @see #setBooleanParameter(String, boolean)
*/
boolean getBooleanParameter(String name, boolean defaultValue);
/**
* Assigns a {@link Boolean} to the parameter with the given name
*
* @param name parameter name
* @param value parameter value
*/
HttpParams setBooleanParameter(String name, boolean value);
/**
* Checks if a boolean parameter is set to <code>true</code>.
*
* @param name parameter name
*
* @return <tt>true</tt> if the parameter is set to value <tt>true</tt>,
* <tt>false</tt> if it is not set or set to <code>false</code>
*/
boolean isParameterTrue(String name);
/**
* Checks if a boolean parameter is not set or <code>false</code>.
*
* @param name parameter name
*
* @return <tt>true</tt> if the parameter is either not set or
* set to value <tt>false</tt>,
* <tt>false</tt> if it is set to <code>true</code>
*/
boolean isParameterFalse(String name);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
/**
* {@link HttpParams} implementation that delegates resolution of a parameter
* to the given default {@link HttpParams} instance if the parameter is not
* present in the local one. The state of the local collection can be mutated,
* whereas the default collection is treated as read-only.
*
* @since 4.0
*/
public final class DefaultedHttpParams extends AbstractHttpParams {
private final HttpParams local;
private final HttpParams defaults;
/**
* Create the defaulted set of HttpParams.
*
* @param local the mutable set of HttpParams
* @param defaults the default set of HttpParams, not mutated by this class
*/
public DefaultedHttpParams(final HttpParams local, final HttpParams defaults) {
super();
if (local == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.local = local;
this.defaults = defaults;
}
/**
* Creates a copy of the local collection with the same default
*
* @deprecated
*/
public HttpParams copy() {
HttpParams clone = this.local.copy();
return new DefaultedHttpParams(clone, this.defaults);
}
/**
* Retrieves the value of the parameter from the local collection and, if the
* parameter is not set locally, delegates its resolution to the default
* collection.
*/
public Object getParameter(final String name) {
Object obj = this.local.getParameter(name);
if (obj == null && this.defaults != null) {
obj = this.defaults.getParameter(name);
}
return obj;
}
/**
* Attempts to remove the parameter from the local collection. This method
* <i>does not</i> modify the default collection.
*/
public boolean removeParameter(final String name) {
return this.local.removeParameter(name);
}
/**
* Sets the parameter in the local collection. This method <i>does not</i>
* modify the default collection.
*/
public HttpParams setParameter(final String name, final Object value) {
return this.local.setParameter(name, value);
}
/**
*
* @return the default HttpParams collection
*/
public HttpParams getDefaults() {
return this.defaults;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
import org.apache.ogt.http.HttpVersion;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate HTTP protocol parameters using Java Beans
* conventions.
*
* @since 4.0
*/
public class HttpProtocolParamBean extends HttpAbstractParamBean {
public HttpProtocolParamBean (final HttpParams params) {
super(params);
}
public void setHttpElementCharset (final String httpElementCharset) {
HttpProtocolParams.setHttpElementCharset(params, httpElementCharset);
}
public void setContentCharset (final String contentCharset) {
HttpProtocolParams.setContentCharset(params, contentCharset);
}
public void setVersion (final HttpVersion version) {
HttpProtocolParams.setVersion(params, version);
}
public void setUserAgent (final String userAgent) {
HttpProtocolParams.setUserAgent(params, userAgent);
}
public void setUseExpectContinue (boolean useExpectContinue) {
HttpProtocolParams.setUseExpectContinue(params, useExpectContinue);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
/**
* @since 4.0
*/
public abstract class HttpAbstractParamBean {
protected final HttpParams params;
public HttpAbstractParamBean (final HttpParams params) {
if (params == null)
throw new IllegalArgumentException("HTTP parameters may not be null");
this.params = params;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
/**
* This is a Java Bean class that can be used to wrap an instance of
* {@link HttpParams} and manipulate HTTP connection parameters using Java Beans
* conventions.
*
* @since 4.0
*/
public class HttpConnectionParamBean extends HttpAbstractParamBean {
public HttpConnectionParamBean (final HttpParams params) {
super(params);
}
public void setSoTimeout (int soTimeout) {
HttpConnectionParams.setSoTimeout(params, soTimeout);
}
public void setTcpNoDelay (boolean tcpNoDelay) {
HttpConnectionParams.setTcpNoDelay(params, tcpNoDelay);
}
public void setSocketBufferSize (int socketBufferSize) {
HttpConnectionParams.setSocketBufferSize(params, socketBufferSize);
}
public void setLinger (int linger) {
HttpConnectionParams.setLinger(params, linger);
}
public void setConnectionTimeout (int connectionTimeout) {
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
}
public void setStaleCheckingEnabled (boolean staleCheckingEnabled) {
HttpConnectionParams.setStaleCheckingEnabled(params, staleCheckingEnabled);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
/**
* Defines parameter names for connections in HttpCore.
*
* @since 4.0
*/
public interface CoreConnectionPNames {
/**
* Defines the socket timeout (<code>SO_TIMEOUT</code>) in milliseconds,
* which is the timeout for waiting for data or, put differently,
* a maximum period inactivity between two consecutive data packets).
* A timeout value of zero is interpreted as an infinite timeout.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
* @see java.net.SocketOptions#SO_TIMEOUT
*/
public static final String SO_TIMEOUT = "http.socket.timeout";
/**
* Determines whether Nagle's algorithm is to be used. The Nagle's algorithm
* tries to conserve bandwidth by minimizing the number of segments that are
* sent. When applications wish to decrease network latency and increase
* performance, they can disable Nagle's algorithm (that is enable
* TCP_NODELAY). Data will be sent earlier, at the cost of an increase
* in bandwidth consumption.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
* @see java.net.SocketOptions#TCP_NODELAY
*/
public static final String TCP_NODELAY = "http.tcp.nodelay";
/**
* Determines the size of the internal socket buffer used to buffer data
* while receiving / transmitting HTTP messages.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String SOCKET_BUFFER_SIZE = "http.socket.buffer-size";
/**
* Sets SO_LINGER with the specified linger time in seconds. The maximum
* timeout value is platform specific. Value <code>0</code> implies that
* the option is disabled. Value <code>-1</code> implies that the JRE
* default is used. The setting only affects the socket close operation.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
* @see java.net.SocketOptions#SO_LINGER
*/
public static final String SO_LINGER = "http.socket.linger";
/**
* Defines whether the socket can be bound even though a previous connection is
* still in a timeout state.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
* @see java.net.Socket#setReuseAddress(boolean)
*
* @since 4.1
*/
public static final String SO_REUSEADDR = "http.socket.reuseaddr";
/**
* Determines the timeout in milliseconds until a connection is established.
* A timeout value of zero is interpreted as an infinite timeout.
* <p>
* Please note this parameter can only be applied to connections that
* are bound to a particular local address.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String CONNECTION_TIMEOUT = "http.connection.timeout";
/**
* Determines whether stale connection check is to be used. The stale
* connection check can cause up to 30 millisecond overhead per request and
* should be used only when appropriate. For performance critical
* operations this check should be disabled.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck";
/**
* Determines the maximum line length limit. If set to a positive value,
* any HTTP line exceeding this limit will cause an IOException. A negative
* or zero value will effectively disable the check.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String MAX_LINE_LENGTH = "http.connection.max-line-length";
/**
* Determines the maximum HTTP header count allowed. If set to a positive
* value, the number of HTTP headers received from the data stream exceeding
* this limit will cause an IOException. A negative or zero value will
* effectively disable the check.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*/
public static final String MAX_HEADER_COUNT = "http.connection.max-header-count";
/**
* Defines the size limit below which data chunks should be buffered in a session I/O buffer
* in order to minimize native method invocations on the underlying network socket.
* The optimal value of this parameter can be platform specific and defines a trade-off
* between performance of memory copy operations and that of native method invocation.
* <p>
* This parameter expects a value of type {@link Integer}.
* </p>
*
* @since 4.1
*/
public static final String MIN_CHUNK_LIMIT = "http.connection.min-chunk-limit";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
/**
* Utility class for accessing connection parameters in {@link HttpParams}.
*
* @since 4.0
*/
public final class HttpConnectionParams implements CoreConnectionPNames {
private HttpConnectionParams() {
super();
}
/**
* Obtains value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter.
* If not set, defaults to <code>0</code>.
*
* @param params HTTP parameters.
* @return SO_TIMEOUT.
*/
public static int getSoTimeout(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);
}
/**
* Sets value of the {@link CoreConnectionPNames#SO_TIMEOUT} parameter.
*
* @param params HTTP parameters.
* @param timeout SO_TIMEOUT.
*/
public static void setSoTimeout(final HttpParams params, int timeout) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
}
/**
* Obtains value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter.
* If not set, defaults to <code>false</code>.
*
* @param params HTTP parameters.
* @return SO_REUSEADDR.
*
* @since 4.1
*/
public static boolean getSoReuseaddr(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, false);
}
/**
* Sets value of the {@link CoreConnectionPNames#SO_REUSEADDR} parameter.
*
* @param params HTTP parameters.
* @param reuseaddr SO_REUSEADDR.
*
* @since 4.1
*/
public static void setSoReuseaddr(final HttpParams params, boolean reuseaddr) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter(CoreConnectionPNames.SO_REUSEADDR, reuseaddr);
}
/**
* Obtains value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter.
* If not set, defaults to <code>true</code>.
*
* @param params HTTP parameters.
* @return Nagle's algorithm flag
*/
public static boolean getTcpNoDelay(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter
(CoreConnectionPNames.TCP_NODELAY, true);
}
/**
* Sets value of the {@link CoreConnectionPNames#TCP_NODELAY} parameter.
*
* @param params HTTP parameters.
* @param value Nagle's algorithm flag
*/
public static void setTcpNoDelay(final HttpParams params, boolean value) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, value);
}
/**
* Obtains value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE}
* parameter. If not set, defaults to <code>-1</code>.
*
* @param params HTTP parameters.
* @return socket buffer size
*/
public static int getSocketBufferSize(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter
(CoreConnectionPNames.SOCKET_BUFFER_SIZE, -1);
}
/**
* Sets value of the {@link CoreConnectionPNames#SOCKET_BUFFER_SIZE}
* parameter.
*
* @param params HTTP parameters.
* @param size socket buffer size
*/
public static void setSocketBufferSize(final HttpParams params, int size) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, size);
}
/**
* Obtains value of the {@link CoreConnectionPNames#SO_LINGER} parameter.
* If not set, defaults to <code>-1</code>.
*
* @param params HTTP parameters.
* @return SO_LINGER.
*/
public static int getLinger(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter(CoreConnectionPNames.SO_LINGER, -1);
}
/**
* Sets value of the {@link CoreConnectionPNames#SO_LINGER} parameter.
*
* @param params HTTP parameters.
* @param value SO_LINGER.
*/
public static void setLinger(final HttpParams params, int value) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter(CoreConnectionPNames.SO_LINGER, value);
}
/**
* Obtains value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT}
* parameter. If not set, defaults to <code>0</code>.
*
* @param params HTTP parameters.
* @return connect timeout.
*/
public static int getConnectionTimeout(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getIntParameter
(CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
}
/**
* Sets value of the {@link CoreConnectionPNames#CONNECTION_TIMEOUT}
* parameter.
*
* @param params HTTP parameters.
* @param timeout connect timeout.
*/
public static void setConnectionTimeout(final HttpParams params, int timeout) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setIntParameter
(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
}
/**
* Obtains value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK}
* parameter. If not set, defaults to <code>true</code>.
*
* @param params HTTP parameters.
* @return stale connection check flag.
*/
public static boolean isStaleCheckingEnabled(final HttpParams params) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
return params.getBooleanParameter
(CoreConnectionPNames.STALE_CONNECTION_CHECK, true);
}
/**
* Sets value of the {@link CoreConnectionPNames#STALE_CONNECTION_CHECK}
* parameter.
*
* @param params HTTP parameters.
* @param value stale connection check flag.
*/
public static void setStaleCheckingEnabled(final HttpParams params, boolean value) {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
params.setBooleanParameter
(CoreConnectionPNames.STALE_CONNECTION_CHECK, value);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
import org.apache.ogt.http.params.HttpParams;
/**
* Abstract base class for parameter collections.
* Type specific setters and getters are mapped to the abstract,
* generic getters and setters.
*
* @since 4.0
*/
public abstract class AbstractHttpParams implements HttpParams {
/**
* Instantiates parameters.
*/
protected AbstractHttpParams() {
super();
}
public long getLongParameter(final String name, long defaultValue) {
Object param = getParameter(name);
if (param == null) {
return defaultValue;
}
return ((Long)param).longValue();
}
public HttpParams setLongParameter(final String name, long value) {
setParameter(name, new Long(value));
return this;
}
public int getIntParameter(final String name, int defaultValue) {
Object param = getParameter(name);
if (param == null) {
return defaultValue;
}
return ((Integer)param).intValue();
}
public HttpParams setIntParameter(final String name, int value) {
setParameter(name, new Integer(value));
return this;
}
public double getDoubleParameter(final String name, double defaultValue) {
Object param = getParameter(name);
if (param == null) {
return defaultValue;
}
return ((Double)param).doubleValue();
}
public HttpParams setDoubleParameter(final String name, double value) {
setParameter(name, new Double(value));
return this;
}
public boolean getBooleanParameter(final String name, boolean defaultValue) {
Object param = getParameter(name);
if (param == null) {
return defaultValue;
}
return ((Boolean)param).booleanValue();
}
public HttpParams setBooleanParameter(final String name, boolean value) {
setParameter(name, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
public boolean isParameterTrue(final String name) {
return getBooleanParameter(name, false);
}
public boolean isParameterFalse(final String name) {
return !getBooleanParameter(name, false);
}
} // class AbstractHttpParams
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
import org.apache.ogt.http.ProtocolVersion;
/**
* Defines parameter names for protocol execution in HttpCore.
*
* @since 4.0
*/
public interface CoreProtocolPNames {
/**
* Defines the {@link ProtocolVersion} used per default.
* <p>
* This parameter expects a value of type {@link ProtocolVersion}.
* </p>
*/
public static final String PROTOCOL_VERSION = "http.protocol.version";
/**
* Defines the charset to be used for encoding HTTP protocol elements.
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset";
/**
* Defines the charset to be used per default for encoding content body.
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String HTTP_CONTENT_CHARSET = "http.protocol.content-charset";
/**
* Defines the content of the <code>User-Agent</code> header.
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String USER_AGENT = "http.useragent";
/**
* Defines the content of the <code>Server</code> header.
* <p>
* This parameter expects a value of type {@link String}.
* </p>
*/
public static final String ORIGIN_SERVER = "http.origin-server";
/**
* Defines whether responses with an invalid <code>Transfer-Encoding</code>
* header should be rejected.
* <p>
* This parameter expects a value of type {@link Boolean}.
* </p>
*/
public static final String STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding";
/**
* <p>
* Activates 'Expect: 100-Continue' handshake for the
* entity enclosing methods. The purpose of the 'Expect: 100-Continue'
* handshake is to allow a client that is sending a request message with
* a request body to determine if the origin server is willing to
* accept the request (based on the request headers) before the client
* sends the request body.
* </p>
*
* <p>
* The use of the 'Expect: 100-continue' handshake can result in
* a noticeable performance improvement for entity enclosing requests
* (such as POST and PUT) that require the target server's
* authentication.
* </p>
*
* <p>
* 'Expect: 100-continue' handshake should be used with
* caution, as it may cause problems with HTTP servers and
* proxies that do not support HTTP/1.1 protocol.
* </p>
*
* This parameter expects a value of type {@link Boolean}.
*/
public static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue";
/**
* <p>
* Defines the maximum period of time in milliseconds the client should spend
* waiting for a 100-continue response.
* </p>
*
* This parameter expects a value of type {@link Integer}.
*/
public static final String WAIT_FOR_CONTINUE = "http.protocol.wait-for-continue";
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.params;
import java.io.Serializable;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.ogt.http.params.HttpParams;
/**
* Default implementation of {@link HttpParams} interface.
* <p>
* Please note access to the internal structures of this class is not
* synchronized and therefore this class may be thread-unsafe.
*
* @since 4.0
*/
public class BasicHttpParams extends AbstractHttpParams implements Serializable, Cloneable {
private static final long serialVersionUID = -7086398485908701455L;
/** Map of HTTP parameters that this collection contains. */
private final HashMap parameters = new HashMap();
public BasicHttpParams() {
super();
}
public Object getParameter(final String name) {
return this.parameters.get(name);
}
public HttpParams setParameter(final String name, final Object value) {
this.parameters.put(name, value);
return this;
}
public boolean removeParameter(String name) {
//this is to avoid the case in which the key has a null value
if (this.parameters.containsKey(name)) {
this.parameters.remove(name);
return true;
} else {
return false;
}
}
/**
* Assigns the value to all the parameter with the given names
*
* @param names array of parameter names
* @param value parameter value
*/
public void setParameters(final String[] names, final Object value) {
for (int i = 0; i < names.length; i++) {
setParameter(names[i], value);
}
}
/**
* Is the parameter set?
* <p>
* Uses {@link #getParameter(String)} (which is overrideable) to
* fetch the parameter value, if any.
* <p>
* Also @see {@link #isParameterSetLocally(String)}
*
* @param name parameter name
* @return true if parameter is defined and non-null
*/
public boolean isParameterSet(final String name) {
return getParameter(name) != null;
}
/**
* Is the parameter set in this object?
* <p>
* The parameter value is fetched directly.
* <p>
* Also @see {@link #isParameterSet(String)}
*
* @param name parameter name
* @return true if parameter is defined and non-null
*/
public boolean isParameterSetLocally(final String name) {
return this.parameters.get(name) != null;
}
/**
* Removes all parameters from this collection.
*/
public void clear() {
this.parameters.clear();
}
/**
* Creates a copy of these parameters.
* This implementation calls {@link #clone()}.
*
* @return a new set of params holding a copy of the
* <i>local</i> parameters in this object.
*
* @deprecated
* @throws UnsupportedOperationException if the clone() fails
*/
public HttpParams copy() {
try {
return (HttpParams) clone();
} catch (CloneNotSupportedException ex) {
throw new UnsupportedOperationException("Cloning not supported");
}
}
/**
* Clones the instance.
* Uses {@link #copyParams(HttpParams)} to copy the parameters.
*/
public Object clone() throws CloneNotSupportedException {
BasicHttpParams clone = (BasicHttpParams) super.clone();
copyParams(clone);
return clone;
}
protected void copyParams(HttpParams target) {
Iterator iter = parameters.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry me = (Map.Entry) iter.next();
if (me.getKey() instanceof String)
target.setParameter((String)me.getKey(), me.getValue());
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* A name / value pair parameter used as an element of HTTP messages.
* <pre>
* parameter = attribute "=" value
* attribute = token
* value = token | quoted-string
* </pre>
*
*
* @since 4.0
*/
public interface NameValuePair {
String getName();
String getValue();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import org.apache.ogt.http.HttpConnectionMetrics;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestFactory;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.entity.EntityDeserializer;
import org.apache.ogt.http.impl.entity.EntitySerializer;
import org.apache.ogt.http.impl.entity.LaxContentLengthStrategy;
import org.apache.ogt.http.impl.entity.StrictContentLengthStrategy;
import org.apache.ogt.http.impl.io.HttpRequestParser;
import org.apache.ogt.http.impl.io.HttpResponseWriter;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.HttpMessageParser;
import org.apache.ogt.http.io.HttpMessageWriter;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.params.HttpParams;
/**
* Abstract server-side HTTP connection capable of transmitting and receiving
* data using arbitrary {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractHttpServerConnection implements HttpServerConnection {
private final EntitySerializer entityserializer;
private final EntityDeserializer entitydeserializer;
private SessionInputBuffer inbuffer = null;
private SessionOutputBuffer outbuffer = null;
private EofSensor eofSensor = null;
private HttpMessageParser requestParser = null;
private HttpMessageWriter responseWriter = null;
private HttpConnectionMetricsImpl metrics = null;
/**
* Creates an instance of this class.
* <p>
* This constructor will invoke {@link #createEntityDeserializer()}
* and {@link #createEntitySerializer()} methods in order to initialize
* HTTP entity serializer and deserializer implementations for this
* connection.
*/
public AbstractHttpServerConnection() {
super();
this.entityserializer = createEntitySerializer();
this.entitydeserializer = createEntityDeserializer();
}
/**
* Asserts if the connection is open.
*
* @throws IllegalStateException if the connection is not open.
*/
protected abstract void assertOpen() throws IllegalStateException;
/**
* Creates an instance of {@link EntityDeserializer} with the
* {@link LaxContentLengthStrategy} implementation to be used for
* de-serializing entities received over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntityDeserializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity deserializer
*/
protected EntityDeserializer createEntityDeserializer() {
return new EntityDeserializer(new LaxContentLengthStrategy());
}
/**
* Creates an instance of {@link EntitySerializer} with the
* {@link StrictContentLengthStrategy} implementation to be used for
* serializing HTTP entities sent over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntitySerializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity serialzier.
*/
protected EntitySerializer createEntitySerializer() {
return new EntitySerializer(new StrictContentLengthStrategy());
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* for creating {@link HttpRequest} objects received by over this
* connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link HttpMessageParser} to be used for parsing
* HTTP requests received over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageParser} interface or
* to pass a different implementation of {@link LineParser} to the
* the default implementation {@link HttpRequestParser}.
*
* @param buffer the session input buffer.
* @param requestFactory the HTTP request factory.
* @param params HTTP parameters.
* @return HTTP message parser.
*/
protected HttpMessageParser createRequestParser(
final SessionInputBuffer buffer,
final HttpRequestFactory requestFactory,
final HttpParams params) {
return new HttpRequestParser(buffer, null, requestFactory, params);
}
/**
* Creates an instance of {@link HttpMessageWriter} to be used for
* writing out HTTP responses sent over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageWriter} interface or
* to pass a different implementation of {@link LineFormatter} to the
* the default implementation {@link HttpResponseWriter}.
*
* @param buffer the session output buffer
* @param params HTTP parameters
* @return HTTP message writer
*/
protected HttpMessageWriter createResponseWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new HttpResponseWriter(buffer, null, params);
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
/**
* Initializes this connection object with {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} instances to be used for sending and
* receiving data. These session buffers can be bound to any arbitrary
* physical output medium.
* <p>
* This method will invoke {@link #createHttpRequestFactory},
* {@link #createRequestParser(SessionInputBuffer, HttpRequestFactory, HttpParams)}
* and {@link #createResponseWriter(SessionOutputBuffer, HttpParams)}
* methods to initialize HTTP request parser and response writer for this
* connection.
*
* @param inbuffer the session input buffer.
* @param outbuffer the session output buffer.
* @param params HTTP parameters.
*/
protected void init(
final SessionInputBuffer inbuffer,
final SessionOutputBuffer outbuffer,
final HttpParams params) {
if (inbuffer == null) {
throw new IllegalArgumentException("Input session buffer may not be null");
}
if (outbuffer == null) {
throw new IllegalArgumentException("Output session buffer may not be null");
}
this.inbuffer = inbuffer;
this.outbuffer = outbuffer;
if (inbuffer instanceof EofSensor) {
this.eofSensor = (EofSensor) inbuffer;
}
this.requestParser = createRequestParser(
inbuffer,
createHttpRequestFactory(),
params);
this.responseWriter = createResponseWriter(
outbuffer, params);
this.metrics = createConnectionMetrics(
inbuffer.getMetrics(),
outbuffer.getMetrics());
}
public HttpRequest receiveRequestHeader()
throws HttpException, IOException {
assertOpen();
HttpRequest request = (HttpRequest) this.requestParser.parse();
this.metrics.incrementRequestCount();
return request;
}
public void receiveRequestEntity(final HttpEntityEnclosingRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, request);
request.setEntity(entity);
}
protected void doFlush() throws IOException {
this.outbuffer.flush();
}
public void flush() throws IOException {
assertOpen();
doFlush();
}
public void sendResponseHeader(final HttpResponse response)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertOpen();
this.responseWriter.write(response);
if (response.getStatusLine().getStatusCode() >= 200) {
this.metrics.incrementResponseCount();
}
}
public void sendResponseEntity(final HttpResponse response)
throws HttpException, IOException {
if (response.getEntity() == null) {
return;
}
this.entityserializer.serialize(
this.outbuffer,
response,
response.getEntity());
}
protected boolean isEof() {
return this.eofSensor != null && this.eofSensor.isEof();
}
public boolean isStale() {
if (!isOpen()) {
return true;
}
if (isEof()) {
return true;
}
try {
this.inbuffer.isDataAvailable(1);
return isEof();
} catch (IOException ex) {
return true;
}
}
public HttpConnectionMetrics getMetrics() {
return this.metrics;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.impl.io.SocketInputBuffer;
import org.apache.ogt.http.impl.io.SocketOutputBuffer;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Implementation of a server-side HTTP connection that can be bound to a
* network Socket in order to receive and transmit data.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public class SocketHttpServerConnection extends
AbstractHttpServerConnection implements HttpInetConnection {
private volatile boolean open;
private volatile Socket socket = null;
public SocketHttpServerConnection() {
super();
}
protected void assertNotOpen() {
if (this.open) {
throw new IllegalStateException("Connection is already open");
}
}
protected void assertOpen() {
if (!this.open) {
throw new IllegalStateException("Connection is not open");
}
}
/**
* @deprecated Use {@link #createSessionInputBuffer(Socket, int, HttpParams)}
*/
protected SessionInputBuffer createHttpDataReceiver(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return createSessionInputBuffer(socket, buffersize, params);
}
/**
* @deprecated Use {@link #createSessionOutputBuffer(Socket, int, HttpParams)}
*/
protected SessionOutputBuffer createHttpDataTransmitter(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return createSessionOutputBuffer(socket, buffersize, params);
}
/**
* Creates an instance of {@link SocketInputBuffer} to be used for
* receiving data from the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SessionInputBuffer} interface.
*
* @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session input buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionInputBuffer createSessionInputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketInputBuffer(socket, buffersize, params);
}
/**
* Creates an instance of {@link SessionOutputBuffer} to be used for
* sending data to the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SocketOutputBuffer} interface.
*
* @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session output buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionOutputBuffer createSessionOutputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketOutputBuffer(socket, buffersize, params);
}
/**
* Binds this connection to the given {@link Socket}. This socket will be
* used by the connection to send and receive data.
* <p>
* This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
* and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
* to create session input / output buffers bound to this socket and then
* will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
* method to pass references to those buffers to the underlying HTTP message
* parser and formatter.
* <p>
* After this method's execution the connection status will be reported
* as open and the {@link #isOpen()} will return <code>true</code>.
*
* @param socket the socket.
* @param params HTTP parameters.
* @throws IOException in case of an I/O error.
*/
protected void bind(final Socket socket, final HttpParams params) throws IOException {
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.socket = socket;
int buffersize = HttpConnectionParams.getSocketBufferSize(params);
init(
createHttpDataReceiver(socket, buffersize, params),
createHttpDataTransmitter(socket, buffersize, params),
params);
this.open = true;
}
protected Socket getSocket() {
return this.socket;
}
public boolean isOpen() {
return this.open;
}
public InetAddress getLocalAddress() {
if (this.socket != null) {
return this.socket.getLocalAddress();
} else {
return null;
}
}
public int getLocalPort() {
if (this.socket != null) {
return this.socket.getLocalPort();
} else {
return -1;
}
}
public InetAddress getRemoteAddress() {
if (this.socket != null) {
return this.socket.getInetAddress();
} else {
return null;
}
}
public int getRemotePort() {
if (this.socket != null) {
return this.socket.getPort();
} else {
return -1;
}
}
public void setSocketTimeout(int timeout) {
assertOpen();
if (this.socket != null) {
try {
this.socket.setSoTimeout(timeout);
} catch (SocketException ignore) {
// It is not quite clear from the Sun's documentation if there are any
// other legitimate cases for a socket exception to be thrown when setting
// SO_TIMEOUT besides the socket being already closed
}
}
}
public int getSocketTimeout() {
if (this.socket != null) {
try {
return this.socket.getSoTimeout();
} catch (SocketException ignore) {
return -1;
}
} else {
return -1;
}
}
public void shutdown() throws IOException {
this.open = false;
Socket tmpsocket = this.socket;
if (tmpsocket != null) {
tmpsocket.close();
}
}
public void close() throws IOException {
if (!this.open) {
return;
}
this.open = false;
this.open = false;
Socket sock = this.socket;
try {
doFlush();
try {
try {
sock.shutdownOutput();
} catch (IOException ignore) {
}
try {
sock.shutdownInput();
} catch (IOException ignore) {
}
} catch (UnsupportedOperationException ignore) {
// if one isn't supported, the other one isn't either
}
} finally {
sock.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import java.net.Socket;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Default implementation of a server-side HTTP connection.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultHttpServerConnection extends SocketHttpServerConnection {
public DefaultHttpServerConnection() {
super();
}
public void bind(final Socket socket, final HttpParams params) throws IOException {
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
assertNotOpen();
socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
int linger = HttpConnectionParams.getLinger(params);
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
super.bind(socket, params);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
if (isOpen()) {
buffer.append(getRemotePort());
} else {
buffer.append("closed");
}
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.entity;
import java.io.IOException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.entity.BasicHttpEntity;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.io.ChunkedInputStream;
import org.apache.ogt.http.impl.io.ContentLengthInputStream;
import org.apache.ogt.http.impl.io.IdentityInputStream;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.protocol.HTTP;
/**
* HTTP entity deserializer.
* <p>
* This entity deserializer supports "chunked" and "identitiy" transfer-coding
* and content length delimited content.
* <p>
* This class relies on a specific implementation of
* {@link ContentLengthStrategy} to determine the content length or transfer
* encoding of the entity.
* <p>
* This class generates an instance of {@link HttpEntity} based on
* properties of the message. The content of the entity will be decoded
* transparently for the consumer.
*
* @since 4.0
*/
public class EntityDeserializer {
private final ContentLengthStrategy lenStrategy;
public EntityDeserializer(final ContentLengthStrategy lenStrategy) {
super();
if (lenStrategy == null) {
throw new IllegalArgumentException("Content length strategy may not be null");
}
this.lenStrategy = lenStrategy;
}
/**
* Creates a {@link BasicHttpEntity} based on properties of the given
* message. The content of the entity is created by wrapping
* {@link SessionInputBuffer} with a content decoder depending on the
* transfer mechanism used by the message.
* <p>
* This method is called by the public
* {@link #deserialize(SessionInputBuffer, HttpMessage)}.
*
* @param inbuffer the session input buffer.
* @param message the message.
* @return HTTP entity.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
protected BasicHttpEntity doDeserialize(
final SessionInputBuffer inbuffer,
final HttpMessage message) throws HttpException, IOException {
BasicHttpEntity entity = new BasicHttpEntity();
long len = this.lenStrategy.determineLength(message);
if (len == ContentLengthStrategy.CHUNKED) {
entity.setChunked(true);
entity.setContentLength(-1);
entity.setContent(new ChunkedInputStream(inbuffer));
} else if (len == ContentLengthStrategy.IDENTITY) {
entity.setChunked(false);
entity.setContentLength(-1);
entity.setContent(new IdentityInputStream(inbuffer));
} else {
entity.setChunked(false);
entity.setContentLength(len);
entity.setContent(new ContentLengthInputStream(inbuffer, len));
}
Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE);
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader);
}
Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING);
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader);
}
return entity;
}
/**
* Creates an {@link HttpEntity} based on properties of the given message.
* The content of the entity is created by wrapping
* {@link SessionInputBuffer} with a content decoder depending on the
* transfer mechanism used by the message.
* <p>
* The content of the entity is NOT retrieved by this method.
*
* @param inbuffer the session input buffer.
* @param message the message.
* @return HTTP entity.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
public HttpEntity deserialize(
final SessionInputBuffer inbuffer,
final HttpMessage message) throws HttpException, IOException {
if (inbuffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
return doDeserialize(inbuffer, message);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.entity;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.io.ChunkedOutputStream;
import org.apache.ogt.http.impl.io.ContentLengthOutputStream;
import org.apache.ogt.http.impl.io.IdentityOutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* HTTP entity serializer.
* <p>
* This entity serializer currently supports "chunked" and "identitiy"
* transfer-coding and content length delimited content.
* <p>
* This class relies on a specific implementation of
* {@link ContentLengthStrategy} to determine the content length or transfer
* encoding of the entity.
* <p>
* This class writes out the content of {@link HttpEntity} to the data stream
* using a transfer coding based on properties on the HTTP message.
*
* @since 4.0
*/
public class EntitySerializer {
private final ContentLengthStrategy lenStrategy;
public EntitySerializer(final ContentLengthStrategy lenStrategy) {
super();
if (lenStrategy == null) {
throw new IllegalArgumentException("Content length strategy may not be null");
}
this.lenStrategy = lenStrategy;
}
/**
* Creates a transfer codec based on properties of the given HTTP message
* and returns {@link OutputStream} instance that transparently encodes
* output data as it is being written out to the output stream.
* <p>
* This method is called by the public
* {@link #serialize(SessionOutputBuffer, HttpMessage, HttpEntity)}.
*
* @param outbuffer the session output buffer.
* @param message the HTTP message.
* @return output stream.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
protected OutputStream doSerialize(
final SessionOutputBuffer outbuffer,
final HttpMessage message) throws HttpException, IOException {
long len = this.lenStrategy.determineLength(message);
if (len == ContentLengthStrategy.CHUNKED) {
return new ChunkedOutputStream(outbuffer);
} else if (len == ContentLengthStrategy.IDENTITY) {
return new IdentityOutputStream(outbuffer);
} else {
return new ContentLengthOutputStream(outbuffer, len);
}
}
/**
* Writes out the content of the given HTTP entity to the session output
* buffer based on properties of the given HTTP message.
*
* @param outbuffer the output session buffer.
* @param message the HTTP message.
* @param entity the HTTP entity to be written out.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
public void serialize(
final SessionOutputBuffer outbuffer,
final HttpMessage message,
final HttpEntity entity) throws HttpException, IOException {
if (outbuffer == null) {
throw new IllegalArgumentException("Session output buffer may not be null");
}
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
OutputStream outstream = doSerialize(outbuffer, message);
entity.writeTo(outstream);
outstream.close();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.entity;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HTTP;
/**
* The lax implementation of the content length strategy. This class will ignore
* unrecognized transfer encodings and malformed <code>Content-Length</code>
* header values if the {@link CoreProtocolPNames#STRICT_TRANSFER_ENCODING}
* parameter of the given message is not set or set to <code>false</code>.
* <p>
* This class recognizes "chunked" and "identitiy" transfer-coding only.
* <p>
* The following parameters can be used to customize the behavior of this class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* </ul>
*
* @since 4.0
*/
public class LaxContentLengthStrategy implements ContentLengthStrategy {
public LaxContentLengthStrategy() {
super();
}
public long determineLength(final HttpMessage message) throws HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
HttpParams params = message.getParams();
boolean strict = params.isParameterTrue(CoreProtocolPNames.STRICT_TRANSFER_ENCODING);
Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
// We use Transfer-Encoding if present and ignore Content-Length.
// RFC2616, 4.4 item number 3
if (transferEncodingHeader != null) {
HeaderElement[] encodings = null;
try {
encodings = transferEncodingHeader.getElements();
} catch (ParseException px) {
throw new ProtocolException
("Invalid Transfer-Encoding header value: " +
transferEncodingHeader, px);
}
if (strict) {
// Currently only chunk and identity are supported
for (int i = 0; i < encodings.length; i++) {
String encoding = encodings[i].getName();
if (encoding != null && encoding.length() > 0
&& !encoding.equalsIgnoreCase(HTTP.CHUNK_CODING)
&& !encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) {
throw new ProtocolException("Unsupported transfer encoding: " + encoding);
}
}
}
// The chunked encoding must be the last one applied RFC2616, 14.41
int len = encodings.length;
if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
return IDENTITY;
} else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase(
encodings[len - 1].getName()))) {
return CHUNKED;
} else {
if (strict) {
throw new ProtocolException("Chunk-encoding must be the last one applied");
}
return IDENTITY;
}
} else if (contentLengthHeader != null) {
long contentlen = -1;
Header[] headers = message.getHeaders(HTTP.CONTENT_LEN);
if (strict && headers.length > 1) {
throw new ProtocolException("Multiple content length headers");
}
for (int i = headers.length - 1; i >= 0; i--) {
Header header = headers[i];
try {
contentlen = Long.parseLong(header.getValue());
break;
} catch (NumberFormatException e) {
if (strict) {
throw new ProtocolException("Invalid content length: " + header.getValue());
}
}
// See if we can have better luck with another header, if present
}
if (contentlen >= 0) {
return contentlen;
} else {
return IDENTITY;
}
} else {
return IDENTITY;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.entity;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.protocol.HTTP;
/**
* The strict implementation of the content length strategy. This class
* will throw {@link ProtocolException} if it encounters an unsupported
* transfer encoding or a malformed <code>Content-Length</code> header
* value.
* <p>
* This class recognizes "chunked" and "identitiy" transfer-coding only.
*
* @since 4.0
*/
public class StrictContentLengthStrategy implements ContentLengthStrategy {
public StrictContentLengthStrategy() {
super();
}
public long determineLength(final HttpMessage message) throws HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
// Although Transfer-Encoding is specified as a list, in practice
// it is either missing or has the single value "chunked". So we
// treat it as a single-valued header here.
Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
if (transferEncodingHeader != null) {
String s = transferEncodingHeader.getValue();
if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) {
if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
throw new ProtocolException(
"Chunked transfer encoding not allowed for " +
message.getProtocolVersion());
}
return CHUNKED;
} else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) {
return IDENTITY;
} else {
throw new ProtocolException(
"Unsupported transfer encoding: " + s);
}
} else if (contentLengthHeader != null) {
String s = contentLengthHeader.getValue();
try {
long len = Long.parseLong(s);
return len;
} catch (NumberFormatException e) {
throw new ProtocolException("Invalid content length: " + s);
}
} else {
return IDENTITY;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.util.Locale;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.ReasonPhraseCatalog;
/**
* English reason phrases for HTTP status codes.
* All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and
* RFC2518 (WebDAV) are supported.
*
* @since 4.0
*/
public class EnglishReasonPhraseCatalog implements ReasonPhraseCatalog {
// static array with english reason phrases defined below
/**
* The default instance of this catalog.
* This catalog is thread safe, so there typically
* is no need to create other instances.
*/
public final static EnglishReasonPhraseCatalog INSTANCE =
new EnglishReasonPhraseCatalog();
/**
* Restricted default constructor, for derived classes.
* If you need an instance of this class, use {@link #INSTANCE INSTANCE}.
*/
protected EnglishReasonPhraseCatalog() {
// no body
}
/**
* Obtains the reason phrase for a status code.
*
* @param status the status code, in the range 100-599
* @param loc ignored
*
* @return the reason phrase, or <code>null</code>
*/
public String getReason(int status, Locale loc) {
if ((status < 100) || (status >= 600)) {
throw new IllegalArgumentException
("Unknown category for status code " + status + ".");
}
final int category = status / 100;
final int subcode = status - 100*category;
String reason = null;
if (REASON_PHRASES[category].length > subcode)
reason = REASON_PHRASES[category][subcode];
return reason;
}
/** Reason phrases lookup table. */
private static final String[][] REASON_PHRASES = new String[][]{
null,
new String[3], // 1xx
new String[8], // 2xx
new String[8], // 3xx
new String[25], // 4xx
new String[8] // 5xx
};
/**
* Stores the given reason phrase, by status code.
* Helper method to initialize the static lookup table.
*
* @param status the status code for which to define the phrase
* @param reason the reason phrase for this status code
*/
private static void setReason(int status, String reason) {
final int category = status / 100;
final int subcode = status - 100*category;
REASON_PHRASES[category][subcode] = reason;
}
// ----------------------------------------------------- Static Initializer
/** Set up status code to "reason phrase" map. */
static {
// HTTP 1.0 Server status codes -- see RFC 1945
setReason(HttpStatus.SC_OK,
"OK");
setReason(HttpStatus.SC_CREATED,
"Created");
setReason(HttpStatus.SC_ACCEPTED,
"Accepted");
setReason(HttpStatus.SC_NO_CONTENT,
"No Content");
setReason(HttpStatus.SC_MOVED_PERMANENTLY,
"Moved Permanently");
setReason(HttpStatus.SC_MOVED_TEMPORARILY,
"Moved Temporarily");
setReason(HttpStatus.SC_NOT_MODIFIED,
"Not Modified");
setReason(HttpStatus.SC_BAD_REQUEST,
"Bad Request");
setReason(HttpStatus.SC_UNAUTHORIZED,
"Unauthorized");
setReason(HttpStatus.SC_FORBIDDEN,
"Forbidden");
setReason(HttpStatus.SC_NOT_FOUND,
"Not Found");
setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR,
"Internal Server Error");
setReason(HttpStatus.SC_NOT_IMPLEMENTED,
"Not Implemented");
setReason(HttpStatus.SC_BAD_GATEWAY,
"Bad Gateway");
setReason(HttpStatus.SC_SERVICE_UNAVAILABLE,
"Service Unavailable");
// HTTP 1.1 Server status codes -- see RFC 2048
setReason(HttpStatus.SC_CONTINUE,
"Continue");
setReason(HttpStatus.SC_TEMPORARY_REDIRECT,
"Temporary Redirect");
setReason(HttpStatus.SC_METHOD_NOT_ALLOWED,
"Method Not Allowed");
setReason(HttpStatus.SC_CONFLICT,
"Conflict");
setReason(HttpStatus.SC_PRECONDITION_FAILED,
"Precondition Failed");
setReason(HttpStatus.SC_REQUEST_TOO_LONG,
"Request Too Long");
setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG,
"Request-URI Too Long");
setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE,
"Unsupported Media Type");
setReason(HttpStatus.SC_MULTIPLE_CHOICES,
"Multiple Choices");
setReason(HttpStatus.SC_SEE_OTHER,
"See Other");
setReason(HttpStatus.SC_USE_PROXY,
"Use Proxy");
setReason(HttpStatus.SC_PAYMENT_REQUIRED,
"Payment Required");
setReason(HttpStatus.SC_NOT_ACCEPTABLE,
"Not Acceptable");
setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED,
"Proxy Authentication Required");
setReason(HttpStatus.SC_REQUEST_TIMEOUT,
"Request Timeout");
setReason(HttpStatus.SC_SWITCHING_PROTOCOLS,
"Switching Protocols");
setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION,
"Non Authoritative Information");
setReason(HttpStatus.SC_RESET_CONTENT,
"Reset Content");
setReason(HttpStatus.SC_PARTIAL_CONTENT,
"Partial Content");
setReason(HttpStatus.SC_GATEWAY_TIMEOUT,
"Gateway Timeout");
setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED,
"Http Version Not Supported");
setReason(HttpStatus.SC_GONE,
"Gone");
setReason(HttpStatus.SC_LENGTH_REQUIRED,
"Length Required");
setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE,
"Requested Range Not Satisfiable");
setReason(HttpStatus.SC_EXPECTATION_FAILED,
"Expectation Failed");
// WebDAV Server-specific status codes
setReason(HttpStatus.SC_PROCESSING,
"Processing");
setReason(HttpStatus.SC_MULTI_STATUS,
"Multi-Status");
setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY,
"Unprocessable Entity");
setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE,
"Insufficient Space On Resource");
setReason(HttpStatus.SC_METHOD_FAILURE,
"Method Failure");
setReason(HttpStatus.SC_LOCKED,
"Locked");
setReason(HttpStatus.SC_INSUFFICIENT_STORAGE,
"Insufficient Storage");
setReason(HttpStatus.SC_FAILED_DEPENDENCY,
"Failed Dependency");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestFactory;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.RequestLine;
import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.ogt.http.message.BasicHttpRequest;
/**
* Default factory for creating {@link HttpRequest} objects.
*
* @since 4.0
*/
public class DefaultHttpRequestFactory implements HttpRequestFactory {
private static final String[] RFC2616_COMMON_METHODS = {
"GET"
};
private static final String[] RFC2616_ENTITY_ENC_METHODS = {
"POST",
"PUT"
};
private static final String[] RFC2616_SPECIAL_METHODS = {
"HEAD",
"OPTIONS",
"DELETE",
"TRACE",
"CONNECT"
};
public DefaultHttpRequestFactory() {
super();
}
private static boolean isOneOf(final String[] methods, final String method) {
for (int i = 0; i < methods.length; i++) {
if (methods[i].equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
public HttpRequest newHttpRequest(final RequestLine requestline)
throws MethodNotSupportedException {
if (requestline == null) {
throw new IllegalArgumentException("Request line may not be null");
}
String method = requestline.getMethod();
if (isOneOf(RFC2616_COMMON_METHODS, method)) {
return new BasicHttpRequest(requestline);
} else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
return new BasicHttpEntityEnclosingRequest(requestline);
} else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) {
return new BasicHttpRequest(requestline);
} else {
throw new MethodNotSupportedException(method + " method not supported");
}
}
public HttpRequest newHttpRequest(final String method, final String uri)
throws MethodNotSupportedException {
if (isOneOf(RFC2616_COMMON_METHODS, method)) {
return new BasicHttpRequest(method, uri);
} else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
return new BasicHttpEntityEnclosingRequest(method, uri);
} else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) {
return new BasicHttpRequest(method, uri);
} else {
throw new MethodNotSupportedException(method
+ " method not supported");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.impl.io.SocketInputBuffer;
import org.apache.ogt.http.impl.io.SocketOutputBuffer;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Implementation of a client-side HTTP connection that can be bound to an
* arbitrary {@link Socket} for receiving data from and transmitting data to
* a remote server.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public class SocketHttpClientConnection
extends AbstractHttpClientConnection implements HttpInetConnection {
private volatile boolean open;
private volatile Socket socket = null;
public SocketHttpClientConnection() {
super();
}
protected void assertNotOpen() {
if (this.open) {
throw new IllegalStateException("Connection is already open");
}
}
protected void assertOpen() {
if (!this.open) {
throw new IllegalStateException("Connection is not open");
}
}
/**
* Creates an instance of {@link SocketInputBuffer} to be used for
* receiving data from the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SessionInputBuffer} interface.
*
* @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session input buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionInputBuffer createSessionInputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketInputBuffer(socket, buffersize, params);
}
/**
* Creates an instance of {@link SessionOutputBuffer} to be used for
* sending data to the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SocketOutputBuffer} interface.
*
* @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session output buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionOutputBuffer createSessionOutputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketOutputBuffer(socket, buffersize, params);
}
/**
* Binds this connection to the given {@link Socket}. This socket will be
* used by the connection to send and receive data.
* <p>
* This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
* and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
* to create session input / output buffers bound to this socket and then
* will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
* method to pass references to those buffers to the underlying HTTP message
* parser and formatter.
* <p>
* After this method's execution the connection status will be reported
* as open and the {@link #isOpen()} will return <code>true</code>.
*
* @param socket the socket.
* @param params HTTP parameters.
* @throws IOException in case of an I/O error.
*/
protected void bind(
final Socket socket,
final HttpParams params) throws IOException {
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.socket = socket;
int buffersize = HttpConnectionParams.getSocketBufferSize(params);
init(
createSessionInputBuffer(socket, buffersize, params),
createSessionOutputBuffer(socket, buffersize, params),
params);
this.open = true;
}
public boolean isOpen() {
return this.open;
}
protected Socket getSocket() {
return this.socket;
}
public InetAddress getLocalAddress() {
if (this.socket != null) {
return this.socket.getLocalAddress();
} else {
return null;
}
}
public int getLocalPort() {
if (this.socket != null) {
return this.socket.getLocalPort();
} else {
return -1;
}
}
public InetAddress getRemoteAddress() {
if (this.socket != null) {
return this.socket.getInetAddress();
} else {
return null;
}
}
public int getRemotePort() {
if (this.socket != null) {
return this.socket.getPort();
} else {
return -1;
}
}
public void setSocketTimeout(int timeout) {
assertOpen();
if (this.socket != null) {
try {
this.socket.setSoTimeout(timeout);
} catch (SocketException ignore) {
// It is not quite clear from the Sun's documentation if there are any
// other legitimate cases for a socket exception to be thrown when setting
// SO_TIMEOUT besides the socket being already closed
}
}
}
public int getSocketTimeout() {
if (this.socket != null) {
try {
return this.socket.getSoTimeout();
} catch (SocketException ignore) {
return -1;
}
} else {
return -1;
}
}
public void shutdown() throws IOException {
this.open = false;
Socket tmpsocket = this.socket;
if (tmpsocket != null) {
tmpsocket.close();
}
}
public void close() throws IOException {
if (!this.open) {
return;
}
this.open = false;
Socket sock = this.socket;
try {
doFlush();
try {
try {
sock.shutdownOutput();
} catch (IOException ignore) {
}
try {
sock.shutdownInput();
} catch (IOException ignore) {
}
} catch (UnsupportedOperationException ignore) {
// if one isn't supported, the other one isn't either
}
} finally {
sock.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HeaderIterator;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.TokenIterator;
import org.apache.ogt.http.message.BasicTokenIterator;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of a strategy deciding about connection re-use.
* The default implementation first checks some basics, for example
* whether the connection is still open or whether the end of the
* request entity can be determined without closing the connection.
* If these checks pass, the tokens in the <code>Connection</code> header will
* be examined. In the absence of a <code>Connection</code> header, the
* non-standard but commonly used <code>Proxy-Connection</code> header takes
* it's role. A token <code>close</code> indicates that the connection cannot
* be reused. If there is no such token, a token <code>keep-alive</code>
* indicates that the connection should be re-used. If neither token is found,
* or if there are no <code>Connection</code> headers, the default policy for
* the HTTP version is applied. Since <code>HTTP/1.1</code>, connections are
* re-used by default. Up until <code>HTTP/1.0</code>, connections are not
* re-used by default.
*
* @since 4.0
*/
public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
public DefaultConnectionReuseStrategy() {
super();
}
// see interface ConnectionReuseStrategy
public boolean keepAlive(final HttpResponse response,
final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException
("HTTP response may not be null.");
}
if (context == null) {
throw new IllegalArgumentException
("HTTP context may not be null.");
}
HttpConnection conn = (HttpConnection)
context.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null && !conn.isOpen())
return false;
// do NOT check for stale connection, that is an expensive operation
// Check for a self-terminating entity. If the end of the entity will
// be indicated by closing the connection, there is no keep-alive.
HttpEntity entity = response.getEntity();
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
if (entity != null) {
if (entity.getContentLength() < 0) {
if (!entity.isChunked() ||
ver.lessEquals(HttpVersion.HTTP_1_0)) {
// if the content length is not known and is not chunk
// encoded, the connection cannot be reused
return false;
}
}
}
// Check for the "Connection" header. If that is absent, check for
// the "Proxy-Connection" header. The latter is an unspecified and
// broken but unfortunately common extension of HTTP.
HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
if (!hit.hasNext())
hit = response.headerIterator("Proxy-Connection");
// Experimental usage of the "Connection" header in HTTP/1.0 is
// documented in RFC 2068, section 19.7.1. A token "keep-alive" is
// used to indicate that the connection should be persistent.
// Note that the final specification of HTTP/1.1 in RFC 2616 does not
// include this information. Neither is the "Connection" header
// mentioned in RFC 1945, which informally describes HTTP/1.0.
//
// RFC 2616 specifies "close" as the only connection token with a
// specific meaning: it disables persistent connections.
//
// The "Proxy-Connection" header is not formally specified anywhere,
// but is commonly used to carry one token, "close" or "keep-alive".
// The "Connection" header, on the other hand, is defined as a
// sequence of tokens, where each token is a header name, and the
// token "close" has the above-mentioned additional meaning.
//
// To get through this mess, we treat the "Proxy-Connection" header
// in exactly the same way as the "Connection" header, but only if
// the latter is missing. We scan the sequence of tokens for both
// "close" and "keep-alive". As "close" is specified by RFC 2068,
// it takes precedence and indicates a non-persistent connection.
// If there is no "close" but a "keep-alive", we take the hint.
if (hit.hasNext()) {
try {
TokenIterator ti = createTokenIterator(hit);
boolean keepalive = false;
while (ti.hasNext()) {
final String token = ti.nextToken();
if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
return false;
} else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
// continue the loop, there may be a "close" afterwards
keepalive = true;
}
}
if (keepalive)
return true;
// neither "close" nor "keep-alive", use default policy
} catch (ParseException px) {
// invalid connection header means no persistent connection
// we don't have logging in HttpCore, so the exception is lost
return false;
}
}
// default since HTTP/1.1 is persistent, before it was non-persistent
return !ver.lessEquals(HttpVersion.HTTP_1_0);
}
/**
* Creates a token iterator from a header iterator.
* This method can be overridden to replace the implementation of
* the token iterator.
*
* @param hit the header iterator
*
* @return the token iterator
*/
protected TokenIterator createTokenIterator(HeaderIterator hit) {
return new BasicTokenIterator(hit);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.util.Locale;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.ReasonPhraseCatalog;
import org.apache.ogt.http.StatusLine;
import org.apache.ogt.http.impl.EnglishReasonPhraseCatalog;
import org.apache.ogt.http.message.BasicHttpResponse;
import org.apache.ogt.http.message.BasicStatusLine;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default factory for creating {@link HttpResponse} objects.
*
* @since 4.0
*/
public class DefaultHttpResponseFactory implements HttpResponseFactory {
/** The catalog for looking up reason phrases. */
protected final ReasonPhraseCatalog reasonCatalog;
/**
* Creates a new response factory with the given catalog.
*
* @param catalog the catalog of reason phrases
*/
public DefaultHttpResponseFactory(ReasonPhraseCatalog catalog) {
if (catalog == null) {
throw new IllegalArgumentException
("Reason phrase catalog must not be null.");
}
this.reasonCatalog = catalog;
}
/**
* Creates a new response factory with the default catalog.
* The default catalog is {@link EnglishReasonPhraseCatalog}.
*/
public DefaultHttpResponseFactory() {
this(EnglishReasonPhraseCatalog.INSTANCE);
}
// non-javadoc, see interface HttpResponseFactory
public HttpResponse newHttpResponse(final ProtocolVersion ver,
final int status,
HttpContext context) {
if (ver == null) {
throw new IllegalArgumentException("HTTP version may not be null");
}
final Locale loc = determineLocale(context);
final String reason = reasonCatalog.getReason(status, loc);
StatusLine statusline = new BasicStatusLine(ver, status, reason);
return new BasicHttpResponse(statusline, reasonCatalog, loc);
}
// non-javadoc, see interface HttpResponseFactory
public HttpResponse newHttpResponse(final StatusLine statusline,
HttpContext context) {
if (statusline == null) {
throw new IllegalArgumentException("Status line may not be null");
}
final Locale loc = determineLocale(context);
return new BasicHttpResponse(statusline, reasonCatalog, loc);
}
/**
* Determines the locale of the response.
* The implementation in this class always returns the default locale.
*
* @param context the context from which to determine the locale, or
* <code>null</code> to use the default locale
*
* @return the locale for the response, never <code>null</code>
*/
protected Locale determineLocale(HttpContext context) {
return Locale.getDefault();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.entity.EntityDeserializer;
import org.apache.ogt.http.impl.entity.EntitySerializer;
import org.apache.ogt.http.impl.entity.LaxContentLengthStrategy;
import org.apache.ogt.http.impl.entity.StrictContentLengthStrategy;
import org.apache.ogt.http.impl.io.HttpRequestWriter;
import org.apache.ogt.http.impl.io.HttpResponseParser;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.HttpMessageParser;
import org.apache.ogt.http.io.HttpMessageWriter;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.params.HttpParams;
/**
* Abstract client-side HTTP connection capable of transmitting and receiving
* data using arbitrary {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractHttpClientConnection implements HttpClientConnection {
private final EntitySerializer entityserializer;
private final EntityDeserializer entitydeserializer;
private SessionInputBuffer inbuffer = null;
private SessionOutputBuffer outbuffer = null;
private EofSensor eofSensor = null;
private HttpMessageParser responseParser = null;
private HttpMessageWriter requestWriter = null;
private HttpConnectionMetricsImpl metrics = null;
/**
* Creates an instance of this class.
* <p>
* This constructor will invoke {@link #createEntityDeserializer()}
* and {@link #createEntitySerializer()} methods in order to initialize
* HTTP entity serializer and deserializer implementations for this
* connection.
*/
public AbstractHttpClientConnection() {
super();
this.entityserializer = createEntitySerializer();
this.entitydeserializer = createEntityDeserializer();
}
/**
* Asserts if the connection is open.
*
* @throws IllegalStateException if the connection is not open.
*/
protected abstract void assertOpen() throws IllegalStateException;
/**
* Creates an instance of {@link EntityDeserializer} with the
* {@link LaxContentLengthStrategy} implementation to be used for
* de-serializing entities received over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntityDeserializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity deserializer
*/
protected EntityDeserializer createEntityDeserializer() {
return new EntityDeserializer(new LaxContentLengthStrategy());
}
/**
* Creates an instance of {@link EntitySerializer} with the
* {@link StrictContentLengthStrategy} implementation to be used for
* serializing HTTP entities sent over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntitySerializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity serialzier.
*/
protected EntitySerializer createEntitySerializer() {
return new EntitySerializer(new StrictContentLengthStrategy());
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* for creating {@link HttpResponse} objects received by over this
* connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link HttpMessageParser} to be used for parsing
* HTTP responses received over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageParser} interface or
* to pass a different implementation of {@link LineParser} to the
* the default implementation {@link HttpResponseParser}.
*
* @param buffer the session input buffer.
* @param responseFactory the HTTP response factory.
* @param params HTTP parameters.
* @return HTTP message parser.
*/
protected HttpMessageParser createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new HttpResponseParser(buffer, null, responseFactory, params);
}
/**
* Creates an instance of {@link HttpMessageWriter} to be used for
* writing out HTTP requests sent over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageWriter} interface or
* to pass a different implementation of {@link LineFormatter} to the
* the default implementation {@link HttpRequestWriter}.
*
* @param buffer the session output buffer
* @param params HTTP parameters
* @return HTTP message writer
*/
protected HttpMessageWriter createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new HttpRequestWriter(buffer, null, params);
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
/**
* Initializes this connection object with {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} instances to be used for sending and
* receiving data. These session buffers can be bound to any arbitrary
* physical output medium.
* <p>
* This method will invoke {@link #createHttpResponseFactory()},
* {@link #createRequestWriter(SessionOutputBuffer, HttpParams)}
* and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)}
* methods to initialize HTTP request writer and response parser for this
* connection.
*
* @param inbuffer the session input buffer.
* @param outbuffer the session output buffer.
* @param params HTTP parameters.
*/
protected void init(
final SessionInputBuffer inbuffer,
final SessionOutputBuffer outbuffer,
final HttpParams params) {
if (inbuffer == null) {
throw new IllegalArgumentException("Input session buffer may not be null");
}
if (outbuffer == null) {
throw new IllegalArgumentException("Output session buffer may not be null");
}
this.inbuffer = inbuffer;
this.outbuffer = outbuffer;
if (inbuffer instanceof EofSensor) {
this.eofSensor = (EofSensor) inbuffer;
}
this.responseParser = createResponseParser(
inbuffer,
createHttpResponseFactory(),
params);
this.requestWriter = createRequestWriter(
outbuffer, params);
this.metrics = createConnectionMetrics(
inbuffer.getMetrics(),
outbuffer.getMetrics());
}
public boolean isResponseAvailable(int timeout) throws IOException {
assertOpen();
return this.inbuffer.isDataAvailable(timeout);
}
public void sendRequestHeader(final HttpRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
this.requestWriter.write(request);
this.metrics.incrementRequestCount();
}
public void sendRequestEntity(final HttpEntityEnclosingRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
if (request.getEntity() == null) {
return;
}
this.entityserializer.serialize(
this.outbuffer,
request,
request.getEntity());
}
protected void doFlush() throws IOException {
this.outbuffer.flush();
}
public void flush() throws IOException {
assertOpen();
doFlush();
}
public HttpResponse receiveResponseHeader()
throws HttpException, IOException {
assertOpen();
HttpResponse response = (HttpResponse) this.responseParser.parse();
if (response.getStatusLine().getStatusCode() >= 200) {
this.metrics.incrementResponseCount();
}
return response;
}
public void receiveResponseEntity(final HttpResponse response)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertOpen();
HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response);
response.setEntity(entity);
}
protected boolean isEof() {
return this.eofSensor != null && this.eofSensor.isEof();
}
public boolean isStale() {
if (!isOpen()) {
return true;
}
if (isEof()) {
return true;
}
try {
this.inbuffer.isDataAvailable(1);
return isEof();
} catch (IOException ex) {
return true;
}
}
public HttpConnectionMetrics getMetrics() {
return this.metrics;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.util.HashMap;
import org.apache.ogt.http.HttpConnectionMetrics;
import org.apache.ogt.http.io.HttpTransportMetrics;
/**
* Default implementation of the {@link HttpConnectionMetrics} interface.
*
* @since 4.0
*/
public class HttpConnectionMetricsImpl implements HttpConnectionMetrics {
public static final String REQUEST_COUNT = "http.request-count";
public static final String RESPONSE_COUNT = "http.response-count";
public static final String SENT_BYTES_COUNT = "http.sent-bytes-count";
public static final String RECEIVED_BYTES_COUNT = "http.received-bytes-count";
private final HttpTransportMetrics inTransportMetric;
private final HttpTransportMetrics outTransportMetric;
private long requestCount = 0;
private long responseCount = 0;
/**
* The cache map for all metrics values.
*/
private HashMap metricsCache;
public HttpConnectionMetricsImpl(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
super();
this.inTransportMetric = inTransportMetric;
this.outTransportMetric = outTransportMetric;
}
/* ------------------ Public interface method -------------------------- */
public long getReceivedBytesCount() {
if (this.inTransportMetric != null) {
return this.inTransportMetric.getBytesTransferred();
} else {
return -1;
}
}
public long getSentBytesCount() {
if (this.outTransportMetric != null) {
return this.outTransportMetric.getBytesTransferred();
} else {
return -1;
}
}
public long getRequestCount() {
return this.requestCount;
}
public void incrementRequestCount() {
this.requestCount++;
}
public long getResponseCount() {
return this.responseCount;
}
public void incrementResponseCount() {
this.responseCount++;
}
public Object getMetric(final String metricName) {
Object value = null;
if (this.metricsCache != null) {
value = this.metricsCache.get(metricName);
}
if (value == null) {
if (REQUEST_COUNT.equals(metricName)) {
value = new Long(requestCount);
} else if (RESPONSE_COUNT.equals(metricName)) {
value = new Long(responseCount);
} else if (RECEIVED_BYTES_COUNT.equals(metricName)) {
if (this.inTransportMetric != null) {
return new Long(this.inTransportMetric.getBytesTransferred());
} else {
return null;
}
} else if (SENT_BYTES_COUNT.equals(metricName)) {
if (this.outTransportMetric != null) {
return new Long(this.outTransportMetric.getBytesTransferred());
} else {
return null;
}
}
}
return value;
}
public void setMetric(final String metricName, Object obj) {
if (this.metricsCache == null) {
this.metricsCache = new HashMap();
}
this.metricsCache.put(metricName, obj);
}
public void reset() {
if (this.outTransportMetric != null) {
this.outTransportMetric.reset();
}
if (this.inTransportMetric != null) {
this.inTransportMetric.reset();
}
this.requestCount = 0;
this.responseCount = 0;
this.metricsCache = null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A strategy that never re-uses a connection.
*
* @since 4.0
*/
public class NoConnectionReuseStrategy implements ConnectionReuseStrategy {
// default constructor
// non-JavaDoc, see interface ConnectionReuseStrategy
public boolean keepAlive(final HttpResponse response, final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
return false;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* Output stream that writes data without any transformation. The end of
* the content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, the stream will be marked as closed and no further
* output will be permitted.
*
* @since 4.0
*/
public class IdentityOutputStream extends OutputStream {
/**
* Wrapped session output buffer.
*/
private final SessionOutputBuffer out;
/** True if the stream is closed. */
private boolean closed = false;
public IdentityOutputStream(final SessionOutputBuffer out) {
super();
if (out == null) {
throw new IllegalArgumentException("Session output buffer may not be null");
}
this.out = out;
}
/**
* <p>Does not close the underlying socket output.</p>
*
* @throws IOException If an I/O problem occurs.
*/
public void close() throws IOException {
if (!this.closed) {
this.closed = true;
this.out.flush();
}
}
public void flush() throws IOException {
this.out.flush();
}
public void write(byte[] b, int off, int len) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
this.out.write(b, off, len);
}
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
this.out.write(b);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link SessionInputBuffer} implementation bound to a {@link Socket}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class SocketInputBuffer extends AbstractSessionInputBuffer implements EofSensor {
static private final Class SOCKET_TIMEOUT_CLASS = SocketTimeoutExceptionClass();
/**
* Returns <code>SocketTimeoutExceptionClass<code> or <code>null</code> if the class
* does not exist.
*
* @return <code>SocketTimeoutExceptionClass<code>, or <code>null</code> if unavailable.
*/
static private Class SocketTimeoutExceptionClass() {
try {
return Class.forName("java.net.SocketTimeoutException");
} catch (ClassNotFoundException e) {
return null;
}
}
private static boolean isSocketTimeoutException(final InterruptedIOException e) {
if (SOCKET_TIMEOUT_CLASS != null) {
return SOCKET_TIMEOUT_CLASS.isInstance(e);
} else {
return true;
}
}
private final Socket socket;
private boolean eof;
/**
* Creates an instance of this class.
*
* @param socket the socket to read data from.
* @param buffersize the size of the internal buffer. If this number is less
* than <code>0</code> it is set to the value of
* {@link Socket#getReceiveBufferSize()}. If resultant number is less
* than <code>1024</code> it is set to <code>1024</code>.
* @param params HTTP parameters.
*/
public SocketInputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
super();
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
this.socket = socket;
this.eof = false;
if (buffersize < 0) {
buffersize = socket.getReceiveBufferSize();
}
if (buffersize < 1024) {
buffersize = 1024;
}
init(socket.getInputStream(), buffersize, params);
}
protected int fillBuffer() throws IOException {
int i = super.fillBuffer();
this.eof = i == -1;
return i;
}
public boolean isDataAvailable(int timeout) throws IOException {
boolean result = hasBufferedData();
if (!result) {
int oldtimeout = this.socket.getSoTimeout();
try {
this.socket.setSoTimeout(timeout);
fillBuffer();
result = hasBufferedData();
} catch (InterruptedIOException e) {
if (!isSocketTimeoutException(e)) {
throw e;
}
} finally {
socket.setSoTimeout(oldtimeout);
}
}
return result;
}
public boolean isEof() {
return this.eof;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.util.Iterator;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.io.HttpMessageWriter;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.BasicLineFormatter;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for HTTP message writers that serialize output to
* an instance of {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public abstract class AbstractMessageWriter implements HttpMessageWriter {
protected final SessionOutputBuffer sessionBuffer;
protected final CharArrayBuffer lineBuf;
protected final LineFormatter lineFormatter;
/**
* Creates an instance of AbstractMessageWriter.
*
* @param buffer the session output buffer.
* @param formatter the line formatter.
* @param params HTTP parameters.
*/
public AbstractMessageWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.sessionBuffer = buffer;
this.lineBuf = new CharArrayBuffer(128);
this.lineFormatter = (formatter != null) ?
formatter : BasicLineFormatter.DEFAULT;
}
/**
* Subclasses must override this method to write out the first header line
* based on the {@link HttpMessage} passed as a parameter.
*
* @param message the message whose first line is to be written out.
* @throws IOException in case of an I/O error.
*/
protected abstract void writeHeadLine(HttpMessage message) throws IOException;
public void write(
final HttpMessage message) throws IOException, HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
writeHeadLine(message);
for (Iterator it = message.headerIterator(); it.hasNext(); ) {
Header header = (Header) it.next();
this.sessionBuffer.writeLine
(lineFormatter.formatHeader(this.lineBuf, header));
}
this.lineBuf.clear();
this.sessionBuffer.writeLine(this.lineBuf);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.params.HttpParams;
/**
* HTTP request writer that serializes its output to an instance
* of {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public class HttpRequestWriter extends AbstractMessageWriter {
public HttpRequestWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
protected void writeHeadLine(final HttpMessage message)
throws IOException {
lineFormatter.formatRequestLine(this.lineBuf,
((HttpRequest) message).getRequestLine());
this.sessionBuffer.writeLine(this.lineBuf);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.NoHttpResponseException;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.StatusLine;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* HTTP response parser that obtain its input from an instance
* of {@link SessionInputBuffer}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class HttpResponseParser extends AbstractMessageParser {
private final HttpResponseFactory responseFactory;
private final CharArrayBuffer lineBuf;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param responseFactory the factory to use to create
* {@link HttpResponse}s.
* @param params HTTP parameters.
*/
public HttpResponseParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpResponseFactory responseFactory,
final HttpParams params) {
super(buffer, parser, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
this.lineBuf = new CharArrayBuffer(128);
}
protected HttpMessage parseHead(
final SessionInputBuffer sessionBuffer)
throws IOException, HttpException, ParseException {
this.lineBuf.clear();
int i = sessionBuffer.readLine(this.lineBuf);
if (i == -1) {
throw new NoHttpResponseException("The target server failed to respond");
}
//create the status line from the status string
ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor);
return this.responseFactory.newHttpResponse(statusline, null);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.params.HttpParams;
/**
* HTTP response writer that serializes its output to an instance
* of {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public class HttpResponseWriter extends AbstractMessageWriter {
public HttpResponseWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
protected void writeHeadLine(final HttpMessage message)
throws IOException {
lineFormatter.formatStatusLine(this.lineBuf,
((HttpResponse) message).getStatusLine());
this.sessionBuffer.writeLine(this.lineBuf);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* Output stream that cuts off after a defined number of bytes. This class
* is used to send content of HTTP messages where the end of the content entity
* is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, the stream will be marked as closed and no further
* output will be permitted.
*
* @since 4.0
*/
public class ContentLengthOutputStream extends OutputStream {
/**
* Wrapped session output buffer.
*/
private final SessionOutputBuffer out;
/**
* The maximum number of bytes that can be written the stream. Subsequent
* write operations will be ignored.
*/
private final long contentLength;
/** Total bytes written */
private long total = 0;
/** True if the stream is closed. */
private boolean closed = false;
/**
* Wraps a session output buffer and cuts off output after a defined number
* of bytes.
*
* @param out The session output buffer
* @param contentLength The maximum number of bytes that can be written to
* the stream. Subsequent write operations will be ignored.
*
* @since 4.0
*/
public ContentLengthOutputStream(final SessionOutputBuffer out, long contentLength) {
super();
if (out == null) {
throw new IllegalArgumentException("Session output buffer may not be null");
}
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.out = out;
this.contentLength = contentLength;
}
/**
* <p>Does not close the underlying socket output.</p>
*
* @throws IOException If an I/O problem occurs.
*/
public void close() throws IOException {
if (!this.closed) {
this.closed = true;
this.out.flush();
}
}
public void flush() throws IOException {
this.out.flush();
}
public void write(byte[] b, int off, int len) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
if (this.total < this.contentLength) {
long max = this.contentLength - this.total;
if (len > max) {
len = (int) max;
}
this.out.write(b, off, len);
this.total += len;
}
}
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
if (this.total < this.contentLength) {
this.out.write(b);
this.total++;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.net.Socket;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link SessionOutputBuffer} implementation bound to a {@link Socket}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
public class SocketOutputBuffer extends AbstractSessionOutputBuffer {
/**
* Creates an instance of this class.
*
* @param socket the socket to write data to.
* @param buffersize the size of the internal buffer. If this number is less
* than <code>0</code> it is set to the value of
* {@link Socket#getSendBufferSize()}. If resultant number is less
* than <code>1024</code> it is set to <code>1024</code>.
* @param params HTTP parameters.
*/
public SocketOutputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
super();
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (buffersize < 0) {
buffersize = socket.getSendBufferSize();
}
if (buffersize < 1024) {
buffersize = 1024;
}
init(socket.getOutputStream(), buffersize, params);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.SessionInputBuffer;
/**
* Input stream that reads data without any transformation. The end of the
* content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, it will read until the end of the stream (until
* <code>-1</code> is returned).
*
* @since 4.0
*/
public class IdentityInputStream extends InputStream {
private final SessionInputBuffer in;
private boolean closed = false;
/**
* Wraps session input stream and reads input until the the end of stream.
*
* @param in The session input buffer
*/
public IdentityInputStream(final SessionInputBuffer in) {
super();
if (in == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.in = in;
}
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
return ((BufferInfo) this.in).length();
} else {
return 0;
}
}
public void close() throws IOException {
this.closed = true;
}
public int read() throws IOException {
if (this.closed) {
return -1;
} else {
return this.in.read();
}
}
public int read(final byte[] b, int off, int len) throws IOException {
if (this.closed) {
return -1;
} else {
return this.in.read(b, off, len);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.ByteArrayBuffer;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for session output buffers that stream data to
* an arbitrary {@link OutputStream}. This class buffers small chunks of
* output data in an internal byte array for optimal output performance.
* <p>
* {@link #writeLine(CharArrayBuffer)} and {@link #writeLine(String)} methods
* of this class use CR-LF as a line delimiter.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}</li>
* </ul>
* <p>
*
* @since 4.0
*/
public abstract class AbstractSessionOutputBuffer implements SessionOutputBuffer, BufferInfo {
private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF};
private OutputStream outstream;
private ByteArrayBuffer buffer;
private String charset = HTTP.US_ASCII;
private boolean ascii = true;
private int minChunkLimit = 512;
private HttpTransportMetricsImpl metrics;
/**
* Initializes this session output buffer.
*
* @param outstream the destination output stream.
* @param buffersize the size of the internal buffer.
* @param params HTTP parameters.
*/
protected void init(final OutputStream outstream, int buffersize, final HttpParams params) {
if (outstream == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
if (buffersize <= 0) {
throw new IllegalArgumentException("Buffer size may not be negative or zero");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.outstream = outstream;
this.buffer = new ByteArrayBuffer(buffersize);
this.charset = HttpProtocolParams.getHttpElementCharset(params);
this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII)
|| this.charset.equalsIgnoreCase(HTTP.ASCII);
this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512);
this.metrics = createTransportMetrics();
}
/**
* @since 4.1
*/
protected HttpTransportMetricsImpl createTransportMetrics() {
return new HttpTransportMetricsImpl();
}
/**
* @since 4.`1
*/
public int capacity() {
return this.buffer.capacity();
}
/**
* @since 4.1
*/
public int length() {
return this.buffer.length();
}
/**
* @since 4.1
*/
public int available() {
return capacity() - length();
}
protected void flushBuffer() throws IOException {
int len = this.buffer.length();
if (len > 0) {
this.outstream.write(this.buffer.buffer(), 0, len);
this.buffer.clear();
this.metrics.incrementBytesTransferred(len);
}
}
public void flush() throws IOException {
flushBuffer();
this.outstream.flush();
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
// Do not want to buffer large-ish chunks
// if the byte array is larger then MIN_CHUNK_LIMIT
// write it directly to the output stream
if (len > this.minChunkLimit || len > this.buffer.capacity()) {
// flush the buffer
flushBuffer();
// write directly to the out stream
this.outstream.write(b, off, len);
this.metrics.incrementBytesTransferred(len);
} else {
// Do not let the buffer grow unnecessarily
int freecapacity = this.buffer.capacity() - this.buffer.length();
if (len > freecapacity) {
// flush the buffer
flushBuffer();
}
// buffer
this.buffer.append(b, off, len);
}
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.buffer.isFull()) {
flushBuffer();
}
this.buffer.append(b);
}
/**
* Writes characters from the specified string followed by a line delimiter
* to this session buffer.
* <p>
* This method uses CR-LF as a line delimiter.
*
* @param s the line.
* @exception IOException if an I/O error occurs.
*/
public void writeLine(final String s) throws IOException {
if (s == null) {
return;
}
if (s.length() > 0) {
write(s.getBytes(this.charset));
}
write(CRLF);
}
/**
* Writes characters from the specified char array followed by a line
* delimiter to this session buffer.
* <p>
* This method uses CR-LF as a line delimiter.
*
* @param s the buffer containing chars of the line.
* @exception IOException if an I/O error occurs.
*/
public void writeLine(final CharArrayBuffer s) throws IOException {
if (s == null) {
return;
}
if (this.ascii) {
int off = 0;
int remaining = s.length();
while (remaining > 0) {
int chunk = this.buffer.capacity() - this.buffer.length();
chunk = Math.min(chunk, remaining);
if (chunk > 0) {
this.buffer.append(s, off, chunk);
}
if (this.buffer.isFull()) {
flushBuffer();
}
off += chunk;
remaining -= chunk;
}
} else {
// This is VERY memory inefficient, BUT since non-ASCII charsets are
// NOT meant to be used anyway, there's no point optimizing it
byte[] tmp = s.toString().getBytes(this.charset);
write(tmp);
}
write(CRLF);
}
public HttpTransportMetrics getMetrics() {
return this.metrics;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestFactory;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.RequestLine;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* HTTP request parser that obtain its input from an instance
* of {@link SessionInputBuffer}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class HttpRequestParser extends AbstractMessageParser {
private final HttpRequestFactory requestFactory;
private final CharArrayBuffer lineBuf;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param requestFactory the factory to use to create
* {@link HttpRequest}s.
* @param params HTTP parameters.
*/
public HttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
this.lineBuf = new CharArrayBuffer(128);
}
protected HttpMessage parseHead(
final SessionInputBuffer sessionBuffer)
throws IOException, HttpException, ParseException {
this.lineBuf.clear();
int i = sessionBuffer.readLine(this.lineBuf);
if (i == -1) {
throw new ConnectionClosedException("Client closed connection");
}
ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor);
return this.requestFactory.newHttpRequest(requestline);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* Implements chunked transfer coding. The content is sent in small chunks.
* Entities transferred using this output stream can be of unlimited length.
* Writes are buffered to an internal buffer (2048 default size).
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, the stream will be marked as closed and no further
* output will be permitted.
*
*
* @since 4.0
*/
public class ChunkedOutputStream extends OutputStream {
// ----------------------------------------------------- Instance Variables
private final SessionOutputBuffer out;
private byte[] cache;
private int cachePosition = 0;
private boolean wroteLastChunk = false;
/** True if the stream is closed. */
private boolean closed = false;
// ----------------------------------------------------------- Constructors
/**
* Wraps a session output buffer and chunk-encodes the output.
*
* @param out The session output buffer
* @param bufferSize The minimum chunk size (excluding last chunk)
* @throws IOException in case of an I/O error
*/
public ChunkedOutputStream(final SessionOutputBuffer out, int bufferSize)
throws IOException {
super();
this.cache = new byte[bufferSize];
this.out = out;
}
/**
* Wraps a session output buffer and chunks the output. The default buffer
* size of 2048 was chosen because the chunk overhead is less than 0.5%
*
* @param out the output buffer to wrap
* @throws IOException in case of an I/O error
*/
public ChunkedOutputStream(final SessionOutputBuffer out)
throws IOException {
this(out, 2048);
}
// ----------------------------------------------------------- Internal methods
/**
* Writes the cache out onto the underlying stream
*/
protected void flushCache() throws IOException {
if (this.cachePosition > 0) {
this.out.writeLine(Integer.toHexString(this.cachePosition));
this.out.write(this.cache, 0, this.cachePosition);
this.out.writeLine("");
this.cachePosition = 0;
}
}
/**
* Writes the cache and bufferToAppend to the underlying stream
* as one large chunk
*/
protected void flushCacheWithAppend(byte bufferToAppend[], int off, int len) throws IOException {
this.out.writeLine(Integer.toHexString(this.cachePosition + len));
this.out.write(this.cache, 0, this.cachePosition);
this.out.write(bufferToAppend, off, len);
this.out.writeLine("");
this.cachePosition = 0;
}
protected void writeClosingChunk() throws IOException {
// Write the final chunk.
this.out.writeLine("0");
this.out.writeLine("");
}
// ----------------------------------------------------------- Public Methods
/**
* Must be called to ensure the internal cache is flushed and the closing
* chunk is written.
* @throws IOException in case of an I/O error
*/
public void finish() throws IOException {
if (!this.wroteLastChunk) {
flushCache();
writeClosingChunk();
this.wroteLastChunk = true;
}
}
// -------------------------------------------- OutputStream Methods
public void write(int b) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
this.cache[this.cachePosition] = (byte) b;
this.cachePosition++;
if (this.cachePosition == this.cache.length) flushCache();
}
/**
* Writes the array. If the array does not fit within the buffer, it is
* not split, but rather written out as one large chunk.
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* Writes the array. If the array does not fit within the buffer, it is
* not split, but rather written out as one large chunk.
*/
public void write(byte src[], int off, int len) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
if (len >= this.cache.length - this.cachePosition) {
flushCacheWithAppend(src, off, len);
} else {
System.arraycopy(src, off, cache, this.cachePosition, len);
this.cachePosition += len;
}
}
/**
* Flushes the content buffer and the underlying stream.
*/
public void flush() throws IOException {
flushCache();
this.out.flush();
}
/**
* Finishes writing to the underlying stream, but does NOT close the underlying stream.
*/
public void close() throws IOException {
if (!this.closed) {
this.closed = true;
finish();
this.out.flush();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import org.apache.ogt.http.io.HttpTransportMetrics;
/**
* Default implementation of {@link HttpTransportMetrics}.
*
* @since 4.0
*/
public class HttpTransportMetricsImpl implements HttpTransportMetrics {
private long bytesTransferred = 0;
public HttpTransportMetricsImpl() {
super();
}
public long getBytesTransferred() {
return this.bytesTransferred;
}
public void setBytesTransferred(long count) {
this.bytesTransferred = count;
}
public void incrementBytesTransferred(long count) {
this.bytesTransferred += count;
}
public void reset() {
this.bytesTransferred = 0;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.ByteArrayBuffer;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for session input buffers that stream data from
* an arbitrary {@link InputStream}. This class buffers input data in
* an internal byte array for optimal input performance.
* <p>
* {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this
* class treat a lone LF as valid line delimiters in addition to CR-LF required
* by the HTTP specification.
*
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}</li>
* </ul>
* @since 4.0
*/
public abstract class AbstractSessionInputBuffer implements SessionInputBuffer, BufferInfo {
private InputStream instream;
private byte[] buffer;
private int bufferpos;
private int bufferlen;
private ByteArrayBuffer linebuffer = null;
private String charset = HTTP.US_ASCII;
private boolean ascii = true;
private int maxLineLen = -1;
private int minChunkLimit = 512;
private HttpTransportMetricsImpl metrics;
/**
* Initializes this session input buffer.
*
* @param instream the source input stream.
* @param buffersize the size of the internal buffer.
* @param params HTTP parameters.
*/
protected void init(final InputStream instream, int buffersize, final HttpParams params) {
if (instream == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
if (buffersize <= 0) {
throw new IllegalArgumentException("Buffer size may not be negative or zero");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.instream = instream;
this.buffer = new byte[buffersize];
this.bufferpos = 0;
this.bufferlen = 0;
this.linebuffer = new ByteArrayBuffer(buffersize);
this.charset = HttpProtocolParams.getHttpElementCharset(params);
this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII)
|| this.charset.equalsIgnoreCase(HTTP.ASCII);
this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1);
this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512);
this.metrics = createTransportMetrics();
}
/**
* @since 4.1
*/
protected HttpTransportMetricsImpl createTransportMetrics() {
return new HttpTransportMetricsImpl();
}
/**
* @since 4.1
*/
public int capacity() {
return this.buffer.length;
}
/**
* @since 4.1
*/
public int length() {
return this.bufferlen - this.bufferpos;
}
/**
* @since 4.1
*/
public int available() {
return capacity() - length();
}
protected int fillBuffer() throws IOException {
// compact the buffer if necessary
if (this.bufferpos > 0) {
int len = this.bufferlen - this.bufferpos;
if (len > 0) {
System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len);
}
this.bufferpos = 0;
this.bufferlen = len;
}
int l;
int off = this.bufferlen;
int len = this.buffer.length - off;
l = this.instream.read(this.buffer, off, len);
if (l == -1) {
return -1;
} else {
this.bufferlen = off + l;
this.metrics.incrementBytesTransferred(l);
return l;
}
}
protected boolean hasBufferedData() {
return this.bufferpos < this.bufferlen;
}
public int read() throws IOException {
int noRead = 0;
while (!hasBufferedData()) {
noRead = fillBuffer();
if (noRead == -1) {
return -1;
}
}
return this.buffer[this.bufferpos++] & 0xff;
}
public int read(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return 0;
}
if (hasBufferedData()) {
int chunk = Math.min(len, this.bufferlen - this.bufferpos);
System.arraycopy(this.buffer, this.bufferpos, b, off, chunk);
this.bufferpos += chunk;
return chunk;
}
// If the remaining capacity is big enough, read directly from the
// underlying input stream bypassing the buffer.
if (len > this.minChunkLimit) {
int read = this.instream.read(b, off, len);
if (read > 0) {
this.metrics.incrementBytesTransferred(read);
}
return read;
} else {
// otherwise read to the buffer first
while (!hasBufferedData()) {
int noRead = fillBuffer();
if (noRead == -1) {
return -1;
}
}
int chunk = Math.min(len, this.bufferlen - this.bufferpos);
System.arraycopy(this.buffer, this.bufferpos, b, off, chunk);
this.bufferpos += chunk;
return chunk;
}
}
public int read(final byte[] b) throws IOException {
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
private int locateLF() {
for (int i = this.bufferpos; i < this.bufferlen; i++) {
if (this.buffer[i] == HTTP.LF) {
return i;
}
}
return -1;
}
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer into the given line buffer. The number of chars actually
* read is returned as an integer. The line delimiter itself is discarded.
* If no char is available because the end of the stream has been reached,
* the value <code>-1</code> is returned. This method blocks until input
* data is available, end of file is detected, or an exception is thrown.
* <p>
* This method treats a lone LF as a valid line delimiters in addition
* to CR-LF required by the HTTP specification.
*
* @param charbuffer the line buffer.
* @return one line of characters
* @exception IOException if an I/O error occurs.
*/
public int readLine(final CharArrayBuffer charbuffer) throws IOException {
if (charbuffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
int noRead = 0;
boolean retry = true;
while (retry) {
// attempt to find end of line (LF)
int i = locateLF();
if (i != -1) {
// end of line found.
if (this.linebuffer.isEmpty()) {
// the entire line is preset in the read buffer
return lineFromReadBuffer(charbuffer, i);
}
retry = false;
int len = i + 1 - this.bufferpos;
this.linebuffer.append(this.buffer, this.bufferpos, len);
this.bufferpos = i + 1;
} else {
// end of line not found
if (hasBufferedData()) {
int len = this.bufferlen - this.bufferpos;
this.linebuffer.append(this.buffer, this.bufferpos, len);
this.bufferpos = this.bufferlen;
}
noRead = fillBuffer();
if (noRead == -1) {
retry = false;
}
}
if (this.maxLineLen > 0 && this.linebuffer.length() >= this.maxLineLen) {
throw new IOException("Maximum line length limit exceeded");
}
}
if (noRead == -1 && this.linebuffer.isEmpty()) {
// indicate the end of stream
return -1;
}
return lineFromLineBuffer(charbuffer);
}
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer. The line delimiter itself is discarded. If no char is
* available because the end of the stream has been reached,
* <code>null</code> is returned. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
* <p>
* This method treats a lone LF as a valid line delimiters in addition
* to CR-LF required by the HTTP specification.
*
* @return HTTP line as a string
* @exception IOException if an I/O error occurs.
*/
private int lineFromLineBuffer(final CharArrayBuffer charbuffer)
throws IOException {
// discard LF if found
int l = this.linebuffer.length();
if (l > 0) {
if (this.linebuffer.byteAt(l - 1) == HTTP.LF) {
l--;
this.linebuffer.setLength(l);
}
// discard CR if found
if (l > 0) {
if (this.linebuffer.byteAt(l - 1) == HTTP.CR) {
l--;
this.linebuffer.setLength(l);
}
}
}
l = this.linebuffer.length();
if (this.ascii) {
charbuffer.append(this.linebuffer, 0, l);
} else {
// This is VERY memory inefficient, BUT since non-ASCII charsets are
// NOT meant to be used anyway, there's no point optimizing it
String s = new String(this.linebuffer.buffer(), 0, l, this.charset);
l = s.length();
charbuffer.append(s);
}
this.linebuffer.clear();
return l;
}
private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos)
throws IOException {
int off = this.bufferpos;
int len;
this.bufferpos = pos + 1;
if (pos > 0 && this.buffer[pos - 1] == HTTP.CR) {
// skip CR if found
pos--;
}
len = pos - off;
if (this.ascii) {
charbuffer.append(this.buffer, off, len);
} else {
// This is VERY memory inefficient, BUT since non-ASCII charsets are
// NOT meant to be used anyway, there's no point optimizing it
String s = new String(this.buffer, off, len, this.charset);
charbuffer.append(s);
len = s.length();
}
return len;
}
public String readLine() throws IOException {
CharArrayBuffer charbuffer = new CharArrayBuffer(64);
int l = readLine(charbuffer);
if (l != -1) {
return charbuffer.toString();
} else {
return null;
}
}
public HttpTransportMetrics getMetrics() {
return this.metrics;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.SessionInputBuffer;
/**
* Input stream that cuts off after a defined number of bytes. This class
* is used to receive content of HTTP messages where the end of the content
* entity is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, it will read until the "end" of its limit on
* close, which allows for the seamless execution of subsequent HTTP 1.1
* requests, while not requiring the client to remember to read the entire
* contents of the response.
*
*
* @since 4.0
*/
public class ContentLengthInputStream extends InputStream {
private static final int BUFFER_SIZE = 2048;
/**
* The maximum number of bytes that can be read from the stream. Subsequent
* read operations will return -1.
*/
private long contentLength;
/** The current position */
private long pos = 0;
/** True if the stream is closed. */
private boolean closed = false;
/**
* Wrapped input stream that all calls are delegated to.
*/
private SessionInputBuffer in = null;
/**
* Wraps a session input buffer and cuts off output after a defined number
* of bytes.
*
* @param in The session input buffer
* @param contentLength The maximum number of bytes that can be read from
* the stream. Subsequent read operations will return -1.
*/
public ContentLengthInputStream(final SessionInputBuffer in, long contentLength) {
super();
if (in == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.in = in;
this.contentLength = contentLength;
}
/**
* <p>Reads until the end of the known length of content.</p>
*
* <p>Does not close the underlying socket input, but instead leaves it
* primed to parse the next response.</p>
* @throws IOException If an IO problem occurs.
*/
public void close() throws IOException {
if (!closed) {
try {
if (pos < contentLength) {
byte buffer[] = new byte[BUFFER_SIZE];
while (read(buffer) >= 0) {
}
}
} finally {
// close after above so that we don't throw an exception trying
// to read after closed!
closed = true;
}
}
}
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
int len = ((BufferInfo) this.in).length();
return Math.min(len, (int) (this.contentLength - this.pos));
} else {
return 0;
}
}
/**
* Read the next byte from the stream
* @return The next byte or -1 if the end of stream has been reached.
* @throws IOException If an IO problem occurs
* @see java.io.InputStream#read()
*/
public int read() throws IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (pos >= contentLength) {
return -1;
}
int b = this.in.read();
if (b == -1) {
if (pos < contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ contentLength + "; received: " + pos);
}
} else {
pos++;
}
return b;
}
/**
* Does standard {@link InputStream#read(byte[], int, int)} behavior, but
* also notifies the watcher when the contents have been consumed.
*
* @param b The byte array to fill.
* @param off Start filling at this position.
* @param len The number of bytes to attempt to read.
* @return The number of bytes read, or -1 if the end of content has been
* reached.
*
* @throws java.io.IOException Should an error occur on the wrapped stream.
*/
public int read (byte[] b, int off, int len) throws java.io.IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (pos >= contentLength) {
return -1;
}
if (pos + len > contentLength) {
len = (int) (contentLength - pos);
}
int count = this.in.read(b, off, len);
if (count == -1 && pos < contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ contentLength + "; received: " + pos);
}
if (count > 0) {
pos += count;
}
return count;
}
/**
* Read more bytes from the stream.
* @param b The byte array to put the new data in.
* @return The number of bytes read into the buffer.
* @throws IOException If an IO problem occurs
* @see java.io.InputStream#read(byte[])
*/
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Skips and discards a number of bytes from the input stream.
* @param n The number of bytes to skip.
* @return The actual number of bytes skipped. <= 0 if no bytes
* are skipped.
* @throws IOException If an error occurs while skipping bytes.
* @see InputStream#skip(long)
*/
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
byte[] buffer = new byte[BUFFER_SIZE];
// make sure we don't skip more bytes than are
// still available
long remaining = Math.min(n, this.contentLength - this.pos);
// skip and keep track of the bytes actually skipped
long count = 0;
while (remaining > 0) {
int l = read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining));
if (l == -1) {
break;
}
count += l;
remaining -= l;
}
return count;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.MalformedChunkCodingException;
import org.apache.ogt.http.TruncatedChunkException;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.ExceptionUtils;
/**
* Implements chunked transfer coding. The content is received in small chunks.
* Entities transferred using this input stream can be of unlimited length.
* After the stream is read to the end, it provides access to the trailers,
* if any.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, it will read until the "end" of its chunking on
* close, which allows for the seamless execution of subsequent HTTP 1.1
* requests, while not requiring the client to remember to read the entire
* contents of the response.
*
*
* @since 4.0
*
*/
public class ChunkedInputStream extends InputStream {
private static final int CHUNK_LEN = 1;
private static final int CHUNK_DATA = 2;
private static final int CHUNK_CRLF = 3;
private static final int BUFFER_SIZE = 2048;
/** The session input buffer */
private final SessionInputBuffer in;
private final CharArrayBuffer buffer;
private int state;
/** The chunk size */
private int chunkSize;
/** The current position within the current chunk */
private int pos;
/** True if we've reached the end of stream */
private boolean eof = false;
/** True if this stream is closed */
private boolean closed = false;
private Header[] footers = new Header[] {};
/**
* Wraps session input stream and reads chunk coded input.
*
* @param in The session input buffer
*/
public ChunkedInputStream(final SessionInputBuffer in) {
super();
if (in == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.in = in;
this.pos = 0;
this.buffer = new CharArrayBuffer(16);
this.state = CHUNK_LEN;
}
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
int len = ((BufferInfo) this.in).length();
return Math.min(len, this.chunkSize - this.pos);
} else {
return 0;
}
}
/**
* <p> Returns all the data in a chunked stream in coalesced form. A chunk
* is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
* is detected.</p>
*
* <p> Trailer headers are read automatically at the end of the stream and
* can be obtained with the getResponseFooters() method.</p>
*
* @return -1 of the end of the stream has been reached or the next data
* byte
* @throws IOException in case of an I/O error
*/
public int read() throws IOException {
if (this.closed) {
throw new IOException("Attempted read from closed stream.");
}
if (this.eof) {
return -1;
}
if (state != CHUNK_DATA) {
nextChunk();
if (this.eof) {
return -1;
}
}
int b = in.read();
if (b != -1) {
pos++;
if (pos >= chunkSize) {
state = CHUNK_CRLF;
}
}
return b;
}
/**
* Read some bytes from the stream.
* @param b The byte array that will hold the contents from the stream.
* @param off The offset into the byte array at which bytes will start to be
* placed.
* @param len the maximum number of bytes that can be returned.
* @return The number of bytes returned or -1 if the end of stream has been
* reached.
* @throws IOException in case of an I/O error
*/
public int read (byte[] b, int off, int len) throws IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (eof) {
return -1;
}
if (state != CHUNK_DATA) {
nextChunk();
if (eof) {
return -1;
}
}
len = Math.min(len, chunkSize - pos);
int bytesRead = in.read(b, off, len);
if (bytesRead != -1) {
pos += bytesRead;
if (pos >= chunkSize) {
state = CHUNK_CRLF;
}
return bytesRead;
} else {
eof = true;
throw new TruncatedChunkException("Truncated chunk "
+ "( expected size: " + chunkSize
+ "; actual size: " + pos + ")");
}
}
/**
* Read some bytes from the stream.
* @param b The byte array that will hold the contents from the stream.
* @return The number of bytes returned or -1 if the end of stream has been
* reached.
* @throws IOException in case of an I/O error
*/
public int read (byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Read the next chunk.
* @throws IOException in case of an I/O error
*/
private void nextChunk() throws IOException {
chunkSize = getChunkSize();
if (chunkSize < 0) {
throw new MalformedChunkCodingException("Negative chunk size");
}
state = CHUNK_DATA;
pos = 0;
if (chunkSize == 0) {
eof = true;
parseTrailerHeaders();
}
}
/**
* Expects the stream to start with a chunksize in hex with optional
* comments after a semicolon. The line must end with a CRLF: "a3; some
* comment\r\n" Positions the stream at the start of the next line.
*
* @param in The new input stream.
* @param required <tt>true<tt/> if a valid chunk must be present,
* <tt>false<tt/> otherwise.
*
* @return the chunk size as integer
*
* @throws IOException when the chunk size could not be parsed
*/
private int getChunkSize() throws IOException {
int st = this.state;
switch (st) {
case CHUNK_CRLF:
this.buffer.clear();
int i = this.in.readLine(this.buffer);
if (i == -1) {
return 0;
}
if (!this.buffer.isEmpty()) {
throw new MalformedChunkCodingException(
"Unexpected content at the end of chunk");
}
state = CHUNK_LEN;
//$FALL-THROUGH$
case CHUNK_LEN:
this.buffer.clear();
i = this.in.readLine(this.buffer);
if (i == -1) {
return 0;
}
int separator = this.buffer.indexOf(';');
if (separator < 0) {
separator = this.buffer.length();
}
try {
return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16);
} catch (NumberFormatException e) {
throw new MalformedChunkCodingException("Bad chunk header");
}
default:
throw new IllegalStateException("Inconsistent codec state");
}
}
/**
* Reads and stores the Trailer headers.
* @throws IOException in case of an I/O error
*/
private void parseTrailerHeaders() throws IOException {
try {
this.footers = AbstractMessageParser.parseHeaders
(in, -1, -1, null);
} catch (HttpException e) {
IOException ioe = new MalformedChunkCodingException("Invalid footer: "
+ e.getMessage());
ExceptionUtils.initCause(ioe, e);
throw ioe;
}
}
/**
* Upon close, this reads the remainder of the chunked message,
* leaving the underlying socket at a position to start reading the
* next response without scanning.
* @throws IOException in case of an I/O error
*/
public void close() throws IOException {
if (!closed) {
try {
if (!eof) {
// read and discard the remainder of the message
byte buffer[] = new byte[BUFFER_SIZE];
while (read(buffer) >= 0) {
}
}
} finally {
eof = true;
closed = true;
}
}
}
public Header[] getFooters() {
return (Header[])this.footers.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.io.HttpMessageParser;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.message.BasicLineParser;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for HTTP message parsers that obtain input from
* an instance of {@link SessionInputBuffer}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractMessageParser implements HttpMessageParser {
private static final int HEAD_LINE = 0;
private static final int HEADERS = 1;
private final SessionInputBuffer sessionBuffer;
private final int maxHeaderCount;
private final int maxLineLen;
private final List headerLines;
protected final LineParser lineParser;
private int state;
private HttpMessage message;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param params HTTP parameters.
*/
public AbstractMessageParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.sessionBuffer = buffer;
this.maxHeaderCount = params.getIntParameter(
CoreConnectionPNames.MAX_HEADER_COUNT, -1);
this.maxLineLen = params.getIntParameter(
CoreConnectionPNames.MAX_LINE_LENGTH, -1);
this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT;
this.headerLines = new ArrayList();
this.state = HEAD_LINE;
}
/**
* Parses HTTP headers from the data receiver stream according to the generic
* format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3.
*
* @param inbuffer Session input buffer
* @param maxHeaderCount maximum number of headers allowed. If the number
* of headers received from the data stream exceeds maxCount value, an
* IOException will be thrown. Setting this parameter to a negative value
* or zero will disable the check.
* @param maxLineLen maximum number of characters for a header line,
* including the continuation lines. Setting this parameter to a negative
* value or zero will disable the check.
* @return array of HTTP headers
* @param parser line parser to use. Can be <code>null</code>, in which case
* the default implementation of this interface will be used.
*
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
public static Header[] parseHeaders(
final SessionInputBuffer inbuffer,
int maxHeaderCount,
int maxLineLen,
LineParser parser)
throws HttpException, IOException {
if (parser == null) {
parser = BasicLineParser.DEFAULT;
}
List headerLines = new ArrayList();
return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, parser, headerLines);
}
/**
* Parses HTTP headers from the data receiver stream according to the generic
* format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3.
*
* @param inbuffer Session input buffer
* @param maxHeaderCount maximum number of headers allowed. If the number
* of headers received from the data stream exceeds maxCount value, an
* IOException will be thrown. Setting this parameter to a negative value
* or zero will disable the check.
* @param maxLineLen maximum number of characters for a header line,
* including the continuation lines. Setting this parameter to a negative
* value or zero will disable the check.
* @param parser line parser to use.
* @param headerLines List of header lines. This list will be used to store
* intermediate results. This makes it possible to resume parsing of
* headers in case of a {@link java.io.InterruptedIOException}.
*
* @return array of HTTP headers
*
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*
* @since 4.1
*/
public static Header[] parseHeaders(
final SessionInputBuffer inbuffer,
int maxHeaderCount,
int maxLineLen,
final LineParser parser,
final List headerLines)
throws HttpException, IOException {
if (inbuffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (parser == null) {
throw new IllegalArgumentException("Line parser may not be null");
}
if (headerLines == null) {
throw new IllegalArgumentException("Header line list may not be null");
}
CharArrayBuffer current = null;
CharArrayBuffer previous = null;
for (;;) {
if (current == null) {
current = new CharArrayBuffer(64);
} else {
current.clear();
}
int l = inbuffer.readLine(current);
if (l == -1 || current.length() < 1) {
break;
}
// Parse the header name and value
// Check for folded headers first
// Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2
// discussion on folded headers
if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) {
// we have continuation folded header
// so append value
int i = 0;
while (i < current.length()) {
char ch = current.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
if (maxLineLen > 0
&& previous.length() + 1 + current.length() - i > maxLineLen) {
throw new IOException("Maximum line length limit exceeded");
}
previous.append(' ');
previous.append(current, i, current.length() - i);
} else {
headerLines.add(current);
previous = current;
current = null;
}
if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) {
throw new IOException("Maximum header count exceeded");
}
}
Header[] headers = new Header[headerLines.size()];
for (int i = 0; i < headerLines.size(); i++) {
CharArrayBuffer buffer = (CharArrayBuffer) headerLines.get(i);
try {
headers[i] = parser.parseHeader(buffer);
} catch (ParseException ex) {
throw new ProtocolException(ex.getMessage());
}
}
return headers;
}
/**
* Subclasses must override this method to generate an instance of
* {@link HttpMessage} based on the initial input from the session buffer.
* <p>
* Usually this method is expected to read just the very first line or
* the very first valid from the data stream and based on the input generate
* an appropriate instance of {@link HttpMessage}.
*
* @param sessionBuffer the session input buffer.
* @return HTTP message based on the input from the session buffer.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation.
* @throws ParseException in case of a parse error.
*/
protected abstract HttpMessage parseHead(SessionInputBuffer sessionBuffer)
throws IOException, HttpException, ParseException;
public HttpMessage parse() throws IOException, HttpException {
int st = this.state;
switch (st) {
case HEAD_LINE:
try {
this.message = parseHead(this.sessionBuffer);
} catch (ParseException px) {
throw new ProtocolException(px.getMessage(), px);
}
this.state = HEADERS;
//$FALL-THROUGH$
case HEADERS:
Header[] headers = AbstractMessageParser.parseHeaders(
this.sessionBuffer,
this.maxHeaderCount,
this.maxLineLen,
this.lineParser,
this.headerLines);
this.message.setHeaders(headers);
HttpMessage result = this.message;
this.message = null;
this.headerLines.clear();
this.state = HEAD_LINE;
return result;
default:
throw new IllegalStateException("Inconsistent parser state");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import java.net.Socket;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Default implementation of a client-side HTTP connection.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class DefaultHttpClientConnection extends SocketHttpClientConnection {
public DefaultHttpClientConnection() {
super();
}
public void bind(
final Socket socket,
final HttpParams params) throws IOException {
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
assertNotOpen();
socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
int linger = HttpConnectionParams.getLinger(params);
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
super.bind(socket, params);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
if (isOpen()) {
buffer.append(getRemotePort());
} else {
buffer.append("closed");
}
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* Signals that an HTTP method is not supported.
*
* @since 4.0
*/
public class MethodNotSupportedException extends HttpException {
private static final long serialVersionUID = 3365359036840171201L;
/**
* Creates a new MethodNotSupportedException with the specified detail message.
*
* @param message The exception detail message
*/
public MethodNotSupportedException(final String message) {
super(message);
}
/**
* Creates a new MethodNotSupportedException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public MethodNotSupportedException(final String message, final Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
import java.util.Locale;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.LangUtils;
/**
* Holds all of the variables needed to describe an HTTP connection to a host.
* This includes remote host name, port and scheme.
*
*
* @since 4.0
*/
//@Immutable
public final class HttpHost implements Cloneable, Serializable {
private static final long serialVersionUID = -7529410654042457626L;
/** The default scheme is "http". */
public static final String DEFAULT_SCHEME_NAME = "http";
/** The host to use. */
protected final String hostname;
/** The lowercase host, for {@link #equals} and {@link #hashCode}. */
protected final String lcHostname;
/** The port to use. */
protected final int port;
/** The scheme (lowercased) */
protected final String schemeName;
/**
* Creates a new {@link HttpHost HttpHost}, specifying all values.
* Constructor for HttpHost.
*
* @param hostname the hostname (IP or DNS name)
* @param port the port number.
* <code>-1</code> indicates the scheme default port.
* @param scheme the name of the scheme.
* <code>null</code> indicates the
* {@link #DEFAULT_SCHEME_NAME default scheme}
*/
public HttpHost(final String hostname, int port, final String scheme) {
super();
if (hostname == null) {
throw new IllegalArgumentException("Host name may not be null");
}
this.hostname = hostname;
this.lcHostname = hostname.toLowerCase(Locale.ENGLISH);
if (scheme != null) {
this.schemeName = scheme.toLowerCase(Locale.ENGLISH);
} else {
this.schemeName = DEFAULT_SCHEME_NAME;
}
this.port = port;
}
/**
* Creates a new {@link HttpHost HttpHost}, with default scheme.
*
* @param hostname the hostname (IP or DNS name)
* @param port the port number.
* <code>-1</code> indicates the scheme default port.
*/
public HttpHost(final String hostname, int port) {
this(hostname, port, null);
}
/**
* Creates a new {@link HttpHost HttpHost}, with default scheme and port.
*
* @param hostname the hostname (IP or DNS name)
*/
public HttpHost(final String hostname) {
this(hostname, -1, null);
}
/**
* Copy constructor for {@link HttpHost HttpHost}.
*
* @param httphost the HTTP host to copy details from
*/
public HttpHost (final HttpHost httphost) {
this(httphost.hostname, httphost.port, httphost.schemeName);
}
/**
* Returns the host name.
*
* @return the host name (IP or DNS name)
*/
public String getHostName() {
return this.hostname;
}
/**
* Returns the port.
*
* @return the host port, or <code>-1</code> if not set
*/
public int getPort() {
return this.port;
}
/**
* Returns the scheme name.
*
* @return the scheme name
*/
public String getSchemeName() {
return this.schemeName;
}
/**
* Return the host URI, as a string.
*
* @return the host URI
*/
public String toURI() {
CharArrayBuffer buffer = new CharArrayBuffer(32);
buffer.append(this.schemeName);
buffer.append("://");
buffer.append(this.hostname);
if (this.port != -1) {
buffer.append(':');
buffer.append(Integer.toString(this.port));
}
return buffer.toString();
}
/**
* Obtains the host string, without scheme prefix.
*
* @return the host string, for example <code>localhost:8080</code>
*/
public String toHostString() {
if (this.port != -1) {
//the highest port number is 65535, which is length 6 with the addition of the colon
CharArrayBuffer buffer = new CharArrayBuffer(this.hostname.length() + 6);
buffer.append(this.hostname);
buffer.append(":");
buffer.append(Integer.toString(this.port));
return buffer.toString();
} else {
return this.hostname;
}
}
public String toString() {
return toURI();
}
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj instanceof HttpHost) {
HttpHost that = (HttpHost) obj;
return this.lcHostname.equals(that.lcHostname)
&& this.port == that.port
&& this.schemeName.equals(that.schemeName);
} else {
return false;
}
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.lcHostname);
hash = LangUtils.hashCode(hash, this.port);
hash = LangUtils.hashCode(hash, this.schemeName);
return hash;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* Signals a malformed chunked stream.
*
* @since 4.0
*/
public class MalformedChunkCodingException extends IOException {
private static final long serialVersionUID = 2158560246948994524L;
/**
* Creates a MalformedChunkCodingException without a detail message.
*/
public MalformedChunkCodingException() {
super();
}
/**
* Creates a MalformedChunkCodingException with the specified detail message.
*
* @param message The exception detail message
*/
public MalformedChunkCodingException(final String message) {
super(message);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* A client-side HTTP connection, which can be used for sending
* requests and receiving responses.
*
* @since 4.0
*/
public interface HttpClientConnection extends HttpConnection {
/**
* Checks if response data is available from the connection. May wait for
* the specified time until some data becomes available. Note that some
* implementations may completely ignore the timeout parameter.
*
* @param timeout the maximum time in milliseconds to wait for data
* @return true if data is available; false if there was no data available
* even after waiting for <code>timeout</code> milliseconds.
* @throws IOException if an error happens on the connection
*/
boolean isResponseAvailable(int timeout)
throws IOException;
/**
* Sends the request line and all headers over the connection.
* @param request the request whose headers to send.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void sendRequestHeader(HttpRequest request)
throws HttpException, IOException;
/**
* Sends the request entity over the connection.
* @param request the request whose entity to send.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void sendRequestEntity(HttpEntityEnclosingRequest request)
throws HttpException, IOException;
/**
* Receives the request line and headers of the next response available from
* this connection. The caller should examine the HttpResponse object to
* find out if it should try to receive a response entity as well.
*
* @return a new HttpResponse object with status line and headers
* initialized.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
HttpResponse receiveResponseHeader()
throws HttpException, IOException;
/**
* Receives the next response entity available from this connection and
* attaches it to an existing HttpResponse object.
*
* @param response the response to attach the entity to
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void receiveResponseEntity(HttpResponse response)
throws HttpException, IOException;
/**
* Writes out all pending buffered data over the open connection.
*
* @throws IOException in case of an I/O error
*/
void flush() throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* Signals that an HTTP protocol violation has occurred.
* For example a malformed status line or headers, a missing message body, etc.
*
*
* @since 4.0
*/
public class ProtocolException extends HttpException {
private static final long serialVersionUID = -2143571074341228994L;
/**
* Creates a new ProtocolException with a <tt>null</tt> detail message.
*/
public ProtocolException() {
super();
}
/**
* Creates a new ProtocolException with the specified detail message.
*
* @param message The exception detail message
*/
public ProtocolException(String message) {
super(message);
}
/**
* Creates a new ProtocolException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public ProtocolException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The first line of a Response message is the Status-Line, consisting
* of the protocol version followed by a numeric status code and its
* associated textual phrase, with each element separated by SP
* characters. No CR or LF is allowed except in the final CRLF sequence.
* <pre>
* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
* </pre>
*
* @see HttpStatus
* @version $Id: StatusLine.java 937295 2010-04-23 13:44:00Z olegk $
*
* @since 4.0
*/
public interface StatusLine {
ProtocolVersion getProtocolVersion();
int getStatusCode();
String getReasonPhrase();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.util.Locale;
/**
* After receiving and interpreting a request message, a server responds
* with an HTTP response message.
* <pre>
* Response = Status-Line
* *(( general-header
* | response-header
* | entity-header ) CRLF)
* CRLF
* [ message-body ]
* </pre>
*
* @since 4.0
*/
public interface HttpResponse extends HttpMessage {
/**
* Obtains the status line of this response.
* The status line can be set using one of the
* {@link #setStatusLine setStatusLine} methods,
* or it can be initialized in a constructor.
*
* @return the status line, or <code>null</code> if not yet set
*/
StatusLine getStatusLine();
/**
* Sets the status line of this response.
*
* @param statusline the status line of this response
*/
void setStatusLine(StatusLine statusline);
/**
* Sets the status line of this response.
* The reason phrase will be determined based on the current
* {@link #getLocale locale}.
*
* @param ver the HTTP version
* @param code the status code
*/
void setStatusLine(ProtocolVersion ver, int code);
/**
* Sets the status line of this response with a reason phrase.
*
* @param ver the HTTP version
* @param code the status code
* @param reason the reason phrase, or <code>null</code> to omit
*/
void setStatusLine(ProtocolVersion ver, int code, String reason);
/**
* Updates the status line of this response with a new status code.
* The status line can only be updated if it is available. It must
* have been set either explicitly or in a constructor.
* <br/>
* The reason phrase will be updated according to the new status code,
* based on the current {@link #getLocale locale}. It can be set
* explicitly using {@link #setReasonPhrase setReasonPhrase}.
*
* @param code the HTTP status code.
*
* @throws IllegalStateException
* if the status line has not be set
*
* @see HttpStatus
* @see #setStatusLine(StatusLine)
* @see #setStatusLine(ProtocolVersion,int)
*/
void setStatusCode(int code)
throws IllegalStateException;
/**
* Updates the status line of this response with a new reason phrase.
* The status line can only be updated if it is available. It must
* have been set either explicitly or in a constructor.
*
* @param reason the new reason phrase as a single-line string, or
* <code>null</code> to unset the reason phrase
*
* @throws IllegalStateException
* if the status line has not be set
*
* @see #setStatusLine(StatusLine)
* @see #setStatusLine(ProtocolVersion,int)
*/
void setReasonPhrase(String reason)
throws IllegalStateException;
/**
* Obtains the message entity of this response, if any.
* The entity is provided by calling {@link #setEntity setEntity}.
*
* @return the response entity, or
* <code>null</code> if there is none
*/
HttpEntity getEntity();
/**
* Associates a response entity with this response.
*
* @param entity the entity to associate with this response, or
* <code>null</code> to unset
*/
void setEntity(HttpEntity entity);
/**
* Obtains the locale of this response.
* The locale is used to determine the reason phrase
* for the {@link #setStatusCode status code}.
* It can be changed using {@link #setLocale setLocale}.
*
* @return the locale of this response, never <code>null</code>
*/
Locale getLocale();
/**
* Changes the locale of this response.
* If there is a status line, it's reason phrase will be updated
* according to the status code and new locale.
*
* @param loc the new locale
*
* @see #getLocale getLocale
* @see #setStatusCode setStatusCode
*/
void setLocale(Locale loc);
}
| Java |
/*
* $Header: $
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* A request with an entity.
*
* @since 4.0
*/
public interface HttpEntityEnclosingRequest extends HttpRequest {
/**
* Tells if this request should use the expect-continue handshake.
* The expect continue handshake gives the server a chance to decide
* whether to accept the entity enclosing request before the possibly
* lengthy entity is sent across the wire.
* @return true if the expect continue handshake should be used, false if
* not.
*/
boolean expectContinue();
/**
* Associates the entity with this request.
*
* @param entity the entity to send.
*/
void setEntity(HttpEntity entity);
/**
* Returns the entity associated with this request.
*
* @return entity
*/
HttpEntity getEntity();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* A request message from a client to a server includes, within the
* first line of that message, the method to be applied to the resource,
* the identifier of the resource, and the protocol version in use.
* <pre>
* Request = Request-Line
* *(( general-header
* | request-header
* | entity-header ) CRLF)
* CRLF
* [ message-body ]
* </pre>
*
* @since 4.0
*/
public interface HttpRequest extends HttpMessage {
/**
* Returns the request line of this request.
* @return the request line.
*/
RequestLine getRequestLine();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.params.HttpParams;
/**
* HTTP messages consist of requests from client to server and responses
* from server to client.
* <pre>
* HTTP-message = Request | Response ; HTTP/1.1 messages
* </pre>
* <p>
* HTTP messages use the generic message format of RFC 822 for
* transferring entities (the payload of the message). Both types
* of message consist of a start-line, zero or more header fields
* (also known as "headers"), an empty line (i.e., a line with nothing
* preceding the CRLF) indicating the end of the header fields,
* and possibly a message-body.
* </p>
* <pre>
* generic-message = start-line
* *(message-header CRLF)
* CRLF
* [ message-body ]
* start-line = Request-Line | Status-Line
* </pre>
*
* @since 4.0
*/
public interface HttpMessage {
/**
* Returns the protocol version this message is compatible with.
*/
ProtocolVersion getProtocolVersion();
/**
* Checks if a certain header is present in this message. Header values are
* ignored.
*
* @param name the header name to check for.
* @return true if at least one header with this name is present.
*/
boolean containsHeader(String name);
/**
* Returns all the headers with a specified name of this message. Header values
* are ignored. Headers are orderd in the sequence they will be sent over a
* connection.
*
* @param name the name of the headers to return.
* @return the headers whose name property equals <code>name</code>.
*/
Header[] getHeaders(String name);
/**
* Returns the first header with a specified name of this message. Header
* values are ignored. If there is more than one matching header in the
* message the first element of {@link #getHeaders(String)} is returned.
* If there is no matching header in the message <code>null</code> is
* returned.
*
* @param name the name of the header to return.
* @return the first header whose name property equals <code>name</code>
* or <code>null</code> if no such header could be found.
*/
Header getFirstHeader(String name);
/**
* Returns the last header with a specified name of this message. Header values
* are ignored. If there is more than one matching header in the message the
* last element of {@link #getHeaders(String)} is returned. If there is no
* matching header in the message <code>null</code> is returned.
*
* @param name the name of the header to return.
* @return the last header whose name property equals <code>name</code>.
* or <code>null</code> if no such header could be found.
*/
Header getLastHeader(String name);
/**
* Returns all the headers of this message. Headers are orderd in the sequence
* they will be sent over a connection.
*
* @return all the headers of this message
*/
Header[] getAllHeaders();
/**
* Adds a header to this message. The header will be appended to the end of
* the list.
*
* @param header the header to append.
*/
void addHeader(Header header);
/**
* Adds a header to this message. The header will be appended to the end of
* the list.
*
* @param name the name of the header.
* @param value the value of the header.
*/
void addHeader(String name, String value);
/**
* Overwrites the first header with the same name. The new header will be appended to
* the end of the list, if no header with the given name can be found.
*
* @param header the header to set.
*/
void setHeader(Header header);
/**
* Overwrites the first header with the same name. The new header will be appended to
* the end of the list, if no header with the given name can be found.
*
* @param name the name of the header.
* @param value the value of the header.
*/
void setHeader(String name, String value);
/**
* Overwrites all the headers in the message.
*
* @param headers the array of headers to set.
*/
void setHeaders(Header[] headers);
/**
* Removes a header from this message.
*
* @param header the header to remove.
*/
void removeHeader(Header header);
/**
* Removes all headers with a certain name from this message.
*
* @param name The name of the headers to remove.
*/
void removeHeaders(String name);
/**
* Returns an iterator of all the headers.
*
* @return Iterator that returns Header objects in the sequence they are
* sent over a connection.
*/
HeaderIterator headerIterator();
/**
* Returns an iterator of the headers with a given name.
*
* @param name the name of the headers over which to iterate, or
* <code>null</code> for all headers
*
* @return Iterator that returns Header objects with the argument name
* in the sequence they are sent over a connection.
*/
HeaderIterator headerIterator(String name);
/**
* Returns the parameters effective for this message as set by
* {@link #setParams(HttpParams)}.
*/
HttpParams getParams();
/**
* Provides parameters to be used for the processing of this message.
* @param params the parameters
*/
void setParams(HttpParams params);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.Serializable;
/**
* A resizable byte array.
*
* @since 4.0
*/
public final class ByteArrayBuffer implements Serializable {
private static final long serialVersionUID = 4359112959524048036L;
private byte[] buffer;
private int len;
/**
* Creates an instance of {@link ByteArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public ByteArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new byte[capacity];
}
private void expand(int newlen) {
byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends <code>b</code> byte to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional byte.
*
* @param b the byte to be appended.
*/
public void append(int b) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = (byte)b;
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased if necessary to accommodate all <code>len</code> chars.
* <p>
* The chars are converted to bytes using simple cast.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (byte) b[i1];
}
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* char array buffer starting at index <code>off</code>. The capacity
* of the buffer is increased if necessary to accommodate all
* <code>len</code> chars.
* <p>
* The chars are converted to bytes using simple cast.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Clears content of the buffer. The underlying byte array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of bytes.
*
* @return byte array
*/
public byte[] toByteArray() {
byte[] b = new byte[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>byte</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired byte value.
* @return the byte value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public int byteAt(int i) {
return this.buffer[i];
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended bytes, beyond which an allocation
* will occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (byte count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*
* @since 4.1
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Returns reference to the underlying byte array.
*
* @return the byte array.
*/
public byte[] buffer() {
return this.buffer;
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified byte, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such byte occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param b the byte to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the byte in the buffer
* within the given bounds, or <code>-1</code> if the byte does
* not occur.
*
* @since 4.1
*/
public int indexOf(byte b, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == b) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified byte, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such byte occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param b the byte to search for.
* @return the index of the first occurrence of the byte in the
* buffer, or <code>-1</code> if the byte does not occur.
*
* @since 4.1
*/
public int indexOf(byte b) {
return indexOf(b, 0, this.len);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.protocol.HTTP;
/**
* Static helpers for dealing with {@link HttpEntity}s.
*
* @since 4.0
*/
public final class EntityUtils {
private EntityUtils() {
}
/**
* Ensures that the entity content is fully consumed and the content stream, if exists,
* is closed.
*
* @param entity
* @throws IOException if an error occurs reading the input stream
*
* @since 4.1
*/
public static void consume(final HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}
/**
* Read the contents of an entity and return it as a byte array.
*
* @param entity
* @return byte array containing the entity content. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws IOException if an error occurs reading the input stream
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
*/
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ByteArrayBuffer buffer = new ByteArrayBuffer(i);
byte[] tmp = new byte[4096];
int l;
while((l = instream.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toByteArray();
} finally {
instream.close();
}
}
/**
* Obtains character set of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*/
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
/**
* Obtains mime type of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*
* @since 4.1
*/
public static String getContentMimeType(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String mimeType = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
mimeType = values[0].getName();
}
}
return mimeType;
}
/**
* Get the entity content as a String, using the provided default character set
* if none is found in the entity.
* If defaultCharset is null, the default "ISO-8859-1" is used.
*
* @param entity must not be null
* @param defaultCharset character set to be applied if none found in the entity
* @return the entity content as a String. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
/**
* Read the contents of an entity and return it as a String.
* The content is converted using the character set from the entity (if any),
* failing that, "ISO-8859-1" is used.
*
* @param entity
* @return String containing the content.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(final HttpEntity entity)
throws IOException, ParseException {
return toString(entity, null);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
/**
* A set of utility methods to help produce consistent
* {@link Object#equals equals} and {@link Object#hashCode hashCode} methods.
*
*
* @since 4.0
*/
public final class LangUtils {
public static final int HASH_SEED = 17;
public static final int HASH_OFFSET = 37;
/** Disabled default constructor. */
private LangUtils() {
}
public static int hashCode(final int seed, final int hashcode) {
return seed * HASH_OFFSET + hashcode;
}
public static int hashCode(final int seed, final boolean b) {
return hashCode(seed, b ? 1 : 0);
}
public static int hashCode(final int seed, final Object obj) {
return hashCode(seed, obj != null ? obj.hashCode() : 0);
}
/**
* Check if two objects are equal.
*
* @param obj1 first object to compare, may be {@code null}
* @param obj2 second object to compare, may be {@code null}
* @return {@code true} if the objects are equal or both null
*/
public static boolean equals(final Object obj1, final Object obj2) {
return obj1 == null ? obj2 == null : obj1.equals(obj2);
}
/**
* Check if two object arrays are equal.
* <p>
* <ul>
* <li>If both parameters are null, return {@code true}</li>
* <li>If one parameter is null, return {@code false}</li>
* <li>If the array lengths are different, return {@code false}</li>
* <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li>
* <li>Return {@code true}</li>
* </ul>
*
* @param a1 first array to compare, may be {@code null}
* @param a2 second array to compare, may be {@code null}
* @return {@code true} if the arrays are equal or both null
*/
public static boolean equals(final Object[] a1, final Object[] a2) {
if (a1 == null) {
if (a2 == null) {
return true;
} else {
return false;
}
} else {
if (a2 != null && a1.length == a2.length) {
for (int i = 0; i < a1.length; i++) {
if (!equals(a1[i], a2[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.Serializable;
import org.apache.ogt.http.protocol.HTTP;
/**
* A resizable char array.
*
* @since 4.0
*/
public final class CharArrayBuffer implements Serializable {
private static final long serialVersionUID = -6208952725094867135L;
private char[] buffer;
private int len;
/**
* Creates an instance of {@link CharArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public CharArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new char[capacity];
}
private void expand(int newlen) {
char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> chars.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends chars of the given string to this buffer. The capacity of the
* buffer is increased, if necessary, to accommodate all chars.
*
* @param str the string.
*/
public void append(String str) {
if (str == null) {
str = "null";
}
int strlen = str.length();
int newlen = this.len + strlen;
if (newlen > this.buffer.length) {
expand(newlen);
}
str.getChars(0, strlen, this.buffer, this.len);
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* buffer starting at index <code>off</code>. The capacity of the
* destination buffer is increased, if necessary, to accommodate all
* <code>len</code> chars.
*
* @param b the source buffer to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer, off, len);
}
/**
* Appends all chars to this buffer from the given source buffer starting
* at index <code>0</code>. The capacity of the destination buffer is
* increased, if necessary, to accommodate all {@link #length()} chars.
*
* @param b the source buffer to be appended.
*/
public void append(final CharArrayBuffer b) {
if (b == null) {
return;
}
append(b.buffer,0, b.len);
}
/**
* Appends <code>ch</code> char to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional char.
*
* @param ch the char to be appended.
*/
public void append(char ch) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = ch;
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (char) (b[i1] & 0xff);
}
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final ByteArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Appends chars of the textual representation of the given object to this
* buffer. The capacity of the buffer is increased, if necessary, to
* accommodate all chars.
*
* @param obj the object.
*/
public void append(final Object obj) {
append(String.valueOf(obj));
}
/**
* Clears content of the buffer. The underlying char array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of chars.
*
* @return char array
*/
public char[] toCharArray() {
char[] b = new char[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>char</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired char value.
* @return the char value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public char charAt(int i) {
return this.buffer[i];
}
/**
* Returns reference to the underlying char array.
*
* @return the char array.
*/
public char[] buffer() {
return this.buffer;
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended chars, beyond which an allocation will
* occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (char count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such character occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the character in the buffer
* within the given bounds, or <code>-1</code> if the character does
* not occur.
*/
public int indexOf(int ch, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == ch) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such character occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @return the index of the first occurrence of the character in the
* buffer, or <code>-1</code> if the character does not occur.
*/
public int indexOf(int ch) {
return indexOf(ch, 0, this.len);
}
/**
* Returns a substring of this buffer. The substring begins at the specified
* <code>beginIndex</code> and extends to the character at index
* <code>endIndex - 1</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception StringIndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substring(int beginIndex, int endIndex) {
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
/**
* Returns a substring of this buffer with leading and trailing whitespace
* omitted. The substring begins with the first non-whitespace character
* from <code>beginIndex</code> and extends to the last
* non-whitespace character with the index lesser than
* <code>endIndex</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substringTrimmed(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex);
}
if (endIndex > this.len) {
throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len);
}
if (beginIndex > endIndex) {
throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex);
}
while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) {
beginIndex++;
}
while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) {
endIndex--;
}
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
public String toString() {
return new String(this.buffer, 0, this.len);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.protocol.HTTP;
/**
* The home for utility methods that handle various encoding tasks.
*
*
* @since 4.0
*/
public final class EncodingUtils {
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(
final byte[] data,
int offset,
int length,
String charset
) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
try {
return new String(data, offset, length, charset);
} catch (UnsupportedEncodingException e) {
return new String(data, offset, length);
}
}
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(final byte[] data, final String charset) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return getString(data, 0, data.length, charset);
}
/**
* Converts the specified string to a byte array. If the charset is not supported the
* default system charset is used.
*
* @param data the string to be encoded
* @param charset the desired character encoding
* @return The resulting byte array.
*/
public static byte[] getBytes(final String data, final String charset) {
if (data == null) {
throw new IllegalArgumentException("data may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
try {
return data.getBytes(charset);
} catch (UnsupportedEncodingException e) {
return data.getBytes();
}
}
/**
* Converts the specified string to byte array of ASCII characters.
*
* @param data the string to be encoded
* @return The string as a byte array.
*/
public static byte[] getAsciiBytes(final String data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
try {
return data.getBytes(HTTP.US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error("HttpClient requires ASCII support");
}
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data, int offset, int length) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
try {
return new String(data, offset, length, HTTP.US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error("HttpClient requires ASCII support");
}
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return getAsciiString(data, 0, data.length);
}
/**
* This class should not be instantiated.
*/
private EncodingUtils() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.ArrayList;
/**
* Provides access to version information for HTTP components.
* Static methods are used to extract version information from property
* files that are automatically packaged with HTTP component release JARs.
* <br/>
* All available version information is provided in strings, where
* the string format is informal and subject to change without notice.
* Version information is provided for debugging output and interpretation
* by humans, not for automated processing in applications.
*
* @since 4.0
*/
public class VersionInfo {
/** A string constant for unavailable information. */
public final static String UNAVAILABLE = "UNAVAILABLE";
/** The filename of the version information files. */
public final static String VERSION_PROPERTY_FILE = "version.properties";
// the property names
public final static String PROPERTY_MODULE = "info.module";
public final static String PROPERTY_RELEASE = "info.release";
public final static String PROPERTY_TIMESTAMP = "info.timestamp";
/** The package that contains the version information. */
private final String infoPackage;
/** The module from the version info. */
private final String infoModule;
/** The release from the version info. */
private final String infoRelease;
/** The timestamp from the version info. */
private final String infoTimestamp;
/** The classloader from which the version info was obtained. */
private final String infoClassloader;
/**
* Instantiates version information.
*
* @param pckg the package
* @param module the module, or <code>null</code>
* @param release the release, or <code>null</code>
* @param time the build time, or <code>null</code>
* @param clsldr the class loader, or <code>null</code>
*/
protected VersionInfo(String pckg, String module,
String release, String time, String clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
infoPackage = pckg;
infoModule = (module != null) ? module : UNAVAILABLE;
infoRelease = (release != null) ? release : UNAVAILABLE;
infoTimestamp = (time != null) ? time : UNAVAILABLE;
infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE;
}
/**
* Obtains the package name.
* The package name identifies the module or informal unit.
*
* @return the package name, never <code>null</code>
*/
public final String getPackage() {
return infoPackage;
}
/**
* Obtains the name of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the module name, never <code>null</code>
*/
public final String getModule() {
return infoModule;
}
/**
* Obtains the release of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the release version, never <code>null</code>
*/
public final String getRelease() {
return infoRelease;
}
/**
* Obtains the timestamp of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the timestamp, never <code>null</code>
*/
public final String getTimestamp() {
return infoTimestamp;
}
/**
* Obtains the classloader used to read the version information.
* This is just the <code>toString</code> output of the classloader,
* since the version information should not keep a reference to
* the classloader itself. That could prevent garbage collection.
*
* @return the classloader description, never <code>null</code>
*/
public final String getClassloader() {
return infoClassloader;
}
/**
* Provides the version information in human-readable format.
*
* @return a string holding this version information
*/
public String toString() {
StringBuffer sb = new StringBuffer
(20 + infoPackage.length() + infoModule.length() +
infoRelease.length() + infoTimestamp.length() +
infoClassloader.length());
sb.append("VersionInfo(")
.append(infoPackage).append(':').append(infoModule);
// If version info is missing, a single "UNAVAILABLE" for the module
// is sufficient. Everything else just clutters the output.
if (!UNAVAILABLE.equals(infoRelease))
sb.append(':').append(infoRelease);
if (!UNAVAILABLE.equals(infoTimestamp))
sb.append(':').append(infoTimestamp);
sb.append(')');
if (!UNAVAILABLE.equals(infoClassloader))
sb.append('@').append(infoClassloader);
return sb.toString();
}
/**
* Loads version information for a list of packages.
*
* @param pckgs the packages for which to load version info
* @param clsldr the classloader to load from, or
* <code>null</code> for the thread context classloader
*
* @return the version information for all packages found,
* never <code>null</code>
*/
public final static VersionInfo[] loadVersionInfo(String[] pckgs,
ClassLoader clsldr) {
if (pckgs == null) {
throw new IllegalArgumentException
("Package identifier list must not be null.");
}
ArrayList vil = new ArrayList(pckgs.length);
for (int i=0; i<pckgs.length; i++) {
VersionInfo vi = loadVersionInfo(pckgs[i], clsldr);
if (vi != null)
vil.add(vi);
}
return (VersionInfo[]) vil.toArray(new VersionInfo[vil.size()]);
}
/**
* Loads version information for a package.
*
* @param pckg the package for which to load version information,
* for example "org.apache.ogt.http".
* The package name should NOT end with a dot.
* @param clsldr the classloader to load from, or
* <code>null</code> for the thread context classloader
*
* @return the version information for the argument package, or
* <code>null</code> if not available
*/
public final static VersionInfo loadVersionInfo(final String pckg,
ClassLoader clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
if (clsldr == null)
clsldr = Thread.currentThread().getContextClassLoader();
Properties vip = null; // version info properties, if available
try {
// org.apache.ogt.http becomes
// org/apache/http/version.properties
InputStream is = clsldr.getResourceAsStream
(pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE);
if (is != null) {
try {
Properties props = new Properties();
props.load(is);
vip = props;
} finally {
is.close();
}
}
} catch (IOException ex) {
// shamelessly munch this exception
}
VersionInfo result = null;
if (vip != null)
result = fromMap(pckg, vip, clsldr);
return result;
}
/**
* Instantiates version information from properties.
*
* @param pckg the package for the version information
* @param info the map from string keys to string values,
* for example {@link java.util.Properties}
* @param clsldr the classloader, or <code>null</code>
*
* @return the version information
*/
protected final static VersionInfo fromMap(String pckg, Map info,
ClassLoader clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
String module = null;
String release = null;
String timestamp = null;
if (info != null) {
module = (String) info.get(PROPERTY_MODULE);
if ((module != null) && (module.length() < 1))
module = null;
release = (String) info.get(PROPERTY_RELEASE);
if ((release != null) && ((release.length() < 1) ||
(release.equals("${pom.version}"))))
release = null;
timestamp = (String) info.get(PROPERTY_TIMESTAMP);
if ((timestamp != null) &&
((timestamp.length() < 1) ||
(timestamp.equals("${mvn.timestamp}")))
)
timestamp = null;
} // if info
String clsldrstr = null;
if (clsldr != null)
clsldrstr = clsldr.toString();
return new VersionInfo(pckg, module, release, timestamp, clsldrstr);
}
} // class VersionInfo
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.lang.reflect.Method;
/**
* The home for utility methods that handle various exception-related tasks.
*
*
* @since 4.0
*/
public final class ExceptionUtils {
/** A reference to Throwable's initCause method, or null if it's not there in this JVM */
static private final Method INIT_CAUSE_METHOD = getInitCauseMethod();
/**
* Returns a <code>Method<code> allowing access to
* {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable},
* or <code>null</code> if the method
* does not exist.
*
* @return A <code>Method<code> for <code>Throwable.initCause</code>, or
* <code>null</code> if unavailable.
*/
static private Method getInitCauseMethod() {
try {
Class[] paramsClasses = new Class[] { Throwable.class };
return Throwable.class.getMethod("initCause", paramsClasses);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
*
* @param throwable The throwable.
* @param cause The cause of the throwable.
*/
public static void initCause(Throwable throwable, Throwable cause) {
if (INIT_CAUSE_METHOD != null) {
try {
INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause });
} catch (Exception e) {
// Well, with no logging, the only option is to munch the exception
}
}
}
private ExceptionUtils() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The point of access to the statistics of an {@link HttpConnection}.
*
* @since 4.0
*/
public interface HttpConnectionMetrics {
/**
* Returns the number of requests transferred over the connection,
* 0 if not available.
*/
long getRequestCount();
/**
* Returns the number of responses transferred over the connection,
* 0 if not available.
*/
long getResponseCount();
/**
* Returns the number of bytes transferred over the connection,
* 0 if not available.
*/
long getSentBytesCount();
/**
* Returns the number of bytes transferred over the connection,
* 0 if not available.
*/
long getReceivedBytesCount();
/**
* Return the value for the specified metric.
*
*@param metricName the name of the metric to query.
*
*@return the object representing the metric requested,
* <code>null</code> if the metric cannot not found.
*/
Object getMetric(String metricName);
/**
* Resets the counts
*
*/
void reset();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A factory for {@link HttpResponse HttpResponse} objects.
*
* @since 4.0
*/
public interface HttpResponseFactory {
/**
* Creates a new response from status line elements.
*
* @param ver the protocol version
* @param status the status code
* @param context the context from which to determine the locale
* for looking up a reason phrase to the status code, or
* <code>null</code> to use the default locale
*
* @return the new response with an initialized status line
*/
HttpResponse newHttpResponse(ProtocolVersion ver, int status,
HttpContext context);
/**
* Creates a new response from a status line.
*
* @param statusline the status line
* @param context the context from which to determine the locale
* for looking up a reason phrase if the status code
* is updated, or
* <code>null</code> to use the default locale
*
* @return the new response with the argument status line
*/
HttpResponse newHttpResponse(StatusLine statusline,
HttpContext context);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Session output buffer for blocking connections. This interface is similar to
* OutputStream class, but it also provides methods for writing lines of text.
* <p>
* Implementing classes are also expected to manage intermediate data buffering
* for optimal output performance.
*
* @since 4.0
*/
public interface SessionOutputBuffer {
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this session buffer.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b, int off, int len) throws IOException;
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this session buffer.
*
* @param b the data.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b) throws IOException;
/**
* Writes the specified byte to this session buffer.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/**
* Writes characters from the specified string followed by a line delimiter
* to this session buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param s the line.
* @exception IOException if an I/O error occurs.
*/
void writeLine(String s) throws IOException;
/**
* Writes characters from the specified char array followed by a line
* delimiter to this session buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param buffer the buffer containing chars of the line.
* @exception IOException if an I/O error occurs.
*/
void writeLine(CharArrayBuffer buffer) throws IOException;
/**
* Flushes this session buffer and forces any buffered output bytes
* to be written out. The general contract of <code>flush</code> is
* that calling it is an indication that, if any bytes previously
* written have been buffered by the implementation of the output
* stream, such bytes should immediately be written to their
* intended destination.
*
* @exception IOException if an I/O error occurs.
*/
void flush() throws IOException;
/**
* Returns {@link HttpTransportMetrics} for this session buffer.
*
* @return transport metrics.
*/
HttpTransportMetrics getMetrics();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
/**
* Abstract message parser intended to build HTTP messages from an arbitrary
* data source.
*
* @since 4.0
*/
public interface HttpMessageParser {
/**
* Generates an instance of {@link HttpMessage} from the underlying data
* source.
*
* @return HTTP message
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
HttpMessage parse()
throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* EOF sensor.
*
* @since 4.0
*/
public interface EofSensor {
boolean isEof();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
/**
* Abstract message writer intended to serialize HTTP messages to an arbitrary
* data sink.
*
* @since 4.0
*/
public interface HttpMessageWriter {
/**
* Serializes an instance of {@link HttpMessage} to the underlying data
* sink.
*
* @param message
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
void write(HttpMessage message)
throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* The point of access to the statistics of {@link SessionInputBuffer} or
* {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public interface HttpTransportMetrics {
/**
* Returns the number of bytes transferred.
*/
long getBytesTransferred();
/**
* Resets the counts
*/
void reset();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Session input buffer for blocking connections. This interface is similar to
* InputStream class, but it also provides methods for reading lines of text.
* <p>
* Implementing classes are also expected to manage intermediate data buffering
* for optimal input performance.
*
* @since 4.0
*/
public interface SessionInputBuffer {
/**
* Reads up to <code>len</code> bytes of data from the session buffer into
* an array of bytes. An attempt is made to read as many as
* <code>len</code> bytes, but a smaller number may be read, possibly
* zero. The number of bytes actually read is returned as an integer.
*
* <p> This method blocks until input data is available, end of file is
* detected, or an exception is thrown.
*
* <p> If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <code>IndexOutOfBoundsException</code> is
* thrown.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Reads some number of bytes from the session buffer and stores them into
* the buffer array <code>b</code>. The number of bytes actually read is
* returned as an integer. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> is there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b) throws IOException;
/**
* Reads the next byte of data from this session buffer. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
int read() throws IOException;
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer into the given line buffer. The number of chars actually
* read is returned as an integer. The line delimiter itself is discarded.
* If no char is available because the end of the stream has been reached,
* the value <code>-1</code> is returned. This method blocks until input
* data is available, end of file is detected, or an exception is thrown.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param buffer the line buffer.
* @return one line of characters
* @exception IOException if an I/O error occurs.
*/
int readLine(CharArrayBuffer buffer) throws IOException;
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer. The line delimiter itself is discarded. If no char is
* available because the end of the stream has been reached,
* <code>null</code> is returned. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @return HTTP line as a string
* @exception IOException if an I/O error occurs.
*/
String readLine() throws IOException;
/** Blocks until some data becomes available in the session buffer or the
* given timeout period in milliseconds elapses. If the timeout value is
* <code>0</code> this method blocks indefinitely.
*
* @param timeout in milliseconds.
* @return <code>true</code> if some data is available in the session
* buffer or <code>false</code> otherwise.
* @exception IOException if an I/O error occurs.
*/
boolean isDataAvailable(int timeout) throws IOException;
/**
* Returns {@link HttpTransportMetrics} for this session buffer.
*
* @return transport metrics.
*/
HttpTransportMetrics getMetrics();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* Basic buffer properties.
*
* @since 4.1
*/
public interface BufferInfo {
/**
* Return length data stored in the buffer
*
* @return data length
*/
int length();
/**
* Returns total capacity of the buffer
*
* @return total capacity
*/
int capacity();
/**
* Returns available space in the buffer.
*
* @return available space.
*/
int available();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
import org.apache.ogt.http.protocol.HttpContext;
/**
* HTTP protocol interceptor is a routine that implements a specific aspect of
* the HTTP protocol. Usually protocol interceptors are expected to act upon
* one specific header or a group of related headers of the incoming message
* or populate the outgoing message with one specific header or a group of
* related headers.
* <p>
* Protocol Interceptors can also manipulate content entities enclosed with messages.
* Usually this is accomplished by using the 'Decorator' pattern where a wrapper
* entity class is used to decorate the original entity.
* <p>
* Protocol interceptors must be implemented as thread-safe. Similarly to
* servlets, protocol interceptors should not use instance variables unless
* access to those variables is synchronized.
*
* @since 4.0
*/
public interface HttpRequestInterceptor {
/**
* Processes a request.
* On the client side, this step is performed before the request is
* sent to the server. On the server side, this step is performed
* on incoming messages before the message body is evaluated.
*
* @param request the request to preprocess
* @param context the context for the request
*
* @throws HttpException in case of an HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void process(HttpRequest request, HttpContext context)
throws HttpException, IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Represents a protocol version. The "major.minor" numbering
* scheme is used to indicate versions of the protocol.
* <p>
* This class defines a protocol version as a combination of
* protocol name, major version number, and minor version number.
* Note that {@link #equals} and {@link #hashCode} are defined as
* final here, they cannot be overridden in derived classes.
* </p>
*
* @since 4.0
*/
public class ProtocolVersion implements Serializable, Cloneable {
private static final long serialVersionUID = 8950662842175091068L;
/** Name of the protocol. */
protected final String protocol;
/** Major version number of the protocol */
protected final int major;
/** Minor version number of the protocol */
protected final int minor;
/**
* Create a protocol version designator.
*
* @param protocol the name of the protocol, for example "HTTP"
* @param major the major version number of the protocol
* @param minor the minor version number of the protocol
*/
public ProtocolVersion(String protocol, int major, int minor) {
if (protocol == null) {
throw new IllegalArgumentException
("Protocol name must not be null.");
}
if (major < 0) {
throw new IllegalArgumentException
("Protocol major version number must not be negative.");
}
if (minor < 0) {
throw new IllegalArgumentException
("Protocol minor version number may not be negative");
}
this.protocol = protocol;
this.major = major;
this.minor = minor;
}
/**
* Returns the name of the protocol.
*
* @return the protocol name
*/
public final String getProtocol() {
return protocol;
}
/**
* Returns the major version number of the protocol.
*
* @return the major version number.
*/
public final int getMajor() {
return major;
}
/**
* Returns the minor version number of the HTTP protocol.
*
* @return the minor version number.
*/
public final int getMinor() {
return minor;
}
/**
* Obtains a specific version of this protocol.
* This can be used by derived classes to instantiate themselves instead
* of the base class, and to define constants for commonly used versions.
* <br/>
* The default implementation in this class returns <code>this</code>
* if the version matches, and creates a new {@link ProtocolVersion}
* otherwise.
*
* @param major the major version
* @param minor the minor version
*
* @return a protocol version with the same protocol name
* and the argument version
*/
public ProtocolVersion forVersion(int major, int minor) {
if ((major == this.major) && (minor == this.minor)) {
return this;
}
// argument checking is done in the constructor
return new ProtocolVersion(this.protocol, major, minor);
}
/**
* Obtains a hash code consistent with {@link #equals}.
*
* @return the hashcode of this protocol version
*/
public final int hashCode() {
return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor;
}
/**
* Checks equality of this protocol version with an object.
* The object is equal if it is a protocl version with the same
* protocol name, major version number, and minor version number.
* The specific class of the object is <i>not</i> relevant,
* instances of derived classes with identical attributes are
* equal to instances of the base class and vice versa.
*
* @param obj the object to compare with
*
* @return <code>true</code> if the argument is the same protocol version,
* <code>false</code> otherwise
*/
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ProtocolVersion)) {
return false;
}
ProtocolVersion that = (ProtocolVersion) obj;
return ((this.protocol.equals(that.protocol)) &&
(this.major == that.major) &&
(this.minor == that.minor));
}
/**
* Checks whether this protocol can be compared to another one.
* Only protocol versions with the same protocol name can be
* {@link #compareToVersion compared}.
*
* @param that the protocol version to consider
*
* @return <code>true</code> if {@link #compareToVersion compareToVersion}
* can be called with the argument, <code>false</code> otherwise
*/
public boolean isComparable(ProtocolVersion that) {
return (that != null) && this.protocol.equals(that.protocol);
}
/**
* Compares this protocol version with another one.
* Only protocol versions with the same protocol name can be compared.
* This method does <i>not</i> define a total ordering, as it would be
* required for {@link java.lang.Comparable}.
*
* @param that the protocl version to compare with
*
* @return a negative integer, zero, or a positive integer
* as this version is less than, equal to, or greater than
* the argument version.
*
* @throws IllegalArgumentException
* if the argument has a different protocol name than this object,
* or if the argument is <code>null</code>
*/
public int compareToVersion(ProtocolVersion that) {
if (that == null) {
throw new IllegalArgumentException
("Protocol version must not be null.");
}
if (!this.protocol.equals(that.protocol)) {
throw new IllegalArgumentException
("Versions for different protocols cannot be compared. " +
this + " " + that);
}
int delta = getMajor() - that.getMajor();
if (delta == 0) {
delta = getMinor() - that.getMinor();
}
return delta;
}
/**
* Tests if this protocol version is greater or equal to the given one.
*
* @param version the version against which to check this version
*
* @return <code>true</code> if this protocol version is
* {@link #isComparable comparable} to the argument
* and {@link #compareToVersion compares} as greater or equal,
* <code>false</code> otherwise
*/
public final boolean greaterEquals(ProtocolVersion version) {
return isComparable(version) && (compareToVersion(version) >= 0);
}
/**
* Tests if this protocol version is less or equal to the given one.
*
* @param version the version against which to check this version
*
* @return <code>true</code> if this protocol version is
* {@link #isComparable comparable} to the argument
* and {@link #compareToVersion compares} as less or equal,
* <code>false</code> otherwise
*/
public final boolean lessEquals(ProtocolVersion version) {
return isComparable(version) && (compareToVersion(version) <= 0);
}
/**
* Converts this protocol version to a string.
*
* @return a protocol version string, like "HTTP/1.1"
*/
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append(this.protocol);
buffer.append('/');
buffer.append(Integer.toString(this.major));
buffer.append('.');
buffer.append(Integer.toString(this.minor));
return buffer.toString();
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* One element of an HTTP {@link Header header} value consisting of
* a name / value pair and a number of optional name / value parameters.
* <p>
* Some HTTP headers (such as the set-cookie header) have values that
* can be decomposed into multiple elements. Such headers must be in the
* following form:
* </p>
* <pre>
* header = [ element ] *( "," [ element ] )
* element = name [ "=" [ value ] ] *( ";" [ param ] )
* param = name [ "=" [ value ] ]
*
* name = token
* value = ( token | quoted-string )
*
* token = 1*<any char except "=", ",", ";", <"> and
* white space>
* quoted-string = <"> *( text | quoted-char ) <">
* text = any char except <">
* quoted-char = "\" char
* </pre>
* <p>
* Any amount of white space is allowed between any part of the
* header, element or param and is ignored. A missing value in any
* element or param will be stored as the empty {@link String};
* if the "=" is also missing <var>null</var> will be stored instead.
*
* @since 4.0
*/
public interface HeaderElement {
/**
* Returns header element name.
*
* @return header element name
*/
String getName();
/**
* Returns header element value.
*
* @return header element value
*/
String getValue();
/**
* Returns an array of name / value pairs.
*
* @return array of name / value pairs
*/
NameValuePair[] getParameters();
/**
* Returns the first parameter with the given name.
*
* @param name parameter name
*
* @return name / value pair
*/
NameValuePair getParameterByName(String name);
/**
* Returns the total count of parameters.
*
* @return parameter count
*/
int getParameterCount();
/**
* Returns parameter with the given index.
*
* @param index
* @return name / value pair
*/
NameValuePair getParameter(int index);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ContentProducer;
import org.apache.ogt.http.entity.EntityTemplate;
import org.apache.ogt.http.entity.FileEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
import org.apache.ogt.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
*
*
*/
public class ElementalHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8080, args[0]);
t.setDaemon(false);
t.start();
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot) throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(
httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.entity.InputStreamEntity;
import org.apache.ogt.http.entity.StringEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a POST request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class ElementalHttpPost {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
/**
* Rudimentary HTTP/1.1 reverse proxy.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP reverse proxy.
*
*
*/
public class ElementalReverseProxy {
private static final String HTTP_IN_CONN = "http.proxy.in-conn";
private static final String HTTP_OUT_CONN = "http.proxy.out-conn";
private static final String HTTP_CONN_KEEPALIVE = "http.proxy.conn-keepalive";
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specified target hostname and port");
System.exit(1);
}
String hostname = args[0];
int port = 80;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
HttpHost target = new HttpHost(hostname, port);
Thread t = new RequestListenerThread(8888, target);
t.setDaemon(false);
t.start();
}
static class ProxyHandler implements HttpRequestHandler {
private final HttpHost target;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
public ProxyHandler(
final HttpHost target,
final HttpProcessor httpproc,
final HttpRequestExecutor httpexecutor) {
super();
this.target = target;
this.httpproc = httpproc;
this.httpexecutor = httpexecutor;
this.connStrategy = new DefaultConnectionReuseStrategy();
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpClientConnection conn = (HttpClientConnection) context.getAttribute(
HTTP_OUT_CONN);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
// Remove hop-by-hop headers
request.removeHeaders(HTTP.CONTENT_LEN);
request.removeHeaders(HTTP.TRANSFER_ENCODING);
request.removeHeaders(HTTP.CONN_DIRECTIVE);
request.removeHeaders("Keep-Alive");
request.removeHeaders("Proxy-Authenticate");
request.removeHeaders("TE");
request.removeHeaders("Trailers");
request.removeHeaders("Upgrade");
this.httpexecutor.preProcess(request, this.httpproc, context);
HttpResponse targetResponse = this.httpexecutor.execute(request, conn, context);
this.httpexecutor.postProcess(response, this.httpproc, context);
// Remove hop-by-hop headers
targetResponse.removeHeaders(HTTP.CONTENT_LEN);
targetResponse.removeHeaders(HTTP.TRANSFER_ENCODING);
targetResponse.removeHeaders(HTTP.CONN_DIRECTIVE);
targetResponse.removeHeaders("Keep-Alive");
targetResponse.removeHeaders("TE");
targetResponse.removeHeaders("Trailers");
targetResponse.removeHeaders("Upgrade");
response.setStatusLine(targetResponse.getStatusLine());
response.setHeaders(targetResponse.getAllHeaders());
response.setEntity(targetResponse.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
boolean keepalive = this.connStrategy.keepAlive(response, context);
context.setAttribute(HTTP_CONN_KEEPALIVE, new Boolean(keepalive));
}
}
static class RequestListenerThread extends Thread {
private final HttpHost target;
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final HttpHost target) throws IOException {
this.target = target;
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up HTTP protocol processor for incoming connections
HttpProcessor inhttpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
// Set up HTTP protocol processor for outgoing connections
HttpProcessor outhttpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up outgoing request executor
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
// Set up incoming request handler
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new ProxyHandler(
this.target,
outhttpproc,
httpexecutor));
// Set up the HTTP service
this.httpService = new HttpService(
inhttpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up incoming HTTP connection
Socket insocket = this.serversocket.accept();
DefaultHttpServerConnection inconn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + insocket.getInetAddress());
inconn.bind(insocket, this.params);
// Set up outgoing HTTP connection
Socket outsocket = new Socket(this.target.getHostName(), this.target.getPort());
DefaultHttpClientConnection outconn = new DefaultHttpClientConnection();
outconn.bind(outsocket, this.params);
System.out.println("Outgoing connection to " + outsocket.getInetAddress());
// Start worker thread
Thread t = new ProxyThread(this.httpService, inconn, outconn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class ProxyThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection inconn;
private final HttpClientConnection outconn;
public ProxyThread(
final HttpService httpservice,
final HttpServerConnection inconn,
final HttpClientConnection outconn) {
super();
this.httpservice = httpservice;
this.inconn = inconn;
this.outconn = outconn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
// Bind connection objects to the execution context
context.setAttribute(HTTP_IN_CONN, this.inconn);
context.setAttribute(HTTP_OUT_CONN, this.outconn);
try {
while (!Thread.interrupted()) {
if (!this.inconn.isOpen()) {
this.outconn.close();
break;
}
this.httpservice.handleRequest(this.inconn, context);
Boolean keepalive = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
if (!Boolean.TRUE.equals(keepalive)) {
this.outconn.close();
this.inconn.close();
break;
}
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.inconn.shutdown();
} catch (IOException ignore) {}
try {
this.outconn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a GET request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class ElementalHttpGet {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
String[] targets = {
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import org.apache.ogt.http.util.VersionInfo;
/**
* Prints version information for debugging purposes.
* This can be used to verify that the correct versions of the
* HttpComponent JARs are picked up from the classpath.
*
*
*/
public class PrintVersionInfo {
/** A default list of module packages. */
private final static String[] MODULE_LIST = {
"org.apache.ogt.http", // HttpCore
"org.apache.ogt.http.nio", // HttpCore NIO
"org.apache.ogt.http.client", // HttpClient
};
/**
* Prints version information.
*
* @param args command line arguments. Leave empty to print version
* information for the default packages. Otherwise, pass
* a list of packages for which to get version info.
*/
public static void main(String args[]) {
String[] pckgs = (args.length > 0) ? args : MODULE_LIST;
VersionInfo[] via = VersionInfo.loadVersionInfo(pckgs, null);
System.out.println("version info for thread context classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
System.out.println();
// if the version information for the classloader of this class
// is different from that for the thread context classloader,
// there may be a problem with multiple versions in the classpath
via = VersionInfo.loadVersionInfo
(pckgs, PrintVersionInfo.class.getClassLoader());
System.out.println("version info for static classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.message.AbstractHttpMessage;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* {@link org.apache.ogt.http.HttpMessage} mockup implementation.
*
*/
public class HttpMessageMockup extends AbstractHttpMessage {
public HttpMessageMockup() {
super();
}
public ProtocolVersion getProtocolVersion() {
return HttpProtocolParams.getVersion(this.getParams());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.apache.ogt.http.impl.io.AbstractSessionOutputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionOutputBuffer} mockup implementation.
*
*/
public class SessionOutputBufferMockup extends AbstractSessionOutputBuffer {
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public static final int BUFFER_SIZE = 16;
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize,
final HttpParams params) {
super();
init(outstream, buffersize, params);
}
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize) {
this(outstream, buffersize, new BasicHttpParams());
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer,
final HttpParams params) {
this(buffer, BUFFER_SIZE, params);
this.buffer = buffer;
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer) {
this(buffer, BUFFER_SIZE, new BasicHttpParams());
this.buffer = buffer;
}
public SessionOutputBufferMockup(final HttpParams params) {
this(new ByteArrayOutputStream(), params);
}
public SessionOutputBufferMockup() {
this(new ByteArrayOutputStream(), new BasicHttpParams());
}
public byte[] getData() {
if (this.buffer != null) {
return this.buffer.toByteArray();
} else {
return new byte[] {};
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.impl.io.AbstractSessionInputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionInputBuffer} mockup implementation.
*/
public class SessionInputBufferMockup extends AbstractSessionInputBuffer {
public static final int BUFFER_SIZE = 16;
public SessionInputBufferMockup(
final InputStream instream,
int buffersize,
final HttpParams params) {
super();
init(instream, buffersize, params);
}
public SessionInputBufferMockup(
final InputStream instream,
int buffersize) {
this(instream, buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
final HttpParams params) {
this(bytes, BUFFER_SIZE, params);
}
public SessionInputBufferMockup(
final byte[] bytes) {
this(bytes, BUFFER_SIZE, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize,
final HttpParams params) {
this(new ByteArrayInputStream(bytes), buffersize, params);
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize) {
this(new ByteArrayInputStream(bytes), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, params);
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), params);
}
public SessionInputBufferMockup(
final String s,
final String charset)
throws UnsupportedEncodingException {
this(s.getBytes(charset), new BasicHttpParams());
}
public boolean isDataAvailable(int timeout) throws IOException {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
/**
* Test class similar to {@link java.io.ByteArrayInputStream} that throws if encounters
* value zero '\000' in the source byte array.
*/
public class TimeoutByteArrayInputStream extends InputStream {
private final byte[] buf;
private int pos;
protected int count;
public TimeoutByteArrayInputStream(byte[] buf, int off, int len) {
super();
this.buf = buf;
this.pos = off;
this.count = Math.min(off + len, buf.length);
}
public TimeoutByteArrayInputStream(byte[] buf) {
this(buf, 0, buf.length);
}
public int read() throws IOException {
if (this.pos < this.count) {
return -1;
}
int v = this.buf[this.pos++] & 0xff;
if (v != 0) {
return v;
} else {
throw new InterruptedIOException("Timeout");
}
}
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (this.pos >= this.count) {
return -1;
}
if (this.pos + len > this.count) {
len = this.count - this.pos;
}
if (len <= 0) {
return 0;
}
if ((this.buf[this.pos] & 0xff) == 0) {
this.pos++;
throw new InterruptedIOException("Timeout");
}
for (int i = 0; i < len; i++) {
int v = this.buf[this.pos] & 0xff;
if (v == 0) {
return i;
} else {
b[off + i] = (byte) v;
this.pos++;
}
}
return len;
}
public long skip(long n) {
if (this.pos + n > this.count) {
n = this.count - this.pos;
}
if (n < 0) {
return 0;
}
this.pos += n;
return n;
}
public int available() {
return this.count - this.pos;
}
public boolean markSupported() {
return false;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
/**
* {@link HttpConnection} mockup implementation.
*
*/
public class HttpConnectionMockup implements HttpConnection {
private boolean open = true;
public HttpConnectionMockup() {
super();
}
public void close() throws IOException {
this.open = false;
}
public void shutdown() throws IOException {
this.open = false;
}
public void setSocketTimeout(int timeout) {
}
public int getSocketTimeout() {
return -1;
}
public boolean isOpen() {
return this.open;
}
public boolean isStale() {
return false;
}
public HttpConnectionMetrics getMetrics() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
public class HttpClient {
private final HttpParams params;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
private final HttpContext context;
public HttpClient() {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
this.httpexecutor = new HttpRequestExecutor();
this.connStrategy = new DefaultConnectionReuseStrategy();
this.context = new BasicHttpContext();
}
public HttpParams getParams() {
return this.params;
}
public HttpResponse execute(
final HttpRequest request,
final HttpHost targetHost,
final HttpClientConnection conn) throws HttpException, IOException {
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
this.httpexecutor.preProcess(request, this.httpproc, this.context);
HttpResponse response = this.httpexecutor.execute(request, conn, this.context);
response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
this.httpexecutor.postProcess(response, this.httpproc, this.context);
return response;
}
public boolean keepAlive(final HttpResponse response) {
return this.connStrategy.keepAlive(response, this.context);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.AbstractHttpEntity;
/**
* {@link AbstractHttpEntity} mockup implementation.
*
*/
public class HttpEntityMockup extends AbstractHttpEntity {
private boolean stream;
public InputStream getContent() throws IOException, IllegalStateException {
return null;
}
public long getContentLength() {
return 0;
}
public boolean isRepeatable() {
return false;
}
public void setStreaming(final boolean b) {
this.stream = b;
}
public boolean isStreaming() {
return this.stream;
}
public void writeTo(OutputStream outstream) throws IOException {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpExpectationVerifier;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
public class HttpServer {
private final HttpParams params;
private final HttpProcessor httpproc;
private final ConnectionReuseStrategy connStrategy;
private final HttpResponseFactory responseFactory;
private final HttpRequestHandlerRegistry reqistry;
private final ServerSocket serversocket;
private HttpExpectationVerifier expectationVerifier;
private Thread listener;
private volatile boolean shutdown;
public HttpServer() throws IOException {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
this.connStrategy = new DefaultConnectionReuseStrategy();
this.responseFactory = new DefaultHttpResponseFactory();
this.reqistry = new HttpRequestHandlerRegistry();
this.serversocket = new ServerSocket(0);
}
public void registerHandler(
final String pattern,
final HttpRequestHandler handler) {
this.reqistry.register(pattern, handler);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
private HttpServerConnection acceptConnection() throws IOException {
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.params);
return conn;
}
public int getPort() {
return this.serversocket.getLocalPort();
}
public InetAddress getInetAddress() {
return this.serversocket.getInetAddress();
}
public void start() {
if (this.listener != null) {
throw new IllegalStateException("Listener already running");
}
this.listener = new Thread(new Runnable() {
public void run() {
while (!shutdown && !Thread.interrupted()) {
try {
// Set up HTTP connection
HttpServerConnection conn = acceptConnection();
// Set up the HTTP service
HttpService httpService = new HttpService(
httpproc,
connStrategy,
responseFactory,
reqistry,
expectationVerifier,
params);
// Start worker thread
Thread t = new WorkerThread(httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
break;
}
}
}
});
this.listener.start();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.serversocket.close();
} catch (IOException ignore) {}
this.listener.interrupt();
try {
this.listener.join(1000);
} catch (InterruptedException ignore) {}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
/**
* Translates SimplePosition objects to a telnet command and sends the commands to a telnet session with an android emulator.
*
* @version $Id$
* @author Bram Pouwelse (c) Jan 22, 2009, Sogeti B.V.
*
*/
public class TelnetPositionSender
{
private static final String TAG = "TelnetPositionSender";
private static final String TELNET_OK_FEEDBACK_MESSAGE = "OK\r\n";
private static String HOST = "10.0.2.2";
private static int PORT = 5554;
private Socket socket;
private OutputStream out;
private InputStream in;
/**
* Constructor
*/
public TelnetPositionSender()
{
}
/**
* Setup a telnet connection to the android emulator
*/
private void createTelnetConnection() {
try {
this.socket = new Socket(HOST, PORT);
this.in = this.socket.getInputStream();
this.out = this.socket.getOutputStream();
Thread.sleep(500); // give the telnet session half a second to
// respond
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
readInput(); // read the input to throw it away the first time :)
}
private void closeConnection()
{
try
{
this.out.close();
this.in.close();
this.socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* read the input buffer
* @return
*/
private String readInput() {
StringBuffer sb = new StringBuffer();
try {
byte[] bytes = new byte[this.in.available()];
this.in.read(bytes);
for (byte b : bytes) {
sb.append((char) b);
}
} catch (Exception e) {
System.err.println("Warning: Could not read the input from the telnet session");
}
return sb.toString();
}
/**
* When a new position is received it is sent to the android emulator over the telnet connection.
*
* @param position the position to send
*/
public void sendCommand(String telnetString)
{
createTelnetConnection();
Log.v( TAG, "Sending command: "+telnetString);
byte[] sendArray = telnetString.getBytes();
for (byte b : sendArray)
{
try
{
this.out.write(b);
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
String feedback = readInput();
if (!feedback.equals(TELNET_OK_FEEDBACK_MESSAGE))
{
System.err.println("Warning: no OK mesage message was(" + feedback + ")");
}
closeConnection();
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.