没人理的瀑布 · 天降女子!~女孩子從2樓…掉了下來!?~ ...· 2 月前 · |
慷慨的抽屉 · 2D和3D與實體和虛擬環境之意象圖表法-以行 ...· 2 月前 · |
小胡子的李子 · ComboBox 样式和模板 - WPF ...· 3 月前 · |
痴情的啄木鸟 · MLKL靶点介绍及实验小贴士| Abcam中文官网· 4 月前 · |
打盹的水煮肉 · How do i pause and ...· 7 月前 · |
CascadingError
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public CascadingError( final String message, final Throwable throwable )
- {
- super( message );
- m_throwable = throwable;
- }
- /**
- * Retrieve root cause of the exception.
- *
- * @return the root cause
- */
- public final Throwable getCause()
- {
- return m_throwable;
- }
diff --git a/clients/java/src/org/apache/avalon/framework/CascadingException.java b/clients/java/src/org/apache/avalon/framework/CascadingException.java
deleted file mode 100644
index 0fd0847..0000000
--- a/clients/java/src/org/apache/avalon/framework/CascadingException.java
+++ /dev/null
@@ -1,65 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework;
- * Class from which all exceptions should inherit.
- * Allows recording of nested exceptions.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $
-public class CascadingException
- extends Exception
- implements CascadingThrowable
- /**
- * The Throwable that caused this exception to be thrown.
- */
- private final Throwable m_throwable;
- /**
- * Construct a new
CascadingException
instance.
- *
- * @param message The detail message for this exception.
- */
- public CascadingException( final String message )
- {
- this( message, null );
- }
- /**
- * Construct a new
CascadingException
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public CascadingException( final String message, final Throwable throwable )
- {
- super( message );
- m_throwable = throwable;
- }
- /**
- * Retrieve root cause of the exception.
- *
- * @return the root cause
- */
- public final Throwable getCause()
- {
- return m_throwable;
- }
diff --git a/clients/java/src/org/apache/avalon/framework/CascadingRuntimeException.java b/clients/java/src/org/apache/avalon/framework/CascadingRuntimeException.java
deleted file mode 100644
index 484c94a..0000000
--- a/clients/java/src/org/apache/avalon/framework/CascadingRuntimeException.java
+++ /dev/null
@@ -1,52 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework;
- * Class from which all exceptions should inherit.
- * Allows recording of nested exceptions.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.14 $ $Date: 2004/02/11 14:34:24 $
-public class CascadingRuntimeException
- extends RuntimeException
- implements CascadingThrowable
- private final Throwable m_throwable;
- /**
- * Construct a new
CascadingRuntimeException
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public CascadingRuntimeException( final String message, final Throwable throwable )
- {
- super( message );
- m_throwable = throwable;
- }
- /**
- * Retrieve root cause of the exception.
- *
- * @return the root cause
- */
- public final Throwable getCause()
- {
- return m_throwable;
- }
diff --git a/clients/java/src/org/apache/avalon/framework/CascadingThrowable.java b/clients/java/src/org/apache/avalon/framework/CascadingThrowable.java
deleted file mode 100644
index 836db5d..0000000
--- a/clients/java/src/org/apache/avalon/framework/CascadingThrowable.java
+++ /dev/null
@@ -1,33 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework;
- * Interface which all cascadign throwables should implement.
- * Allows recording of nested exceptions.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $
-public interface CascadingThrowable
- /**
- * Returns the root cause of this
Throwable
.
- *
- * @return a
Throwable
- */
- Throwable getCause();
diff --git a/clients/java/src/org/apache/avalon/framework/Enum.java b/clients/java/src/org/apache/avalon/framework/Enum.java
deleted file mode 100644
index 98cfbca..0000000
--- a/clients/java/src/org/apache/avalon/framework/Enum.java
+++ /dev/null
@@ -1,175 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework;
-import java.util.Map;
- * Basic enum class for type-safe enums. Should be used as an abstract base. For example:
- * import org.apache.avalon.framework.Enum;
- * public final class Color extends Enum {
- * public static final Color RED = new Color( "Red" );
- * public static final Color GREEN = new Color( "Green" );
- * public static final Color BLUE = new Color( "Blue" );
- * private Color( final String color )
- * {
- * super( color );
- * }
- * }
- * If further operations, such as iterating over all items, are required, the
- * {@link #Enum(String, Map)} constructor can be used to populate a
Map
, from which
- * further functionality can be derived:
- * public final class Color extends Enum {
- * static final Map map = new HashMap();
- * public static final Color RED = new Color( "Red", map );
- * public static final Color GREEN = new Color( "Green", map );
- * public static final Color BLUE = new Color( "Blue", map );
- * private Color( final String color, final Map map )
- * {
- * super( color, map );
- * }
- * public static Iterator iterator()
- * {
- * return map.values().iterator();
- * }
- * }
- *
NOTE:
between 4.0 and 4.1, the constructors' access has been changed
- * from
public
to
protected
. This is to prevent users
- * of the Enum breaking type-safety by defining new Enum items. All Enum items
- * should be defined in the Enum class, as shown above.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.28 $ $Date: 2004/02/11 14:34:24 $
-public abstract class Enum
- /**
- * The string representation of the Enum.
- */
- private final String m_name;
- /**
- * Constructor to add a new named item.
- *
- *
Note:
access changed from
public
to
- *
protected
after 4.0. See class description.
- *
- *
Note:
access changed from
public
to
- *
protected
after 4.0. See class description.
- *
Map
, to which will be added a pointer to the newly constructed
- * object.
- */
- protected Enum( final String name, final Map map )
- {
- m_name = name;
- if( null != map )
- {
- map.put( name, this );
- }
- }
- /**
- * Tests for equality. Two Enum:s are considered equal
- * if they are of the same class and have the same names.
- * The method is also declared final - I (LSutic) did this to
- * allow the JIT to inline it easily.
- *
- * @param o the other object
- * @return the equality status
- */
- public final boolean equals( Object o )
- {
- if( this == o )
- return true;
- if( !(o instanceof Enum) )
- return false;
- final Enum enumv = (Enum)o;
- if( !getClass().equals( enumv.getClass() ) )
- return false;
- if( m_name != null ? !m_name.equals( enumv.m_name ) : enumv.m_name != null )
- return false;
- return true;
- }
- public int hashCode()
- {
- int result;
- result = (m_name != null ? m_name.hashCode() : 0);
- result = 29 * result + getClass().hashCode();
- return result;
- }
- /**
- * Returns a hash code value for the object.
- *
- * @return a hash code value for this object
- */
- /*public int hashCode()
- {
- return m_name.hashCode() ^ this.getClass().getName().hashCode();
- }*/
- /**
- * Retrieve the name of this Enum item, set in the constructor.
- * @return the name
String
of this Enum item
- */
- public final String getName()
- {
- return m_name;
- }
- /**
- * Human readable description of this Enum item. For use when debugging.
- * @return String in the form
type[name]
, eg.:
- *
Color[Red]
.
- */
- public String toString()
- {
- return getClass().getName() + "[" + m_name + "]";
- }
diff --git a/clients/java/src/org/apache/avalon/framework/ValuedEnum.java b/clients/java/src/org/apache/avalon/framework/ValuedEnum.java
deleted file mode 100644
index a7a2dee..0000000
--- a/clients/java/src/org/apache/avalon/framework/ValuedEnum.java
+++ /dev/null
@@ -1,198 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework;
-import java.util.Map;
- * Basic enum class for type-safe enums with values. Valued enum items can be compared and ordered
- * with the provided methods. Should be used as an abstract base. For example:
- * import org.apache.avalon.framework.ValuedEnum;
- * public final class JavaVersion
- * extends ValuedEnum
- * {
- * //standard enums for version of JVM
- * public static final JavaVersion JAVA1_0 = new JavaVersion( "Java 1.0", 100 );
- * public static final JavaVersion JAVA1_1 = new JavaVersion( "Java 1.1", 110 );
- * public static final JavaVersion JAVA1_2 = new JavaVersion( "Java 1.2", 120 );
- * public static final JavaVersion JAVA1_3 = new JavaVersion( "Java 1.3", 130 );
- * private JavaVersion( final String name, final int value )
- * {
- * super( name, value );
- * }
- * }
- * The above class could then be used as follows:
- * import org.apache.avalon.framework.context.Context;
- * import org.apache.avalon.framework.context.Contextualizable;
- * import org.apache.avalon.framework.context.ContextException;
- * public class MyComponent implements Contextualizable
- * {
- * JavaVersion requiredVer = JavaVersion.JAVA1_2;
- * public void contextualize(Context context)
- * throws ContextException
- * {
- * JavaVersion ver = (JavaVersion)context.get("java.version");
- * if ( ver.isLessThan( requiredVer ) )
- * {
- * throw new RuntimeException( requiredVer.getName()+" or higher required" );
- * }
- * }
- * }
- * As with
Enum
, the {@link #ValuedEnum(String, int, Map)} constructor can be used to
- * populate a
Map
, from which further functionality can be derived.
- *
NOTE:
between 4.0 and 4.1, the constructors' access has been changed
- * from
public
to
protected
. This is to prevent users
- * of the Enum breaking type-safety by defining new Enum items. All Enum items
- * should be defined in the Enum class, as shown above.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $
-public abstract class ValuedEnum
- extends Enum
- /**
- * The value contained in enum.
- */
- private final int m_value;
- /**
- * Constructor for enum item.
- *
- *
- *
Note:
access changed from
public
to
- *
protected
after 4.0. See class description.
- *
- * Note: access changed from
public
to
- *
protected
after 4.0. See class description.
- *
- *
- * @param name the name of enum item.
- * @param value the value of enum item.
- * @param map the
Map
to add enum item to.
- */
- protected ValuedEnum( final String name, final int value, final Map map )
- {
- super( name, map );
- m_value = value;
- }
- /**
- * Get value of enum item.
- *
- * @return the enum item's value.
- */
- public final int getValue()
- {
- return m_value;
- }
- /**
- * Test if enum item is equal in value to other enum.
- *
- * @param other the other enum
- * @return true if equal
- */
- public final boolean isEqualTo( final ValuedEnum other )
- {
- return m_value == other.m_value;
- }
- /**
- * Test if enum item is greater than in value to other enum.
- *
- * @param other the other enum
- * @return true if greater than
- */
- public final boolean isGreaterThan( final ValuedEnum other )
- {
- return m_value > other.m_value;
- }
- /**
- * Test if enum item is greater than or equal in value to other enum.
- *
- * @param other the other enum
- * @return true if greater than or equal
- */
- public final boolean isGreaterThanOrEqual( final ValuedEnum other )
- {
- return m_value >= other.m_value;
- }
- /**
- * Test if enum item is less than in value to other enum.
- *
- * @param other the other enum
- * @return true if less than
- */
- public final boolean isLessThan( final ValuedEnum other )
- {
- return m_value < other.m_value;
- }
- /**
- * Test if enum item is less than or equal in value to other enum.
- *
- * @param other the other enum
- * @return true if less than or equal
- */
- public final boolean isLessThanOrEqual( final ValuedEnum other )
- {
- return m_value <= other.m_value;
- }
- /**
- * Override toString method to produce human readable description.
- *
- * @return String in the form
type[name=value]
, eg.:
- *
JavaVersion[Java 1.0=100]
.
- */
- public String toString()
- {
- return getClass().getName() + "[" + getName() + "=" + m_value + "]";
- }
diff --git a/clients/java/src/org/apache/avalon/framework/Version.java b/clients/java/src/org/apache/avalon/framework/Version.java
deleted file mode 100644
index c5c0752..0000000
--- a/clients/java/src/org/apache/avalon/framework/Version.java
+++ /dev/null
@@ -1,319 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework;
-import java.io.Serializable;
-import java.util.StringTokenizer;
- * This class is used to hold version information pertaining to a Component or interface.
- * The version number of a
Component
is made up of three
- * dot-separated fields:
- * "
major.minor.micro
"
- * The
major
,
minor
and
micro
fields are
- *
integer
numbers represented in decimal notation and have the
- * following meaning:
- *
- *
- *
null
- * @since 4.1
- */
- public static Version getVersion( final String version )
- throws NumberFormatException, IllegalArgumentException
- {
- if( version == null )
- throw new NullPointerException( "version" );
- final StringTokenizer tokenizer = new StringTokenizer( version, "." );
- final String[] levels = new String[ tokenizer.countTokens() ];
- for( int i = 0; i < levels.length; i++ )
- {
- levels[ i ] = tokenizer.nextToken();
- }
- int major = -1;
- if( 0 < levels.length )
- {
- major = Integer.parseInt( levels[ 0 ] );
- }
- int minor = 0;
- if( 1 < levels.length )
- {
- minor = Integer.parseInt( levels[ 1 ] );
- }
- int micro = 0;
- if( 2 < levels.length )
- {
- micro = Integer.parseInt( levels[ 2 ] );
- }
- return new Version( major, minor, micro );
- }
- /**
- * Create a new instance of a
Version
object with the
- * specified version numbers.
- *
- * @param major This
Version
major number.
- * @param minor This
Version
minor number.
- * @param micro This
Version
micro number.
- */
- public Version( final int major, final int minor, final int micro )
- {
- m_major = major;
- m_minor = minor;
- m_micro = micro;
- }
- /**
- * Retrieve major component of version.
- *
- * @return the major component of version
- * @since 4.1
- */
- public int getMajor()
- {
- return m_major;
- }
- /**
- * Retrieve minor component of version.
- *
- * @return the minor component of version
- * @since 4.1
- */
- public int getMinor()
- {
- return m_minor;
- }
- /**
- * Retrieve micro component of version.
- *
- * @return the micro component of version.
- * @since 4.1
- */
- public int getMicro()
- {
- return m_micro;
- }
- /**
- * Check this
Version
against another for equality.
- *
- * If this
Version
is compatible with the specified one, then
- *
true
is returned, otherwise
false
.
- *
- * @param other The other
Version
object to be compared with this
- * for equality.
- * @return
true
if this
Version
is compatible with the specified one
- * @since 4.1
- */
- public boolean equals( final Version other )
- {
- if( other == null )
- return false;
- boolean isEqual = ( getMajor() == other.getMajor() );
- if ( isEqual )
- {
- isEqual = ( getMinor() == other.getMinor() );
- }
- if ( isEqual )
- {
- isEqual = ( getMicro() == other.getMicro() );
- }
- return isEqual;
- }
- /**
- * Indicates whether some other object is "equal to" this
Version
.
- * Returns
true
if the other object is an instance of
Version
- * and has the same major, minor, and micro components.
- *
- * @param other an
Object
value
- * @return
true
if the other object is equal to this
Version
- */
- public boolean equals( final Object other )
- {
- boolean isEqual = false;
- if( other instanceof Version )
- {
- isEqual = equals( (Version)other );
- }
- return isEqual;
- }
- /**
- * Add a hashing function to ensure the Version object is
- * treated as expected in hashmaps and sets. NOTE: any
- * time the equals() is overridden, hashCode() should also
- * be overridden.
- *
- * @return the hashCode
- */
- public int hashCode()
- {
- int hash = getMajor();
- hash >>>= 17;
- hash += getMinor();
- hash >>>= 17;
- hash += getMicro();
- return hash;
- }
- /**
- * Check this
Version
against another for compliancy
- * (compatibility).
- *
- * If this
Version
is compatible with the specified one, then
- *
true
is returned, otherwise
false
. Be careful when using
- * this method since, in example, version 1.3.7 is compliant to version
- * 1.3.6, while the opposite is not.
- *
- * The following example displays the expected behaviour and results of version. - *
- * final Version v1 = new Version( 1, 3 , 6 ); - * final Version v2 = new Version( 1, 3 , 7 ); - * final Version v3 = new Version( 1, 4 , 0 ); - * final Version v4 = new Version( 2, 0 , 1 ); - * - * assert( v1.complies( v1 ) ); - * assert( ! v1.complies( v2 ) ); - * assert( v2.complies( v1 ) ); - * assert( ! v1.complies( v3 ) ); - * assert( v3.complies( v1 ) ); - * assert( ! v1.complies( v4 ) ); - * assert( ! v4.complies( v1 ) ); - *- * - * @param other The other
Version
object to be compared with this
- * for compliancy (compatibility).
- * @return
true
if this
Version
is compatible with the specified one
- */
- public boolean complies( final Version other )
- {
- if( other == null )
- return false;
- if( other.m_major == -1 )
- {
- return true;
- }
- if( m_major != other.m_major )
- {
- return false;
- }
- else if( m_minor < other.m_minor )
- {
- //If of major version but lower minor version then incompatible
- return false;
- }
- else if( m_minor == other.m_minor
- && m_micro < other.m_micro )
- {
- //If same major version, same minor version but lower micro level
- //then incompatible
- return false;
- }
- else
- {
- return true;
- }
- }
- /**
- * Overload toString to report version correctly.
- *
- * @return the dot seperated version string
- */
- public String toString()
- {
- return m_major + "." + m_minor + "." + m_micro;
- }
- /**
- * Compare two versions together according to the
- * {@link Comparable} interface.
- *
- * @return number indicating relative value (-1, 0, 1)
- */
- public int compareTo(Object o) {
- if( o == null )
- throw new NullPointerException( "o" );
- Version other = (Version)o;
- int val = 0;
- if ( getMajor() < other.getMajor() ) val = -1;
- if ( 0 == val && getMajor() > other.getMajor() ) val = 1;
- if ( 0 == val && getMinor() < other.getMinor() ) val = -1;
- if ( 0 == val && getMinor() > other.getMinor() ) val = 1;
- if ( 0 == val && getMicro() < other.getMicro() ) val = -1;
- if ( 0 == val && getMicro() > other.getMicro() ) val = 1;
- return val;
- }
diff --git a/clients/java/src/org/apache/avalon/framework/activity/Disposable.java b/clients/java/src/org/apache/avalon/framework/activity/Disposable.java
deleted file mode 100644
index 4496434..0000000
--- a/clients/java/src/org/apache/avalon/framework/activity/Disposable.java
+++ /dev/null
@@ -1,34 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.activity;
- * The Disposable interface is used when components need to
- * deallocate and dispose resources prior to their destruction.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:24 $
-public interface Disposable
- /**
- * The dispose operation is called at the end of a components lifecycle.
- * This method will be called after Startable.stop() method (if implemented
- * by component). Components use this method to release and destroy any
- * resources that the Component owns.
- */
- void dispose();
diff --git a/clients/java/src/org/apache/avalon/framework/activity/Executable.java b/clients/java/src/org/apache/avalon/framework/activity/Executable.java
deleted file mode 100644
index 9dafa34..0000000
--- a/clients/java/src/org/apache/avalon/framework/activity/Executable.java
+++ /dev/null
@@ -1,38 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.activity;
- * The Executable can be implemented by components that need to perform
- * some work. In many respects it is similar to Runnable except that it
- * also allows an application to throw a non-Runtime Exception.
- *
The work done may be short lived (ie a simple task) or it could - * be a long running.
- * @author Avalon Development Team - * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $ -public interface Executable - /** - * Execute the action associated with this component. - * - * @throws Exception if an error occurs - */ - void execute() - throws Exception; diff --git a/clients/java/src/org/apache/avalon/framework/activity/Initializable.java b/clients/java/src/org/apache/avalon/framework/activity/Initializable.java deleted file mode 100644 index 7669820..0000000 --- a/clients/java/src/org/apache/avalon/framework/activity/Initializable.java +++ /dev/null @@ -1,36 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.avalon.framework.activity; - * The Initializable interface is used by components that need to - * allocate resources prior to them becoming active. - * @author Avalon Development Team - * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:24 $ -public interface Initializable - /** - * Initialize the component. Initialization includes - * allocating any resources required throughout the - * component's lifecycle. - * - * @throws Exception if an error occurs - */ - void initialize() - throws Exception; diff --git a/clients/java/src/org/apache/avalon/framework/activity/Startable.java b/clients/java/src/org/apache/avalon/framework/activity/Startable.java deleted file mode 100644 index 6776daf..0000000 --- a/clients/java/src/org/apache/avalon/framework/activity/Startable.java +++ /dev/null @@ -1,46 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.avalon.framework.activity; - * The Startable interface is used when components need to - * be "running" to be active. It provides a method through - * which components can be "started" and "stopped" without - * requiring a thread. - * Note that these methods should start the component but return - * imediately. - * @author Avalon Development Team - * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:24 $ -public interface Startable - /** - * Starts the component. - * - * @throws Exception if Component can not be started - */ - void start() - throws Exception; - /** - * Stops the component. - * - * @throws Exception if the Component can not be Stopped. - */ - void stop() - throws Exception; diff --git a/clients/java/src/org/apache/avalon/framework/activity/Suspendable.java b/clients/java/src/org/apache/avalon/framework/activity/Suspendable.java deleted file mode 100644 index d748a64..0000000 --- a/clients/java/src/org/apache/avalon/framework/activity/Suspendable.java +++ /dev/null @@ -1,38 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.avalon.framework.activity; - * The Suspendable interface is used when a component - * will need to temporarily halt execution of a component. - * The execution may be halted so that you can reconfigure/ - * recompose/recontextualize component. - * @author Avalon Development Team - * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:24 $ -public interface Suspendable - /** - * Suspends the component. - */ - void suspend(); - /** - * Resumes the component. - */ - void resume(); diff --git a/clients/java/src/org/apache/avalon/framework/component/Component.java b/clients/java/src/org/apache/avalon/framework/component/Component.java deleted file mode 100644 index 3e27879..0000000 --- a/clients/java/src/org/apache/avalon/framework/component/Component.java +++ /dev/null @@ -1,79 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.avalon.framework.component; - * This interface identifies classes that can be used as
Components
- * by a
Composable
.
- * The contract surrounding the
Component
is that it is
- * used, but not a user. When a class implements this interface, it
- * is stating that other entities may use that class.
- * A
Component
is the basic building block of the Avalon Framework.
- * When a class implements this interface, it allows itself to be
- * managed by a
ComponentManager
and used by an outside
- * element called a
Composable
. The
Composable
- * must know what type of
Component
it is accessing, so
- * it will re-cast the
Component
into the type it needs.
- * In order for a
Component
to be useful you must either
- * extend this interface, or implement this interface in conjunction
- * with one that actually has methods. The new interface is the contract
- * with the
Composable
that this is a particular type of
- * component, and as such it can perform those functions on that type
- * of component.
- * For example, we want a component that performs a logging function
- * so we extend the
Component
to be a
LoggingComponent
.
- * interface LoggingComponent
- * extends Component
- * {
- * log(String message);
- * }
- * Now all
Composable
s that want to use this type of component,
- * will re-cast the
Component
into a
LoggingComponent
- * and the
Composable
will be able to use the
log
- * method.
- *
Deprecated:
- * Deprecated without replacement. Should only be used while migrating away
- * from a system based on Composable/ComponentManager. A generic
java.lang.Object
- * can be used as a replacement.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:24 $
-public interface Component
diff --git a/clients/java/src/org/apache/avalon/framework/component/ComponentException.java b/clients/java/src/org/apache/avalon/framework/component/ComponentException.java
deleted file mode 100644
index ab29ad3..0000000
--- a/clients/java/src/org/apache/avalon/framework/component/ComponentException.java
+++ /dev/null
@@ -1,122 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.component;
-import org.apache.avalon.framework.CascadingException;
- * The exception thrown to indicate a problem with Components.
- * It is usually thrown by ComponentManager or ComponentSelector.
- *
Deprecated:
- * Use {@link org.apache.avalon.framework.service.ServiceException} instead.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.22 $ $Date: 2004/02/11 14:34:24 $
-public class ComponentException
- extends CascadingException
- private final String m_key;
- /**
- * Construct a new
ComponentException
instance.
- * @param key the lookup key
- * @param message the exception message
- * @param throwable the throwable
- */
- public ComponentException( final String key,
- final String message,
- final Throwable throwable )
- {
- super( message, throwable );
- m_key = key;
- }
- /**
- * Construct a new
ComponentException
instance.
- *
- * @deprecated use the String, String, Throwable version to record the role
- * @param message the exception message
- * @param throwable the throwable
- */
- public ComponentException( final String message, final Throwable throwable )
- {
- this( null, message, throwable );
- }
- /**
- * Construct a new
ComponentException
instance.
- *
- * @deprecated use the String, String version to record the role
- * @param message the exception message
- */
- public ComponentException( final String message )
- {
- this( null, message, null );
- }
- /**
- * Construct a new
ComponentException
instance.
- * @param key the lookup key
- * @param message the exception message
- */
- public ComponentException( final String key, final String message )
- {
- this( key, message, null );
- }
- /**
- * Get the key which let to the exception. May be null.
- *
- * @return The key which let to the exception.
- */
- public final String getKey()
- {
- return m_key;
- }
- /**
- * Get the key which let to the exception. May be null.
- *
- * @return The key which let to the exception.
- * @deprecated Use getKey instead
- */
- public final String getRole()
- {
- return getKey();
- }
- /**
- * Return a message describing the exception.
- *
- * @return exception message.
- */
- public String getMessage()
- {
- if( m_key == null )
- {
- return super.getMessage();
- }
- else
- {
- return super.getMessage() + " (key [" + m_key + "])";
- }
- }
diff --git a/clients/java/src/org/apache/avalon/framework/component/ComponentManager.java b/clients/java/src/org/apache/avalon/framework/component/ComponentManager.java
deleted file mode 100644
index 3fe8f36..0000000
--- a/clients/java/src/org/apache/avalon/framework/component/ComponentManager.java
+++ /dev/null
@@ -1,106 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.component;
- * A
ComponentManager
selects
Component
s based on a
- * role. The contract is that all the
Component
s implement the
- * differing roles and there is one
Component
per role. If you
- * need to select on of many
Component
s that implement the same
- * role, then you need to use a
ComponentSelector
. Roles are
- * usually the full interface name.
- * A role is better understood by the analogy of a play. There are many
- * different roles in a script. Any actor or actress can play any given part
- * and you get the same results (phrases said, movements made, etc.). The exact
- * nuances of the performance is different.
- * Below is a list of things that might be considered the different roles:
- *
ComponentManager
does not specify the methodology of
- * getting the
Component
, merely the interface used to get it.
- * Therefore the
ComponentManager
can be implemented with a
- * factory pattern, an object pool, or a simple Hashtable.
- *
Deprecated:
- * Use {@link org.apache.avalon.framework.service.ServiceManager} instead.
- * @see org.apache.avalon.framework.component.Component
- * @see org.apache.avalon.framework.component.Composable
- * @see org.apache.avalon.framework.component.ComponentSelector
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $
-public interface ComponentManager
- /**
- * Get the
Component
associated with the given key. For
- * instance, If the
ComponentManager
had a
- *
LoggerComponent
stored and referenced by key, I would use
- * the following call:
- *
- * try - * { - * LoggerComponent log; - * myComponent = (LoggerComponent) m_manager.lookup(LoggerComponent.ROLE); - * } - * catch (...) - * { - * ... - * } - *- * - * @param key The key name of the
Component
to retrieve.
- * @return the desired component
- * @throws ComponentException if an error occurs
- */
- Component lookup( String key )
- throws ComponentException;
- /**
- * Check to see if a
Component
exists for a key.
- *
- * @param key a string identifying the key to check.
- * @return True if the component exists, False if it does not.
- */
- boolean hasComponent( String key );
- /**
- * Return the
Component
when you are finished with it. This
- * allows the
ComponentManager
to handle the End-Of-Life Lifecycle
- * events associated with the Component. Please note, that no Exceptions
- * should be thrown at this point. This is to allow easy use of the
- * ComponentManager system without having to trap Exceptions on a release.
- *
- * @param component The Component we are releasing.
- */
- void release( Component component );
diff --git a/clients/java/src/org/apache/avalon/framework/component/ComponentSelector.java b/clients/java/src/org/apache/avalon/framework/component/ComponentSelector.java
deleted file mode 100644
index f77c2b1..0000000
--- a/clients/java/src/org/apache/avalon/framework/component/ComponentSelector.java
+++ /dev/null
@@ -1,108 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.component;
- * A
ComponentSelector
selects
Component
s based on a
- * hint. The contract is that all the
Component
s implement the
- * same role.
- * A role is better understood by the analogy of a play. There are many
- * different roles in a script. Any actor or actress can play any given part
- * and you get the same results (phrases said, movements made, etc.). The exact
- * nuances of the performance is different.
- * Below is a list of things that might be considered the same role:
- *
ComponentSelector
does not specify the methodology of
- * getting the
Component
, merely the interface used to get it.
- * Therefore the
ComponentSelector
can be implemented with a
- * factory pattern, an object pool, or a simple Hashtable.
- *
Deprecated:
- * Use {@link org.apache.avalon.framework.service.ServiceSelector} instead.
- * @see org.apache.avalon.framework.component.Component
- * @see org.apache.avalon.framework.component.Composable
- * @see org.apache.avalon.framework.component.ComponentManager
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $
-public interface ComponentSelector
- extends Component
- /**
- * Select the
Component
associated with the given hint.
- * For instance, If the
ComponentSelector
has a
- *
Generator
stored and referenced by a URL, I would use the
- * following call:
- *
- *
- * try - * { - * Generator input; - * input = (Generator)selector.select( new URL("foo://demo/url") ); - * } - * catch (...) - * { - * ... - * } - *- * - * @param hint A hint to retrieve the correct
Component
.
- * @return the desired component
- * @throws ComponentException If the given role is not associated
- * with a
Component
, or a
- *
Component
instance cannot
- * be created.
- */
- Component select( Object hint )
- throws ComponentException;
- /**
- * Check to see if a
Component
exists for a hint.
- *
- * @param hint a string identifying the role to check.
- * @return True if the component exists, False if it does not.
- */
- boolean hasComponent( Object hint );
- /**
- * Return the
Component
when you are finished with it. This
- * allows the
ComponentSelector
to handle the End-Of-Life Lifecycle
- * events associated with the Component. Please note, that no Exceptions
- * should be thrown at this point. This is to allow easy use of the
- * ComponentSelector system without having to trap Exceptions on a release.
- *
- * @param component The Component we are releasing.
- */
- void release( Component component );
diff --git a/clients/java/src/org/apache/avalon/framework/component/Composable.java b/clients/java/src/org/apache/avalon/framework/component/Composable.java
deleted file mode 100644
index 290dfd4..0000000
--- a/clients/java/src/org/apache/avalon/framework/component/Composable.java
+++ /dev/null
@@ -1,55 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.component;
- * A
Composable
class is one that needs to connect to software
- * components using a "role" abstraction, thus not depending on particular
- * implementations but on behavioral interfaces.
- * The contract surrounding a
Composable
is that it is a user.
- * The
Composable
is able to use
Components
managed
- * by the
ComponentManager
it was initialized with. As part
- * of the contract with the system, the instantiating entity must call
- * the
compose
method before the
Composable
- * can be considered valid.
- *
Deprecated:
- * Use {@link org.apache.avalon.framework.service.Serviceable} instead.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:24 $
-public interface Composable
- /**
- * Pass the
ComponentManager
to the
composer
.
- * The
Composable
implementation should use the specified
- *
ComponentManager
to acquire the components it needs for
- * execution.
- *
- * @param componentManager The
ComponentManager
which this
- *
Composable
uses. Must not be
null
.
- * @throws ComponentException if an error occurs
- */
- void compose( ComponentManager componentManager )
- throws ComponentException;
diff --git a/clients/java/src/org/apache/avalon/framework/component/Recomposable.java b/clients/java/src/org/apache/avalon/framework/component/Recomposable.java
deleted file mode 100644
index 8922b7c..0000000
--- a/clients/java/src/org/apache/avalon/framework/component/Recomposable.java
+++ /dev/null
@@ -1,43 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.component;
- * Extends composer to allow recomposing.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.22 $ $Date: 2004/02/11 14:34:24 $
- * @deprecated Deprecated with no replacement. The Recomposable interface is a legacy
- * interface with no concrete contracts. Rather than copy the design mistake
- * to the "service" package, we no longer support this class.
-public interface Recomposable
- extends Composable
- /**
- * Repass the
ComponentManager
to the
composer
.
- * The
Composable
implementation should use the specified
- *
ComponentManager
to acquire the components it needs for
- * execution. It should also drop references to any components it
- * retrieved from old ComponentManager.
- *
- * @param componentManager The
ComponentManager
which this
- *
Composable
uses.
- * @throws ComponentException if an error occurs
- */
- void recompose( ComponentManager componentManager )
- throws ComponentException;
diff --git a/clients/java/src/org/apache/avalon/framework/configuration/Configurable.java b/clients/java/src/org/apache/avalon/framework/configuration/Configurable.java
deleted file mode 100644
index d371c30..0000000
--- a/clients/java/src/org/apache/avalon/framework/configuration/Configurable.java
+++ /dev/null
@@ -1,44 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.configuration;
- * This interface should be implemented by classes that need to be
- * configured with custom parameters before initialization.
- * The contract surrounding a
Configurable
is that the
- * instantiating entity must call the
configure
- * method before it is valid.
- * Note that this interface is incompatible with Parameterizable.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:24 $
-public interface Configurable
- /**
- * Pass the
Configuration
to the
Configurable
- * class.
- *
- * @param configuration the class configurations. Must not be
null
.
- * @throws ConfigurationException if an error occurs
- */
- void configure( Configuration configuration )
- throws ConfigurationException;
diff --git a/clients/java/src/org/apache/avalon/framework/configuration/Configuration.java b/clients/java/src/org/apache/avalon/framework/configuration/Configuration.java
deleted file mode 100644
index 9858c50..0000000
--- a/clients/java/src/org/apache/avalon/framework/configuration/Configuration.java
+++ /dev/null
@@ -1,458 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.configuration;
- *
Configuration
is a interface encapsulating a configuration node
- * used to retrieve configuration values.
- * This is a "read only" interface preventing applications from modifying their
- * own configurations. Once it is created, the information never changes.
- *
Configuration
s are
- * usually built from an XML file by the {@link DefaultConfigurationBuilder}
- * class, or directly by a SAX parser using a {@link SAXConfigurationHandler} or
- * {@link NamespacedSAXConfigurationHandler} event handler.
- *
Configuration
node has a namespace
- * associated with it, in the form of a string, accessible through {@link
- * #getNamespace}. If no namespace is present,
getNamespace
will
- * return blank (""). See {@link DefaultConfigurationBuilder} for details on how
- * XML namespaces are mapped to
Configuration
namespaces.
- *
Configuration
s (with and without
- * namespaces) built from this XML:
- * <my-system version="1.3" xmlns:doc="http://myco.com/documentation">
- * <doc:desc>This is a highly fictitious config file</doc:desc>
- * <widget name="fooWidget" initOrder="1" threadsafe="true"/>
- * </my-system>
- *
If namespace support is enabled (eg through {@link
- * DefaultConfigurationBuilder#DefaultConfigurationBuilder(boolean) new
- * DefaultConfigurationBuilder(true)}), then the
xmlns:doc
element
- * will not translate into a Configuration attribute, and the
- *
doc:desc
element will become a
Configuration
node
- * with name "desc" and namespace "http://myco.com/documentation". The
- *
widget
element will have namespace "".
- *
If namespace support is disabled (the default for {@link
- * DefaultConfigurationBuilder}), the above XML will translate directly to
- *
Configuration
nodes. The
my-system
node will have
- * an attribute named "xmlns:doc", and a child called "doc:desc".
- * Assuming the
Configuration
object is named
conf
,
- * here is how the data could be retrieved:
- * CodeNo namespacesWith namespaces
- *
conf.{@link #getName getName}()
my-system
- *
conf.{@link #getAttributeNames getAttributeNames}().length
- * 21
- *
conf.{@link #getChildren getChildren}().length
- * 2
- *
conf.{@link #getAttributeAsFloat getAttributeAsFloat}("version")
- * 1.3
- *
conf.{@link #getChild getChild}("widget").{@link #getAttribute getAttribute}("name")
- * fooWidget
- *
conf.{@link #getChild getChild}("widget")
- * .{@link #getAttributeAsBoolean getAttributeAsBoolean}("threadsafe")
- *
true
- *
conf.{@link #getChild getChild}("widget").{@link #getLocation getLocation}()
- * file:///home/jeff/tmp/java/avalon/src/java/new.xconf:4:60
- *
conf.{@link #getChild getChild}("desc").{@link #getName getName}()
- * desc (see {@link #getChild(String)})desc
- *
conf.{@link #getChild getChild}("doc:desc").{@link #getName getName}()
- * doc:descdoc:desc (see {@link #getChild(String)})
- *
conf.{@link #getChild getChild}("desc").{@link #getValue getValue}()
- * {@link ConfigurationException}This is a highly fictitious config file
- *
conf.{@link #getChild getChild}("doc:desc").{@link #getValue getValue}()
- * This is a highly fictitious config file{@link ConfigurationException}
- *
conf.{@link #getChild getChild}("desc").{@link #getNamespace getNamespace}()
- * http://myco.com/documentation"
- * Type-safe utility methods are provided for retrieving attribute and element
- * values as
String
,
int
,
long
,
- *
float
and
boolean
.
- *
Configuration
node.
- */
- String getName();
- /**
- * Return a string describing location of Configuration.
- * Location can be different for different mediums (ie "file:line" for normal XML files or
- * "table:primary-key" for DB based configurations);
- *
- * @return a string describing location of Configuration
- */
- String getLocation();
- /**
- * Returns a string indicating which namespace this Configuration node
- * belongs to.
- *
- *
- * What this returns is dependent on the configuration file and the - * Configuration builder. If the Configuration builder does not support - * namespaces, this method will return a blank string. - *
- *In the case of {@link DefaultConfigurationBuilder}, the namespace will - * be the URI associated with the XML element. Eg.,:
- *- * <foo xmlns:x="http://blah.com"> - * <x:bar/> - * </foo> - *- *
The namespace of
foo
will be "", and the namespace of
- *
bar
will be "http://blah.com".
Configuration
instance encapsulating the
- * specified child node.
- *
- * If no such child node exists, an empty
Configuration
will be
- * returned, allowing constructs such as
- *
conf.getChild("foo").getChild("bar").getChild("baz").{@link
- * #getValue(String) getValue}("default");
- *
- * If you wish to get a
null
return when no element is present,
- * use {@link #getChild(String, boolean) getChild("foo",
false
)}.
- *
Configuration
instance encapsulating the specified
- * child node.
- *
- * @param child The name of the child node.
- * @param createNew If
true
, a new
Configuration
- * will be created and returned if the specified child does not exist. If
- *
false
,
null
will be returned when the specified
- * child doesn't exist.
- * @return Configuration
- */
- Configuration getChild( String child, boolean createNew );
- /**
- * Return an
Array
of
Configuration
- * elements containing all node children. The array order will reflect the
- * order in the source config file.
- *
- * @return All child nodes
- */
- Configuration[] getChildren();
- /**
- * Return an
Array
of
Configuration
- * elements containing all node children with the specified name. The array
- * order will reflect the order in the source config file.
- *
- * @param name The name of the children to get.
- * @return The child nodes with name
name
- */
- Configuration[] getChildren( String name );
- /**
- * Return an array of all attribute names.
- *
- *
The order of attributes in this array can not be relied on.
As
- * with XML, a
Configuration
's attributes are an
- *
unordered
set. If your code relies on order, eg
- *
conf.getAttributeNames()[0]
, then it is liable to break if a
- * different XML parser is used.
- *
String[]
value
- */
- String[] getAttributeNames();
- /**
- * Return the value of specified attribute.
- *
- * @param paramName The name of the parameter you ask the value of.
- * @return String value of attribute.
- * @throws ConfigurationException If no attribute with that name exists.
- */
- String getAttribute( String paramName ) throws ConfigurationException;
- /**
- * Return the
int
value of the specified attribute contained
- * in this node.
- *
- * @param paramName The name of the parameter you ask the value of.
- * @return int value of attribute
- * @throws ConfigurationException If no parameter with that name exists.
- * or if conversion to
int
fails.
- *
- */
- int getAttributeAsInteger( String paramName ) throws ConfigurationException;
- /**
- * Returns the value of the attribute specified by its name as a
- *
long
.
- *
- * @param name The name of the parameter you ask the value of.
- * @return long value of attribute
- * @throws ConfigurationException If no parameter with that name exists.
- * or if conversion to
long
fails.
- */
- long getAttributeAsLong( String name ) throws ConfigurationException;
- /**
- * Return the
float
value of the specified parameter contained
- * in this node.
- *
- * @param paramName The name of the parameter you ask the value of.
- * @return float value of attribute
- * @throws ConfigurationException If no parameter with that name exists.
- * or if conversion to
float
fails.
- */
- float getAttributeAsFloat( String paramName ) throws ConfigurationException;
- /**
- * Return the
boolean
value of the specified parameter contained
- * in this node.
- *
- * @param paramName The name of the parameter you ask the value of.
- * @return boolean value of attribute
- * @throws ConfigurationException If no parameter with that name exists.
- * or if conversion to
boolean
fails.
- */
- boolean getAttributeAsBoolean( String paramName ) throws ConfigurationException;
- /**
- * Return the
String
value of the node.
- *
- * @return the value of the node.
- * @throws ConfigurationException if an error occurs
- */
- String getValue() throws ConfigurationException;
- /**
- * Return the
int
value of the node.
- *
- * @return the value of the node.
- *
- * @throws ConfigurationException If conversion to
int
fails.
- */
- int getValueAsInteger() throws ConfigurationException;
- /**
- * Return the
float
value of the node.
- *
- * @return the value of the node.
- * @throws ConfigurationException If conversion to
float
fails.
- */
- float getValueAsFloat() throws ConfigurationException;
- /**
- * Return the
boolean
value of the node.
- *
- * @return the value of the node.
- * @throws ConfigurationException If conversion to
boolean
fails.
- */
- boolean getValueAsBoolean() throws ConfigurationException;
- /**
- * Return the
long
value of the node.
- *
- * @return the value of the node.
- * @throws ConfigurationException If conversion to
long
fails.
- */
- long getValueAsLong() throws ConfigurationException;
- /**
- * Returns the value of the configuration element as a
String
.
- * If the configuration value is not set, the default value will be
- * used.
- *
- * @param defaultValue The default value desired.
- * @return String value of the
Configuration
, or default
- * if none specified.
- */
- String getValue( String defaultValue );
- /**
- * Returns the value of the configuration element as an
int
.
- * If the configuration value is not set, the default value will be
- * used.
- *
- * @param defaultValue The default value desired.
- * @return int value of the
Configuration
, or default
- * if none specified.
- */
- int getValueAsInteger( int defaultValue );
- /**
- * Returns the value of the configuration element as a
long
.
- * If the configuration value is not set, the default value will be
- * used.
- *
- * @param defaultValue The default value desired.
- * @return long value of the
Configuration
, or default
- * if none specified.
- */
- long getValueAsLong( long defaultValue );
- /**
- * Returns the value of the configuration element as a
float
.
- * If the configuration value is not set, the default value will be
- * used.
- *
- * @param defaultValue The default value desired.
- * @return float value of the
Configuration
, or default
- * if none specified.
- */
- float getValueAsFloat( float defaultValue );
- /**
- * Returns the value of the configuration element as a
boolean
.
- * If the configuration value is not set, the default value will be
- * used.
- *
- * @param defaultValue The default value desired.
- * @return boolean value of the
Configuration
, or default
- * if none specified.
- */
- boolean getValueAsBoolean( boolean defaultValue );
- /**
- * Returns the value of the attribute specified by its name as a
- *
String
, or the default value if no attribute by
- * that name exists or is empty.
- *
- * @param name The name of the attribute you ask the value of.
- * @param defaultValue The default value desired.
- * @return String value of attribute. It will return the default
- * value if the named attribute does not exist, or if
- * the value is not set.
- */
- String getAttribute( String name, String defaultValue );
- /**
- * Returns the value of the attribute specified by its name as a
- *
int
, or the default value if no attribute by
- * that name exists or is empty.
- *
- * @param name The name of the attribute you ask the value of.
- * @param defaultValue The default value desired.
- * @return int value of attribute. It will return the default
- * value if the named attribute does not exist, or if
- * the value is not set.
- */
- int getAttributeAsInteger( String name, int defaultValue );
- /**
- * Returns the value of the attribute specified by its name as a
- *
long
, or the default value if no attribute by
- * that name exists or is empty.
- *
- * @param name The name of the attribute you ask the value of.
- * @param defaultValue The default value desired.
- * @return long value of attribute. It will return the default
- * value if the named attribute does not exist, or if
- * the value is not set.
- */
- long getAttributeAsLong( String name, long defaultValue );
- /**
- * Returns the value of the attribute specified by its name as a
- *
float
, or the default value if no attribute by
- * that name exists or is empty.
- *
- * @param name The name of the attribute you ask the value of.
- * @param defaultValue The default value desired.
- * @return float value of attribute. It will return the default
- * value if the named attribute does not exist, or if
- * the value is not set.
- */
- float getAttributeAsFloat( String name, float defaultValue );
- /**
- * Returns the value of the attribute specified by its name as a
- *
boolean
, or the default value if no attribute by
- * that name exists or is empty.
- *
- * @param name The name of the attribute you ask the value of.
- * @param defaultValue The default value desired.
- * @return boolean value of attribute. It will return the default
- * value if the named attribute does not exist, or if
- * the value is not set.
- */
- boolean getAttributeAsBoolean( String name, boolean defaultValue );
diff --git a/clients/java/src/org/apache/avalon/framework/configuration/ConfigurationException.java b/clients/java/src/org/apache/avalon/framework/configuration/ConfigurationException.java
deleted file mode 100644
index 2b52620..0000000
--- a/clients/java/src/org/apache/avalon/framework/configuration/ConfigurationException.java
+++ /dev/null
@@ -1,103 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.configuration;
-import org.apache.avalon.framework.CascadingException;
- * Thrown when a
Configurable
component cannot be configured
- * properly, or if a value cannot be retrieved properly.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.14 $ $Date: 2004/02/11 14:34:24 $
-public class ConfigurationException
- extends CascadingException
- private final Configuration m_config;
- /**
- * Construct a new
ConfigurationException
instance.
- *
- * @param config The offending configuration object
- */
- public ConfigurationException( final Configuration config )
- {
- this( "Bad configuration: " + config.toString(), config );
- }
- /**
- * Construct a new
ConfigurationException
instance.
- *
- * @param message The detail message for this exception.
- */
- public ConfigurationException( final String message )
- {
- this( message, (Configuration) null );
- }
- /**
- * Construct a new
ConfigurationException
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public ConfigurationException( final String message, final Throwable throwable )
- {
- this( message, null, throwable );
- }
- /**
- * Construct a new
ConfigurationException
instance.
- *
- * @param message The detail message for this exception.
- * @param config The configuration object
- */
- public ConfigurationException( final String message, final Configuration config )
- {
- this( message, config, null );
- }
- /**
- * Construct a new
ConfigurationException
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public ConfigurationException( final String message, final Configuration config, final Throwable throwable )
- {
- super( message, throwable );
- m_config = config;
- }
- public Configuration getOffendingConfiguration()
- {
- return m_config;
- }
- public String getMessage()
- {
- StringBuffer message = new StringBuffer(super.getMessage());
- if (null != m_config)
- {
- message.append("@");
- message.append(m_config.getLocation());
- }
- return message.toString();
- }
diff --git a/clients/java/src/org/apache/avalon/framework/configuration/Reconfigurable.java b/clients/java/src/org/apache/avalon/framework/configuration/Reconfigurable.java
deleted file mode 100644
index c671faf..0000000
--- a/clients/java/src/org/apache/avalon/framework/configuration/Reconfigurable.java
+++ /dev/null
@@ -1,36 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.configuration;
- * Extends
Configurable
to allow reconfiguration at runtime.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:24 $
-public interface Reconfigurable
- extends Configurable
- /**
- * Describe
reconfigure
method here.
- *
- * @param configuration a
Configuration
value
- * @throws ConfigurationException if an error occurs
- */
- void reconfigure( Configuration configuration )
- throws ConfigurationException;
diff --git a/clients/java/src/org/apache/avalon/framework/context/Context.java b/clients/java/src/org/apache/avalon/framework/context/Context.java
deleted file mode 100644
index 367f09b..0000000
--- a/clients/java/src/org/apache/avalon/framework/context/Context.java
+++ /dev/null
@@ -1,158 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.context;
- * The context is the interface through which the component and its
- * container communicate.
- *
Note:
In the text below there are several requirements that a
- * component may set up for a container. It is understood that a container
- * does not have to satisfy those requirements in order to be Avalon-compliant.
- * If a component says "I require X to run" a container may reply with "I don't
- * have any X, so I'm not running you". The requirements here are the maximum
- * that a component may ask for, not the minimum a container must deliver.
- * However, a container should document what it is and isn't capable of
- * delivering.
- *
Each Container-Component relationship involves defining a contract
- * between the two entities. A Context contract is defined by (1) an optional
- * target class, and (2) a set of context entries.
- * The optional target class is an interface, called
T
below.
- * It is required that the component should be able to perform
- * the following operation:
- *
public void contextualize( Context context )
- * throws ContextException
- * {
- * T tContext = (T) context;
- * }
- * The container may choose any method to supply the component
- * with a context instance cast-able to
T
.
- * There is no requirement for
T
to extend the
Context
- * interface.
- *
Warning:
A component that specifies this requirement will not
- * be as portable as one that doesn't. Few containers
- * support it. It is therefore discouraged for components
- * to require a castable context.
- * The second part of the context contract defines the set
- * of entries the component can access via the
Context.get()
- * method, where an entry consists of the key passed to
get()
- * and the expected return type (the class or interface).
- * Optionally, an alias for the key name can be specified. The
- * contract associated with a particular entry is defined in the
- * container documentation.
- * The class/interface
T
above may also have associated
- * meta-info that specifies entries, in which case these entries must
- * be supplied by the container in addition to any entries the
- * component itself requires.
- * See:
Context Meta-Info
- * Specification
- * Standard Avalon context entries, their keys, types and and
- * associated semantics are defined under the framework standard
- * attributes table.
- * See:
- * Avalon Standard Context Entries Specification
- *
<entry key="avalon:work" type="java.io.File"/>
- * It should be able to do:
- *
File workDirectory = (File) context.get( "avalon:work" );
- * in order to obtain the value.
- *
<entry alias="work" key="avalon:work" type="java.io.File"/>
- * It should be able to do:
- *
File workDirectory = (File) context.get( "work" );
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:25 $
-public interface Context
- /**
- * Retrieve an object from Context.
- *
- * @param key the key into context
- * @return the object
- * @throws ContextException if object not found. Note that this
- * means that either Component is asking for invalid entry
- * or the Container is not living up to contract.
- */
- Object get( Object key )
- throws ContextException;
diff --git a/clients/java/src/org/apache/avalon/framework/context/ContextException.java b/clients/java/src/org/apache/avalon/framework/context/ContextException.java
deleted file mode 100644
index 5d8bd94..0000000
--- a/clients/java/src/org/apache/avalon/framework/context/ContextException.java
+++ /dev/null
@@ -1,53 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.context;
-import org.apache.avalon.framework.CascadingException;
- * Exception signalling a badly formed Context.
- * This can be thrown by Context object when a entry is not
- * found. It can also be thrown manually in contextualize()
- * when Component detects a malformed context value.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.14 $ $Date: 2004/02/11 14:34:25 $
-public class ContextException
- extends CascadingException
- /**
- * Construct a new
ContextException
instance.
- *
- * @param message The detail message for this exception.
- */
- public ContextException( final String message )
- {
- this( message, null );
- }
- /**
- * Construct a new
ContextException
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public ContextException( final String message, final Throwable throwable )
- {
- super( message, throwable );
- }
diff --git a/clients/java/src/org/apache/avalon/framework/context/Contextualizable.java b/clients/java/src/org/apache/avalon/framework/context/Contextualizable.java
deleted file mode 100644
index a479a64..0000000
--- a/clients/java/src/org/apache/avalon/framework/context/Contextualizable.java
+++ /dev/null
@@ -1,38 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.context;
- * This inteface should be implemented by components that need
- * a Context to work. Context contains runtime generated object
- * provided by the Container to this Component.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
-public interface Contextualizable
- /**
- * Pass the Context to the component.
- * This method is called after the Loggable.setLogger() (if present)
- * method and before any other method.
- *
- * @param context the context. Must not be
null
.
- * @throws ContextException if context is invalid
- */
- void contextualize( Context context )
- throws ContextException;
diff --git a/clients/java/src/org/apache/avalon/framework/context/Recontextualizable.java b/clients/java/src/org/apache/avalon/framework/context/Recontextualizable.java
deleted file mode 100644
index 12f9f5c..0000000
--- a/clients/java/src/org/apache/avalon/framework/context/Recontextualizable.java
+++ /dev/null
@@ -1,39 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.context;
- * Extends Contextualizable to allow recontextualizing.
- * This allows a component to re-receive it's context if
- * container environment has changed.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:25 $
-public interface Recontextualizable
- extends Contextualizable
- /**
- * Pass the new Context to the component.
- * This method is usually called when component is suspended via use of
- * Suspendable.suspend() method.
- *
- * @param context the context
- * @throws ContextException if context is invalid
- */
- void recontextualize( Context context )
- throws ContextException;
diff --git a/clients/java/src/org/apache/avalon/framework/context/Resolvable.java b/clients/java/src/org/apache/avalon/framework/context/Resolvable.java
deleted file mode 100644
index cbffaec..0000000
--- a/clients/java/src/org/apache/avalon/framework/context/Resolvable.java
+++ /dev/null
@@ -1,36 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.context;
- * This interface is used to indicate objects that need to be
- * resolved in some particular context.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:25 $
-public interface Resolvable
- /**
- * Resolve a object to a value.
- *
- * @param context the contextwith respect which to resolve
- * @return the resolved object
- * @throws ContextException if an error occurs
- */
- Object resolve( Context context )
- throws ContextException;
diff --git a/clients/java/src/org/apache/avalon/framework/logger/AbstractLogEnabled.java b/clients/java/src/org/apache/avalon/framework/logger/AbstractLogEnabled.java
deleted file mode 100644
index a9f64ac..0000000
--- a/clients/java/src/org/apache/avalon/framework/logger/AbstractLogEnabled.java
+++ /dev/null
@@ -1,99 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.logger;
- * Utility class to allow easy construction of components that will perform
- * logging.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.4 $ $Date: 2004/02/11 14:34:25 $
-public abstract class AbstractLogEnabled
- implements LogEnabled
- ///Base Logger instance
- private Logger m_logger;
- /**
- * Set the components logger.
- *
- * @param logger the logger
- */
- public void enableLogging( final Logger logger )
- {
- m_logger = logger;
- }
- /**
- * Helper method to allow sub-classes to aquire logger.
- * This method exists rather than exposing a member variable
- * because it protects other users against future changes. It
- * also means they do not have to use our naming convention.
- *
- *
There is no performance penalty as this is a final method - * and will be inlined by the JVM.
- * - * @return the Logger - */ - protected final Logger getLogger() - { - return m_logger; - } - /** - * Helper method to setup other components with same logger. - * - * @param component the component to pass logger object to - */ - protected void setupLogger( final Object component ) - { - setupLogger( component, (String)null ); - } - /** - * Helper method to setup other components with logger. - * The logger has the subcategory of this components logger. - * - * @param component the component to pass logger object to - * @param subCategory the subcategory to use (may be null) - */ - protected void setupLogger( final Object component, final String subCategory ) - { - Logger logger = m_logger; - if( null != subCategory ) - { - logger = m_logger.getChildLogger( subCategory ); - } - setupLogger( component, logger ); - } - /** - * Helper method to setup other components with logger. - * - * @param component the component to pass logger object to - * @param logger the Logger - */ - protected void setupLogger( final Object component, final Logger logger ) - { - if( component instanceof LogEnabled ) - { - ( (LogEnabled)component ).enableLogging( logger ); - } - } diff --git a/clients/java/src/org/apache/avalon/framework/logger/LogEnabled.java b/clients/java/src/org/apache/avalon/framework/logger/LogEnabled.java deleted file mode 100644 index 9d20d44..0000000 --- a/clients/java/src/org/apache/avalon/framework/logger/LogEnabled.java +++ /dev/null @@ -1,33 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.avalon.framework.logger; - * Components that need to log can implement this interface to - * be provided Loggers. - * @author Avalon Development Team - * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:25 $ -public interface LogEnabled - /** - * Provide component with a logger. - * - * @param logger the logger. Must not be
null
.
- */
- void enableLogging( Logger logger );
diff --git a/clients/java/src/org/apache/avalon/framework/logger/Loggable.java b/clients/java/src/org/apache/avalon/framework/logger/Loggable.java
deleted file mode 100644
index fae5824..0000000
--- a/clients/java/src/org/apache/avalon/framework/logger/Loggable.java
+++ /dev/null
@@ -1,35 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.logger;
- * Components that need to log can implement this interface to
- * be provided Loggers.
- * @deprecated Use {@link LogEnabled} instead.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:25 $
-public interface Loggable
- /**
- * Provide component with a logger.
- *
- * @param logger the logger
- */
- void setLogger( Logger logger );
diff --git a/clients/java/src/org/apache/avalon/framework/logger/Logger.java b/clients/java/src/org/apache/avalon/framework/logger/Logger.java
deleted file mode 100644
index 8a43227..0000000
--- a/clients/java/src/org/apache/avalon/framework/logger/Logger.java
+++ /dev/null
@@ -1,147 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.logger;
- * This is a facade for the different logging subsystems.
- * It offers a simplified interface that follows IOC patterns
- * and a simplified priority/level/severity abstraction.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:25 $
-public interface Logger
- /**
- * Log a debug message.
- *
- * @param message the message
- */
- void debug( String message );
- /**
- * Log a debug message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- void debug( String message, Throwable throwable );
- /**
- * Determine if messages of priority "debug" will be logged.
- *
- * @return true if "debug" messages will be logged
- */
- boolean isDebugEnabled();
- /**
- * Log a info message.
- *
- * @param message the message
- */
- void info( String message );
- /**
- * Log a info message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- void info( String message, Throwable throwable );
- /**
- * Determine if messages of priority "info" will be logged.
- *
- * @return true if "info" messages will be logged
- */
- boolean isInfoEnabled();
- /**
- * Log a warn message.
- *
- * @param message the message
- */
- void warn( String message );
- /**
- * Log a warn message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- void warn( String message, Throwable throwable );
- /**
- * Determine if messages of priority "warn" will be logged.
- *
- * @return true if "warn" messages will be logged
- */
- boolean isWarnEnabled();
- /**
- * Log a error message.
- *
- * @param message the message
- */
- void error( String message );
- /**
- * Log a error message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- void error( String message, Throwable throwable );
- /**
- * Determine if messages of priority "error" will be logged.
- *
- * @return true if "error" messages will be logged
- */
- boolean isErrorEnabled();
- /**
- * Log a fatalError message.
- *
- * @param message the message
- */
- void fatalError( String message );
- /**
- * Log a fatalError message.
- *
- * @param message the message
- * @param throwable the throwable
- */
- void fatalError( String message, Throwable throwable );
- /**
- * Determine if messages of priority "fatalError" will be logged.
- *
- * @return true if "fatalError" messages will be logged
- */
- boolean isFatalErrorEnabled();
- /**
- * Create a new child logger.
- * The name of the child logger is [current-loggers-name].[passed-in-name]
- * Throws
IllegalArgumentException
if name has an empty element name
- *
- * @param name the subname of this logger
- * @return the new logger
- */
- Logger getChildLogger( String name );
diff --git a/clients/java/src/org/apache/avalon/framework/parameters/ParameterException.java b/clients/java/src/org/apache/avalon/framework/parameters/ParameterException.java
deleted file mode 100644
index 782b922..0000000
--- a/clients/java/src/org/apache/avalon/framework/parameters/ParameterException.java
+++ /dev/null
@@ -1,50 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.parameters;
-import org.apache.avalon.framework.CascadingException;
- * Thrown when a
Parameterizable
component cannot be parameterized
- * properly, or if a value cannot be retrieved properly.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
-public final class ParameterException
- extends CascadingException
- /**
- * Construct a new
ParameterException
instance.
- *
- * @param message The detail message for this exception.
- */
- public ParameterException( final String message )
- {
- this( message, null );
- }
- /**
- * Construct a new
ParameterException
instance.
- *
- * @param message The detail message for this exception.
- * @param throwable the root cause of the exception
- */
- public ParameterException( final String message, final Throwable throwable )
- {
- super( message, throwable );
- }
diff --git a/clients/java/src/org/apache/avalon/framework/parameters/Parameterizable.java b/clients/java/src/org/apache/avalon/framework/parameters/Parameterizable.java
deleted file mode 100644
index 9b10ce0..0000000
--- a/clients/java/src/org/apache/avalon/framework/parameters/Parameterizable.java
+++ /dev/null
@@ -1,46 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.parameters;
- * Components should implement this interface if they wish to
- * be provided with parameters during startup.
- * The Parameterizable interface is a light-weight alternative to the
- * {@link org.apache.avalon.framework.configuration.Configurable}
- * interface. As such, the
Parameterizable
interface and
- * the
Configurable
interface are
not
- * compatible.
- * This interface will be called after
- *
Composable.compose()
and before
- *
Initializable.initialize()
.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.18 $ $Date: 2004/02/11 14:34:25 $
-public interface Parameterizable
- /**
- * Provide component with parameters.
- *
- * @param parameters the parameters. Must not be
null
.
- * @throws ParameterException if parameters are invalid
- */
- void parameterize( Parameters parameters )
- throws ParameterException;
diff --git a/clients/java/src/org/apache/avalon/framework/parameters/Parameters.java b/clients/java/src/org/apache/avalon/framework/parameters/Parameters.java
deleted file mode 100644
index a078057..0000000
--- a/clients/java/src/org/apache/avalon/framework/parameters/Parameters.java
+++ /dev/null
@@ -1,651 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.parameters;
-import java.io.Serializable;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-import org.apache.avalon.framework.configuration.Configuration;
-import org.apache.avalon.framework.configuration.ConfigurationException;
- * The
Parameters
class represents a set of key-value
- * pairs.
- * The
Parameters
object provides a mechanism to obtain
- * values based on a
String
name. There are convenience
- * methods that allow you to use defaults if the value does not exist,
- * as well as obtain the value in any of the same formats that are in
- * the {@link Configuration} interface.
- * While there are similarities between the
Parameters
- * object and the java.util.Properties object, there are some
- * important semantic differences. First,
Parameters
are
- *
read-only
. Second,
Parameters
are easily
- * derived from {@link Configuration} objects. Lastly, the
- *
Parameters
object is derived from XML fragments that
- * look like this:
- * <parameter name="param-name" value="param-value" />
- *
Note: this class is not thread safe by default.
If you
- * require thread safety please synchronize write access to this class to
- * prevent potential data corruption.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.41 $ $Date: 2004/02/11 14:34:25 $
-public class Parameters
- implements Serializable
- /**
- * Empty Parameters object
- *
- * @since 4.1.2
- */
- public static final Parameters EMPTY_PARAMETERS;
- /** Static initializer to initialize the empty Parameters object */
- static
- {
- EMPTY_PARAMETERS = new Parameters();
- EMPTY_PARAMETERS.makeReadOnly();
- }
- ///Underlying store of parameters
- private Map m_parameters = new HashMap();
- private boolean m_readOnly;
- /**
- * Set the
String
value of a specified parameter.
- *
- * If the specified value is
null
the parameter is removed.
- *
- * @param name a
String
value
- * @param value a
String
value
- * @return The previous value of the parameter or
null
.
- * @throws IllegalStateException if the Parameters object is read-only
- */
- public String setParameter( final String name, final String value )
- throws IllegalStateException
- {
- checkWriteable();
- if( null == name )
- {
- return null;
- }
- if( null == value )
- {
- return (String)m_parameters.remove( name );
- }
- return (String)m_parameters.put( name, value );
- }
- /**
- * Remove a parameter from the parameters object
- * @param name a
String
value
- * @since 4.1
- */
- public void removeParameter( final String name )
- {
- setParameter( name, null );
- }
- /**
- * Return an
Iterator
view of all parameter names.
- *
- * @return a iterator of parameter names
- * @deprecated Use getNames() instead
- */
- public Iterator getParameterNames()
- {
- return m_parameters.keySet().iterator();
- }
- /**
- * Retrieve an array of all parameter names.
- *
- * @return the parameters names
- */
- public String[] getNames()
- {
- return (String[])m_parameters.keySet().toArray( new String[ 0 ] );
- }
- /**
- * Test if the specified parameter can be retrieved.
- *
- * @param name the parameter name
- * @return true if parameter is a name
- */
- public boolean isParameter( final String name )
- {
- return m_parameters.containsKey( name );
- }
- /**
- * Retrieve the
String
value of the specified parameter.
- *
- * If the specified parameter cannot be found, an exception is thrown.
- *
- * @param name the name of parameter
- * @return the value of parameter
- * @throws ParameterException if the specified parameter cannot be found
- */
- public String getParameter( final String name )
- throws ParameterException
- {
- if( null == name )
- {
- throw new ParameterException( "You cannot lookup a null parameter" );
- }
- final String test = (String)m_parameters.get( name );
- if( null == test )
- {
- throw new ParameterException( "The parameter '" + name
- + "' does not contain a value" );
- }
- else
- {
- return test;
- }
- }
- /**
- * Retrieve the
String
value of the specified parameter.
- *
- * If the specified parameter cannot be found,
defaultValue
- * is returned.
- *
- * @param name the name of parameter
- * @param defaultValue the default value, returned if parameter does not exist
- * or parameter's name is null
- * @return the value of parameter
- */
- public String getParameter( final String name, final String defaultValue )
- {
- if( name == null )
- {
- return defaultValue;
- }
- final String test = (String)m_parameters.get( name );
- if( test == null )
- {
- return defaultValue;
- }
- else
- {
- return test;
- }
- }
- /**
- * Parses string represenation of the
int
value.
- *
- * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
- * numbers begin with 0b, all other values are assumed to be decimal.
- *
- * @param value the value to parse
- * @return the integer value
- * @throws NumberFormatException if the specified value can not be parsed
- */
- private int parseInt( final String value )
- throws NumberFormatException
- {
- if( value.startsWith( "0x" ) )
- {
- return Integer.parseInt( value.substring( 2 ), 16 );
- }
- else if( value.startsWith( "0o" ) )
- {
- return Integer.parseInt( value.substring( 2 ), 8 );
- }
- else if( value.startsWith( "0b" ) )
- {
- return Integer.parseInt( value.substring( 2 ), 2 );
- }
- else
- {
- return Integer.parseInt( value );
- }
- }
- /**
- * Retrieve the
int
value of the specified parameter.
- *
- * If the specified parameter cannot be found, an exception is thrown.
- *
- * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
- * numbers begin with 0b, all other values are assumed to be decimal.
- *
- * @param name the name of parameter
- * @return the integer parameter type
- * @throws ParameterException if the specified parameter cannot be found
- * or is not an Integer value
- */
- public int getParameterAsInteger( final String name )
- throws ParameterException
- {
- try
- {
- return parseInt( getParameter( name ) );
- }
- catch( final NumberFormatException e )
- {
- throw new ParameterException( "Could not return an integer value", e );
- }
- }
- /**
- * Retrieve the
int
value of the specified parameter.
- *
- * If the specified parameter cannot be found,
defaultValue
- * is returned.
- *
- * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
- * numbers begin with 0b, all other values are assumed to be decimal.
- *
- * @param name the name of parameter
- * @param defaultValue value returned if parameter does not exist or is of wrong type
- * @return the integer parameter type
- */
- public int getParameterAsInteger( final String name, final int defaultValue )
- {
- try
- {
- final String value = getParameter( name, null );
- if( value == null )
- {
- return defaultValue;
- }
- return parseInt( value );
- }
- catch( final NumberFormatException e )
- {
- return defaultValue;
- }
- }
- /**
- * Parses string represenation of the
long
value.
- *
- * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
- * numbers begin with 0b, all other values are assumed to be decimal.
- *
- * @param value the value to parse
- * @return the long value
- * @throws NumberFormatException if the specified value can not be parsed
- */
- private long parseLong( final String value )
- throws NumberFormatException
- {
- if( value.startsWith( "0x" ) )
- {
- return Long.parseLong( value.substring( 2 ), 16 );
- }
- else if( value.startsWith( "0o" ) )
- {
- return Long.parseLong( value.substring( 2 ), 8 );
- }
- else if( value.startsWith( "0b" ) )
- {
- return Long.parseLong( value.substring( 2 ), 2 );
- }
- else
- {
- return Long.parseLong( value );
- }
- }
- /**
- * Retrieve the
long
value of the specified parameter.
- *
- * If the specified parameter cannot be found, an exception is thrown.
- *
- * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
- * numbers begin with 0b, all other values are assumed to be decimal.
- *
- * @param name the name of parameter
- * @return the long parameter type
- * @throws ParameterException if the specified parameter cannot be found
- * or is not a Long value.
- */
- public long getParameterAsLong( final String name )
- throws ParameterException
- {
- try
- {
- return parseLong( getParameter( name ) );
- }
- catch( final NumberFormatException e )
- {
- throw new ParameterException( "Could not return a long value", e );
- }
- }
- /**
- * Retrieve the
long
value of the specified parameter.
- *
- * If the specified parameter cannot be found,
defaultValue
- * is returned.
- *
- * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
- * numbers begin with 0b, all other values are assumed to be decimal.
- *
- * @param name the name of parameter
- * @param defaultValue value returned if parameter does not exist or is of wrong type
- * @return the long parameter type
- */
- public long getParameterAsLong( final String name, final long defaultValue )
- {
- try
- {
- final String value = getParameter( name, null );
- if( value == null )
- {
- return defaultValue;
- }
- return parseLong( value );
- }
- catch( final NumberFormatException e )
- {
- return defaultValue;
- }
- }
- /**
- * Retrieve the
float
value of the specified parameter.
- *
- * If the specified parameter cannot be found, an exception is thrown.
- *
- * @param name the parameter name
- * @return the value
- * @throws ParameterException if the specified parameter cannot be found
- * or is not a Float value
- */
- public float getParameterAsFloat( final String name )
- throws ParameterException
- {
- try
- {
- return Float.parseFloat( getParameter( name ) );
- }
- catch( final NumberFormatException e )
- {
- throw new ParameterException( "Could not return a float value", e );
- }
- }
- /**
- * Retrieve the
float
value of the specified parameter.
- *
- * If the specified parameter cannot be found,
defaultValue
- * is returned.
- *
- * @param name the parameter name
- * @param defaultValue the default value if parameter does not exist or is of wrong type
- * @return the value
- */
- public float getParameterAsFloat( final String name, final float defaultValue )
- {
- try
- {
- final String value = getParameter( name, null );
- if( value == null )
- {
- return defaultValue;
- }
- return Float.parseFloat( value );
- }
- catch( final NumberFormatException pe )
- {
- return defaultValue;
- }
- }
- /**
- * Retrieve the
boolean
value of the specified parameter.
- *
- * If the specified parameter cannot be found, an exception is thrown.
- *
- * @param name the parameter name
- * @return the value
- * @throws ParameterException if an error occurs
- * @throws ParameterException
- */
- public boolean getParameterAsBoolean( final String name )
- throws ParameterException
- {
- final String value = getParameter( name );
- if( value.equalsIgnoreCase( "true" ) )
- {
- return true;
- }
- else if( value.equalsIgnoreCase( "false" ) )
- {
- return false;
- }
- else
- {
- throw new ParameterException( "Could not return a boolean value" );
- }
- }
- /**
- * Retrieve the
boolean
value of the specified parameter.
- *
- * If the specified parameter cannot be found,
defaultValue
- * is returned.
- *
- * @param name the parameter name
- * @param defaultValue the default value if parameter does not exist or is of wrong type
- * @return the value
- */
- public boolean getParameterAsBoolean( final String name, final boolean defaultValue )
- {
- final String value = getParameter( name, null );
- if( value == null )
- {
- return defaultValue;
- }
- if( value.equalsIgnoreCase( "true" ) )
- {
- return true;
- }
- else if( value.equalsIgnoreCase( "false" ) )
- {
- return false;
- }
- else
- {
- return defaultValue;
- }
- }
- /**
- * Merge parameters from another
Parameters
instance
- * into this.
- *
- * @param other the other Parameters
- * @return This
Parameters
instance.
- */
- public Parameters merge( final Parameters other )
- {
- checkWriteable();
- final String[] names = other.getNames();
- for( int i = 0; i < names.length; i++ )
- {
- final String name = names[ i ];
- String value = null;
- try
- {
- value = other.getParameter( name );
- }
- catch( final ParameterException pe )
- {
- value = null;
- }
- setParameter( name, value );
- }
- return this;
- }
- /**
- * Make this Parameters read-only so that it will throw a
- *
IllegalStateException
if someone tries to
- * modify it.
- */
- public void makeReadOnly()
- {
- m_readOnly = true;
- }
- /**
- * Checks is this
Parameters
object is writeable.
- *
- * @throws IllegalStateException if this
Parameters
object is read-only
- */
- protected final void checkWriteable()
- throws IllegalStateException
- {
- if( m_readOnly )
- {
- throw new IllegalStateException( "Context is read only and can not be modified" );
- }
- }
- /**
- * Create a
Parameters
object from a
Configuration
- * object. This acts exactly like the following method call:
- *
- * Parameters.fromConfiguration(configuration, "parameter"); - *- * - * @param configuration the Configuration - * @return This
Parameters
instance.
- * @throws ConfigurationException if an error occurs
- */
- public static Parameters fromConfiguration( final Configuration configuration )
- throws ConfigurationException
- {
- return fromConfiguration( configuration, "parameter" );
- }
- /**
- * Create a
Parameters
object from a
Configuration
- * object using the supplied element name.
- *
- * @param configuration the Configuration
- * @param elementName the element name for the parameters
- * @return This
Parameters
instance.
- * @throws ConfigurationException if an error occurs
- * @since 4.1
- */
- public static Parameters fromConfiguration( final Configuration configuration,
- final String elementName )
- throws ConfigurationException
- {
- if( null == configuration )
- {
- throw new ConfigurationException(
- "You cannot convert to parameters with a null Configuration" );
- }
- final Configuration[] parameters = configuration.getChildren( elementName );
- final Parameters params = new Parameters();
- for( int i = 0; i < parameters.length; i++ )
- {
- try
- {
- final String name = parameters[ i ].getAttribute( "name" );
- final String value = parameters[ i ].getAttribute( "value" );
- params.setParameter( name, value );
- }
- catch( final Exception e )
- {
- throw new ConfigurationException( "Cannot process Configurable", e );
- }
- }
- return params;
- }
- /**
- * Create a
Parameters
object from a
Properties
- * object.
- *
- * @param properties the Properties
- * @return This
Parameters
instance.
- */
- public static Parameters fromProperties( final Properties properties )
- {
- final Parameters parameters = new Parameters();
- final Enumeration names = properties.propertyNames();
- while( names.hasMoreElements() )
- {
- final String key = names.nextElement().toString();
- final String value = properties.getProperty( key );
- parameters.setParameter( key, value );
- }
- return parameters;
- }
- /**
- * Creates a
java.util.Properties
object from an Avalon
- * Parameters object.
- *
- * @param params a
Parameters
instance
- * @return a
Properties
instance
- */
- public static Properties toProperties( final Parameters params )
- {
- final Properties properties = new Properties();
- final String[] names = params.getNames();
- for( int i = 0; i < names.length; ++i )
- {
- // "" is the default value, since getNames() proves it will exist
- properties.setProperty( names[ i ], params.getParameter( names[ i ], "" ) );
- }
- return properties;
- }
diff --git a/clients/java/src/org/apache/avalon/framework/parameters/Reparameterizable.java b/clients/java/src/org/apache/avalon/framework/parameters/Reparameterizable.java
deleted file mode 100644
index b2c8691..0000000
--- a/clients/java/src/org/apache/avalon/framework/parameters/Reparameterizable.java
+++ /dev/null
@@ -1,38 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.parameters;
- * Components should implement this interface if they wish to
- * be provided with parameters during its lifetime. This interface
- * will be called after Startable.start() and before
- * Startable.stop(). It is incompatible with the
- * Reconfigurable interface.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.13 $ $Date: 2004/02/11 14:34:25 $
-public interface Reparameterizable extends Parameterizable
- /**
- * Provide component with parameters.
- *
- * @param parameters the parameters
- * @throws ParameterException if parameters are invalid
- */
- void reparameterize( Parameters parameters )
- throws ParameterException;
diff --git a/clients/java/src/org/apache/avalon/framework/service/ServiceException.java b/clients/java/src/org/apache/avalon/framework/service/ServiceException.java
deleted file mode 100644
index 543a6a7..0000000
--- a/clients/java/src/org/apache/avalon/framework/service/ServiceException.java
+++ /dev/null
@@ -1,114 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.service;
-import org.apache.avalon.framework.CascadingException;
- * The exception thrown to indicate a problem with service.
- * It is usually thrown by ServiceManager or ServiceSelector.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.21 $ $Date: 2004/02/11 14:34:25 $
-public class ServiceException
- extends CascadingException
- private final String m_key;
- /**
- * Construct a new
ServiceException
instance.
- *
- * @deprecated use the String,String,Throwable version instead
- * @param message the exception message
- * @param throwable the throwable
- */
- public ServiceException( final String message, final Throwable throwable )
- {
- this( null, message, throwable );
- }
- /**
- * Construct a new
ServiceException
instance.
- *
- * @param key the lookup key
- * @param message the exception message
- * @param throwable the throwable
- */
- public ServiceException( final String key, final String message, final Throwable throwable )
- {
- super( message, throwable );
- m_key = key;
- }
- /**
- * Construct a new
ServiceException
instance.
- *
- * @deprecated use the String,String version instead
- * @param message the exception message
- */
- public ServiceException( final String message )
- {
- this( null, message, null );
- }
- /**
- * Construct a new
ServiceException
instance.
- *
- * @param key the lookup key
- * @param message the exception message
- */
- public ServiceException( final String key, final String message )
- {
- this( key, message, null );
- }
- /**
- * Return the key that caused the exception.
- * @return the lookup key triggering the exception
- */
- public String getKey()
- {
- return m_key;
- }
- /**
- * Return the role that caused the exception
- *
- * @deprecated Use getKey() instead
- * @return the the lookup key triggering the exception
- */
- public String getRole()
- {
- return getKey();
- }
- /**
- * Override super's message to add role if applicable.
- * @return a message.
- */
- public String getMessage()
- {
- if( m_key == null )
- {
- return super.getMessage();
- }
- else
- {
- return super.getMessage() + " (Key='" + m_key + "')";
- }
- }
diff --git a/clients/java/src/org/apache/avalon/framework/service/ServiceManager.java b/clients/java/src/org/apache/avalon/framework/service/ServiceManager.java
deleted file mode 100644
index 0735073..0000000
--- a/clients/java/src/org/apache/avalon/framework/service/ServiceManager.java
+++ /dev/null
@@ -1,93 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.service;
- * A
ServiceManager
selects
Object
s based on a
- * role. The contract is that all the
Object
s implement the
- * differing roles and there is one
Object
per role. If you
- * need to select on of many
Object
s that implement the same
- * role, then you need to use a
ServiceSelector
. Roles are
- * usually the full interface name.
- * A role is better understood by the analogy of a play. There are many
- * different roles in a script. Any actor or actress can play any given part
- * and you get the same results (phrases said, movements made, etc.). The exact
- * nuances of the performance is different.
- * Below is a list of things that might be considered the different roles:
- *
ServiceManager
does not specify the methodology of
- * getting the
Object
, merely the interface used to get it.
- * Therefore the
ServiceManager
can be implemented with a
- * factory pattern, an object pool, or a simple Hashtable.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.17 $ $Date: 2004/02/11 14:34:25 $
- * @see org.apache.avalon.framework.service.Serviceable
- * @see org.apache.avalon.framework.service.ServiceSelector
-public interface ServiceManager
- /**
- * Get the
Object
associated with the given key. For
- * instance, If the
ServiceManager
had a
- *
LoggerComponent
stored and referenced by key,
- * the following could be used:
- *
- * try - * { - * LoggerComponent log; - * myComponent = (LoggerComponent) manager.lookup( LoggerComponent.ROLE ); - * } - * catch (...) - * { - * ... - * } - *- * - * @param key The lookup key of the
Object
to retrieve.
- * @return an
Object
value
- * @throws ServiceException if an error occurs
- */
- Object lookup( String key )
- throws ServiceException;
- /**
- * Check to see if a
Object
exists for a key.
- *
- * @param key a string identifying the key to check.
- * @return True if the object exists, False if it does not.
- */
- boolean hasService( String key );
- /**
- * Return the
Object
when you are finished with it. This
- * allows the
ServiceManager
to handle the End-Of-Life Lifecycle
- * events associated with the
Object
. Please note, that no
- * Exception should be thrown at this point. This is to allow easy use of the
- * ServiceManager system without having to trap Exceptions on a release.
- *
- * @param object The
Object
we are releasing, may also be
- * a
null
reference
- */
- void release( Object object );
diff --git a/clients/java/src/org/apache/avalon/framework/service/ServiceSelector.java b/clients/java/src/org/apache/avalon/framework/service/ServiceSelector.java
deleted file mode 100644
index 519d631..0000000
--- a/clients/java/src/org/apache/avalon/framework/service/ServiceSelector.java
+++ /dev/null
@@ -1,75 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.service;
- * A
ServiceSelector
selects {@link Object}s based on a
- * supplied policy. The contract is that all the {@link Object}s implement the
- * same role.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.16 $ $Date: 2004/02/11 14:34:25 $
- * @see org.apache.avalon.framework.service.Serviceable
- * @see org.apache.avalon.framework.service.ServiceSelector
-public interface ServiceSelector
- /**
- * Select the {@link Object} associated with the given policy.
- * For instance, If the {@link ServiceSelector} has a
- *
Generator
stored and referenced by a URL, the
- * following call could be used:
- *
- *
- * try - * { - * Generator input; - * input = (Generator)selector.select( new URL("foo://demo/url") ); - * } - * catch (...) - * { - * ... - * } - *- * - * @param policy A criteria against which a {@link Object} is selected. - * - * @return an {@link Object} value - * @throws ServiceException If the requested {@link Object} cannot be supplied - */ - Object select( Object policy ) - throws ServiceException; - /** - * Check to see if a {@link Object} exists relative to the supplied policy. - * - * @param policy a {@link Object} containing the selection criteria - * @return True if the component is available, False if it not. - */ - boolean isSelectable( Object policy ); - /** - * Return the {@link Object} when you are finished with it. This - * allows the {@link ServiceSelector} to handle the End-Of-Life Lifecycle - * events associated with the {@link Object}. Please note, that no - * Exception should be thrown at this point. This is to allow easy use of the - * ServiceSelector system without having to trap Exceptions on a release. - * - * @param object The {@link Object} we are releasing, may also be a - *
null
reference
- */
- void release( Object object );
diff --git a/clients/java/src/org/apache/avalon/framework/service/Serviceable.java b/clients/java/src/org/apache/avalon/framework/service/Serviceable.java
deleted file mode 100644
index 0b5b9e3..0000000
--- a/clients/java/src/org/apache/avalon/framework/service/Serviceable.java
+++ /dev/null
@@ -1,50 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.service;
- * A Serviceable is a class that need to connect to software components using
- * a "role" abstraction, thus not depending on particular implementations
- * but on behavioral interfaces.
- * The contract surrounding a
Serviceable
is that it is a user.
- * The
Serviceable
is able to use
Object
s managed
- * by the
ServiceManager
it was initialized with. As part
- * of the contract with the system, the instantiating entity must call
- * the
service
method before the
Serviceable
- * can be considered valid.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.19 $ $Date: 2004/02/11 14:34:25 $
- * @see org.apache.avalon.framework.service.ServiceManager
-public interface Serviceable
- /**
- * Pass the
ServiceManager
to the
Serviceable
.
- * The
Serviceable
implementation should use the specified
- *
ServiceManager
to acquire the components it needs for
- * execution.
- *
- * @param manager The
ServiceManager
which this
- *
Serviceable
uses. Must not be
null
.
- * @throws ServiceException if an error occurs
- */
- void service( ServiceManager manager )
- throws ServiceException;
diff --git a/clients/java/src/org/apache/avalon/framework/thread/SingleThreaded.java b/clients/java/src/org/apache/avalon/framework/thread/SingleThreaded.java
deleted file mode 100644
index 6a69f38..0000000
--- a/clients/java/src/org/apache/avalon/framework/thread/SingleThreaded.java
+++ /dev/null
@@ -1,27 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.thread;
- * A interface to mark a component as SingleThreaded.
- * This interface is incompatible with ThreadSafe.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
-public interface SingleThreaded
diff --git a/clients/java/src/org/apache/avalon/framework/thread/ThreadSafe.java b/clients/java/src/org/apache/avalon/framework/thread/ThreadSafe.java
deleted file mode 100644
index f30a206..0000000
--- a/clients/java/src/org/apache/avalon/framework/thread/ThreadSafe.java
+++ /dev/null
@@ -1,27 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.avalon.framework.thread;
- * A interface to mark a component as ThreadSafe or reentrant.
- * This interface is incompatible with SingleThreaded.
- * @author
Avalon Development Team
- * @version CVS $Revision: 1.15 $ $Date: 2004/02/11 14:34:25 $
-public interface ThreadSafe
diff --git a/clients/java/src/org/apache/commons/codec/BinaryDecoder.java b/clients/java/src/org/apache/commons/codec/BinaryDecoder.java
deleted file mode 100644
index 2ef1449..0000000
--- a/clients/java/src/org/apache/commons/codec/BinaryDecoder.java
+++ /dev/null
@@ -1,41 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
- * Defines common decoding methods for byte array decoders.
- * @author Apache Software Foundation
- * @version $Id: BinaryDecoder.java,v 1.10 2004/06/15 18:14:15 ggregory Exp $
-public interface BinaryDecoder extends Decoder {
- /**
- * Decodes a byte array and returns the results as a byte array.
- *
- * @param pArray A byte array which has been encoded with the
- * appropriate encoder
- *
- * @return a byte array that contains decoded content
- *
- * @throws DecoderException A decoder exception is thrown
- * if a Decoder encounters a failure condition during
- * the decode process.
- */
- byte[] decode(byte[] pArray) throws DecoderException;
diff --git a/clients/java/src/org/apache/commons/codec/BinaryEncoder.java b/clients/java/src/org/apache/commons/codec/BinaryEncoder.java
deleted file mode 100644
index db8d1ae..0000000
--- a/clients/java/src/org/apache/commons/codec/BinaryEncoder.java
+++ /dev/null
@@ -1,41 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
- * Defines common encoding methods for byte array encoders.
- * @author Apache Software Foundation
- * @version $Id: BinaryEncoder.java,v 1.10 2004/02/29 04:08:31 tobrien Exp $
-public interface BinaryEncoder extends Encoder {
- /**
- * Encodes a byte array and return the encoded data
- * as a byte array.
- *
- * @param pArray Data to be encoded
- *
- * @return A byte array containing the encoded data
- *
- * @throws EncoderException thrown if the Encoder
- * encounters a failure condition during the
- * encoding process.
- */
- byte[] encode(byte[] pArray) throws EncoderException;
diff --git a/clients/java/src/org/apache/commons/codec/Decoder.java b/clients/java/src/org/apache/commons/codec/Decoder.java
deleted file mode 100644
index d066f01..0000000
--- a/clients/java/src/org/apache/commons/codec/Decoder.java
+++ /dev/null
@@ -1,54 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
- *
Provides the highest level of abstraction for Decoders. - * This is the sister interface of {@link Encoder}. All - * Decoders implement this common generic interface.
- *Allows a user to pass a generic Object to any Decoder - * implementation in the codec package.
- *One of the two interfaces at the center of the codec package.
- * @author Apache Software Foundation - * @version $Id: Decoder.java,v 1.9 2004/02/29 04:08:31 tobrien Exp $ -public interface Decoder { - /** - * Decodes an "encoded" Object and returns a "decoded" - * Object. Note that the implementation of this - * interface will try to cast the Object parameter - * to the specific type expected by a particular Decoder - * implementation. If a {@link java.lang.ClassCastException} occurs - * this decode method will throw a DecoderException. - * - * @param pObject an object to "decode" - * - * @return a 'decoded" object - * - * @throws DecoderException a decoder exception can - * be thrown for any number of reasons. Some good - * candidates are that the parameter passed to this - * method is null, a param cannot be cast to the - * appropriate type for a specific encoder. - */ - Object decode(Object pObject) throws DecoderException; diff --git a/clients/java/src/org/apache/commons/codec/DecoderException.java b/clients/java/src/org/apache/commons/codec/DecoderException.java deleted file mode 100644 index 5d53ec1..0000000 --- a/clients/java/src/org/apache/commons/codec/DecoderException.java +++ /dev/null @@ -1,37 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec; - * Thrown when a Decoder has encountered a failure condition during a decode. - * @author Apache Software Foundation - * @version $Id: DecoderException.java,v 1.9 2004/02/29 04:08:31 tobrien Exp $ -public class DecoderException extends Exception { - /** - * Creates a DecoderException - * - * @param pMessage A message with meaning to a human - */ - public DecoderException(String pMessage) { - super(pMessage); - } diff --git a/clients/java/src/org/apache/commons/codec/Encoder.java b/clients/java/src/org/apache/commons/codec/Encoder.java deleted file mode 100644 index ba5ccee..0000000 --- a/clients/java/src/org/apache/commons/codec/Encoder.java +++ /dev/null @@ -1,45 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec; - *Provides the highest level of abstraction for Encoders. - * This is the sister interface of {@link Decoder}. Every implementation of - * Encoder provides this common generic interface whic allows a user to pass a - * generic Object to any Encoder implementation in the codec package.
- * @author Apache Software Foundation - * @version $Id: Encoder.java,v 1.10 2004/02/29 04:08:31 tobrien Exp $ -public interface Encoder { - /** - * Encodes an "Object" and returns the encoded content - * as an Object. The Objects here may just be
byte[]
- * or
String
s depending on the implementation used.
- *
- * @param pObject An object ot encode
- *
- * @return An "encoded" Object
- *
- * @throws EncoderException an encoder exception is
- * thrown if the encoder experiences a failure
- * condition during the encoding process.
- */
- Object encode(Object pObject) throws EncoderException;
diff --git a/clients/java/src/org/apache/commons/codec/EncoderException.java b/clients/java/src/org/apache/commons/codec/EncoderException.java
deleted file mode 100644
index 55984c8..0000000
--- a/clients/java/src/org/apache/commons/codec/EncoderException.java
+++ /dev/null
@@ -1,39 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
- * Thrown when there is a failure condition during the encoding process. This
- * exception is thrown when an Encoder encounters a encoding specific exception
- * such as invalid data, inability to calculate a checksum, characters outside of the
- * expected range.
- * @author Apache Software Foundation
- * @version $Id: EncoderException.java,v 1.10 2004/02/29 04:08:31 tobrien Exp $
-public class EncoderException extends Exception {
- /**
- * Creates a new instance of this exception with an useful message.
- *
- * @param pMessage a useful message relating to the encoder specific error.
- */
- public EncoderException(String pMessage) {
- super(pMessage);
- }
diff --git a/clients/java/src/org/apache/commons/codec/StringDecoder.java b/clients/java/src/org/apache/commons/codec/StringDecoder.java
deleted file mode 100644
index 68f55dd..0000000
--- a/clients/java/src/org/apache/commons/codec/StringDecoder.java
+++ /dev/null
@@ -1,39 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
- * Decodes a String into a String.
- * @author Apache Software Foundation
- * @version $Id: StringDecoder.java,v 1.9 2004/02/29 04:08:31 tobrien Exp $
-public interface StringDecoder extends Decoder {
- /**
- * Decodes a String and returns a String.
- *
- * @param pString a String to encode
- *
- * @return the encoded String
- *
- * @throws DecoderException thrown if there is
- * an error conidition during the Encoding process.
- */
- String decode(String pString) throws DecoderException;
diff --git a/clients/java/src/org/apache/commons/codec/StringEncoder.java b/clients/java/src/org/apache/commons/codec/StringEncoder.java
deleted file mode 100644
index 0617337..0000000
--- a/clients/java/src/org/apache/commons/codec/StringEncoder.java
+++ /dev/null
@@ -1,39 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
- * Encodes a String into a String.
- * @author Apache Software Foundation
- * @version $Id: StringEncoder.java,v 1.9 2004/02/29 04:08:31 tobrien Exp $
-public interface StringEncoder extends Encoder {
- /**
- * Encodes a String and returns a String.
- *
- * @param pString a String to encode
- *
- * @return the encoded String
- *
- * @throws EncoderException thrown if there is
- * an error conidition during the Encoding process.
- */
- String encode(String pString) throws EncoderException;
diff --git a/clients/java/src/org/apache/commons/codec/StringEncoderComparator.java b/clients/java/src/org/apache/commons/codec/StringEncoderComparator.java
deleted file mode 100644
index 21b7a05..0000000
--- a/clients/java/src/org/apache/commons/codec/StringEncoderComparator.java
+++ /dev/null
@@ -1,83 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec;
-import java.util.Comparator;
- * Strings are comparable, and this comparator allows
- * you to configure it with an instance of a class
- * which implements StringEncoder. This comparator
- * is used to sort Strings by an encoding scheme such
- * as Soundex, Metaphone, etc. This class can come in
- * handy if one need to sort Strings by an encoded
- * form of a name such as Soundex.
- * @author Apache Software Foundation
- * @version $Id: StringEncoderComparator.java,v 1.14 2004/06/21 23:24:17 ggregory Exp $
-public class StringEncoderComparator implements Comparator {
- /**
- * Internal encoder instance.
- */
- private StringEncoder stringEncoder;
- /**
- * Constructs a new instance.
- */
- public StringEncoderComparator() {
- // no init.
- }
- /**
- * Constructs a new instance with the given algorithm.
- * @param stringEncoder the StringEncoder used for comparisons.
- */
- public StringEncoderComparator(StringEncoder stringEncoder) {
- this.stringEncoder = stringEncoder;
- }
- /**
- * Compares two strings based not on the strings
- * themselves, but on an encoding of the two
- * strings using the StringEncoder this Comparator
- * was created with.
- *
- * If an {@link EncoderException} is encountered, return
0
.
- *
- * @param o1 the object to compare
- * @param o2 the object to compare to
- * @return the Comparable.compareTo() return code or 0 if an encoding error was caught.
- * @see Comparable
- */
- public int compare(Object o1, Object o2) {
- int compareCode = 0;
- try {
- Comparable s1 = (Comparable) ((Encoder) this.stringEncoder).encode(o1);
- Comparable s2 = (Comparable) ((Encoder) this.stringEncoder).encode(o2);
- compareCode = s1.compareTo(s2);
- }
- catch (EncoderException ee) {
- compareCode = 0;
- }
- return compareCode;
- }
diff --git a/clients/java/src/org/apache/commons/codec/binary/Base64.java b/clients/java/src/org/apache/commons/codec/binary/Base64.java
deleted file mode 100644
index 08d7164..0000000
--- a/clients/java/src/org/apache/commons/codec/binary/Base64.java
+++ /dev/null
@@ -1,524 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.binary;
-import org.apache.commons.codec.BinaryDecoder;
-import org.apache.commons.codec.BinaryEncoder;
-import org.apache.commons.codec.DecoderException;
-import org.apache.commons.codec.EncoderException;
- * Provides Base64 encoding and decoding as defined by RFC 2045.
- *
This class implements section 6.8. Base64 Content-Transfer-Encoding - * from RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: - * Format of Internet Message Bodies by Freed and Borenstein.
- * @see RFC 2045 - * @author Apache Software Foundation - * @since 1.0-dev - * @version $Id: Base64.java,v 1.20 2004/05/24 00:21:24 ggregory Exp $ -public class Base64 implements BinaryEncoder, BinaryDecoder { - /** - * Chunk size per RFC 2045 section 6.8. - * - *The {@value} character limit does not count the trailing CRLF, but counts - * all other characters, including any equal signs.
- * - * @see RFC 2045 section 6.8 - */ - static final int CHUNK_SIZE = 76; - /** - * Chunk separator per RFC 2045 section 2.1. - * - * @see RFC 2045 section 2.1 - */ - static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes(); - /** - * The base length. - */ - static final int BASELENGTH = 255; - /** - * Lookup length. - */ - static final int LOOKUPLENGTH = 64; - /** - * Used to calculate the number of bits in a byte. - */ - static final int EIGHTBIT = 8; - /** - * Used when encoding something which has fewer than 24 bits. - */ - static final int SIXTEENBIT = 16; - /** - * Used to determine how many bits data contains. - */ - static final int TWENTYFOURBITGROUP = 24; - /** - * Used to get the number of Quadruples. - */ - static final int FOURBYTE = 4; - /** - * Used to test the sign of a byte. - */ - static final int SIGN = -128; - /** - * Byte used to pad output. - */ - static final byte PAD = (byte) '='; - // Create arrays to hold the base64 characters and a - // lookup for base64 chars - private static byte[] base64Alphabet = new byte[BASELENGTH]; - private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; - // Populating the lookup and character arrays - static { - for (int i = 0; i < BASELENGTH; i++) { - base64Alphabet[i] = (byte) -1; - } - for (int i = 'Z'; i >= 'A'; i--) { - base64Alphabet[i] = (byte) (i - 'A'); - } - for (int i = 'z'; i >= 'a'; i--) { - base64Alphabet[i] = (byte) (i - 'a' + 26); - } - for (int i = '9'; i >= '0'; i--) { - base64Alphabet[i] = (byte) (i - '0' + 52); - } - base64Alphabet['+'] = 62; - base64Alphabet['/'] = 63; - for (int i = 0; i <= 25; i++) { - lookUpBase64Alphabet[i] = (byte) ('A' + i); - } - for (int i = 26, j = 0; i <= 51; i++, j++) { - lookUpBase64Alphabet[i] = (byte) ('a' + j); - } - for (int i = 52, j = 0; i <= 61; i++, j++) { - lookUpBase64Alphabet[i] = (byte) ('0' + j); - } - lookUpBase64Alphabet[62] = (byte) '+'; - lookUpBase64Alphabet[63] = (byte) '/'; - } - private static boolean isBase64(byte octect) { - if (octect == PAD) { - return true; - } else if (base64Alphabet[octect] == -1) { - return false; - } else { - return true; - } - } - /** - * Tests a given byte array to see if it contains - * only valid characters within the Base64 alphabet. - * - * @param arrayOctect byte array to test - * @return true if all bytes are valid characters in the Base64 - * alphabet or if the byte array is empty; false, otherwise - */ - public static boolean isArrayByteBase64(byte[] arrayOctect) { - arrayOctect = discardWhitespace(arrayOctect); - int length = arrayOctect.length; - if (length == 0) { - // shouldn't a 0 length array be valid base64 data? - // return false; - return true; - } - for (int i = 0; i < length; i++) { - if (!isBase64(arrayOctect[i])) { - return false; - } - } - return true; - } - /** - * Encodes binary data using the base64 algorithm but - * does not chunk the output. - * - * @param binaryData binary data to encode - * @return Base64 characters - */ - public static byte[] encodeBase64(byte[] binaryData) { - return encodeBase64(binaryData, false); - } - /** - * Encodes binary data using the base64 algorithm and chunks - * the encoded output into 76 character blocks - * - * @param binaryData binary data to encode - * @return Base64 characters chunked in 76 character blocks - */ - public static byte[] encodeBase64Chunked(byte[] binaryData) { - return encodeBase64(binaryData, true); - } - /** - * Decodes an Object using the base64 algorithm. This method - * is provided in order to satisfy the requirements of the - * Decoder interface, and will throw a DecoderException if the - * supplied object is not of type byte[]. - * - * @param pObject Object to decode - * @return An object (of type byte[]) containing the - * binary data which corresponds to the byte[] supplied. - * @throws DecoderException if the parameter supplied is not - * of type byte[] - */ - public Object decode(Object pObject) throws DecoderException { - if (!(pObject instanceof byte[])) { - throw new DecoderException("Parameter supplied to Base64 decode is not a byte[]"); - } - return decode((byte[]) pObject); - } - /** - * Decodes a byte[] containing containing - * characters in the Base64 alphabet. - * - * @param pArray A byte array containing Base64 character data - * @return a byte array containing binary data - */ - public byte[] decode(byte[] pArray) { - return decodeBase64(pArray); - } - /** - * Encodes binary data using the base64 algorithm, optionally - * chunking the output into 76 character blocks. - * - * @param binaryData Array containing binary data to encode. - * @param isChunked if isChunked is true this encoder will chunk - * the base64 output into 76 character blocks - * @return Base64-encoded data. - */ - public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) { - int lengthDataBits = binaryData.length * EIGHTBIT; - int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; - int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; - byte encodedData[] = null; - int encodedDataLength = 0; - int nbrChunks = 0; - if (fewerThan24bits != 0) { - //data not divisible by 24 bit - encodedDataLength = (numberTriplets + 1) * 4; - } else { - // 16 or 8 bit - encodedDataLength = numberTriplets * 4; - } - // If the output is to be "chunked" into 76 character sections, - // for compliance with RFC 2045 MIME, then it is important to - // allow for extra length to account for the separator(s) - if (isChunked) { - nbrChunks = - (CHUNK_SEPARATOR.length == 0 ? 0 : (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE)); - encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length; - } - encodedData = new byte[encodedDataLength]; - byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; - int encodedIndex = 0; - int dataIndex = 0; - int i = 0; - int nextSeparatorIndex = CHUNK_SIZE; - int chunksSoFar = 0; - //log.debug("number of triplets = " + numberTriplets); - for (i = 0; i < numberTriplets; i++) { - dataIndex = i * 3; - b1 = binaryData[dataIndex]; - b2 = binaryData[dataIndex + 1]; - b3 = binaryData[dataIndex + 2]; - //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); - l = (byte) (b2 & 0x0f); - k = (byte) (b1 & 0x03); - byte val1 = - ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); - byte val2 = - ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); - byte val3 = - ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc); - encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; - //log.debug( "val2 = " + val2 ); - //log.debug( "k4 = " + (k<<4) ); - //log.debug( "vak = " + (val2 | (k<<4)) ); - encodedData[encodedIndex + 1] = - lookUpBase64Alphabet[val2 | (k << 4)]; - encodedData[encodedIndex + 2] = - lookUpBase64Alphabet[(l << 2) | val3]; - encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; - encodedIndex += 4; - // If we are chunking, let's put a chunk separator down. - if (isChunked) { - // this assumes that CHUNK_SIZE % 4 == 0 - if (encodedIndex == nextSeparatorIndex) { - System.arraycopy( - CHUNK_SEPARATOR, - 0, - encodedData, - encodedIndex, - CHUNK_SEPARATOR.length); - chunksSoFar++; - nextSeparatorIndex = - (CHUNK_SIZE * (chunksSoFar + 1)) + - (chunksSoFar * CHUNK_SEPARATOR.length); - encodedIndex += CHUNK_SEPARATOR.length; - } - } - } - // form integral number of 6-bit groups - dataIndex = i * 3; - if (fewerThan24bits == EIGHTBIT) { - b1 = binaryData[dataIndex]; - k = (byte) (b1 & 0x03); - //log.debug("b1=" + b1); - //log.debug("b1<<2 = " + (b1>>2) ); - byte val1 = - ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); - encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; - encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4]; - encodedData[encodedIndex + 2] = PAD; - encodedData[encodedIndex + 3] = PAD; - } else if (fewerThan24bits == SIXTEENBIT) { - b1 = binaryData[dataIndex]; - b2 = binaryData[dataIndex + 1]; - l = (byte) (b2 & 0x0f); - k = (byte) (b1 & 0x03); - byte val1 = - ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0); - byte val2 = - ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0); - encodedData[encodedIndex] = lookUpBase64Alphabet[val1]; - encodedData[encodedIndex + 1] = - lookUpBase64Alphabet[val2 | (k << 4)]; - encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2]; - encodedData[encodedIndex + 3] = PAD; - } - if (isChunked) { - // we also add a separator to the end of the final chunk. - if (chunksSoFar < nbrChunks) { - System.arraycopy( - CHUNK_SEPARATOR, - 0, - encodedData, - encodedDataLength - CHUNK_SEPARATOR.length, - CHUNK_SEPARATOR.length); - } - } - return encodedData; - } - /** - * Decodes Base64 data into octects - * - * @param base64Data Byte array containing Base64 data - * @return Array containing decoded data. - */ - public static byte[] decodeBase64(byte[] base64Data) { - // RFC 2045 requires that we discard ALL non-Base64 characters - base64Data = discardNonBase64(base64Data); - // handle the edge case, so we don't have to worry about it later - if (base64Data.length == 0) { - return new byte[0]; - } - int numberQuadruple = base64Data.length / FOURBYTE; - byte decodedData[] = null; - byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0; - // Throw away anything not in base64Data - int encodedIndex = 0; - int dataIndex = 0; - { - // this sizes the output array properly - rlw - int lastData = base64Data.length; - // ignore the '=' padding - while (base64Data[lastData - 1] == PAD) { - if (--lastData == 0) { - return new byte[0]; - } - } - decodedData = new byte[lastData - numberQuadruple]; - } - for (int i = 0; i < numberQuadruple; i++) { - dataIndex = i * 4; - marker0 = base64Data[dataIndex + 2]; - marker1 = base64Data[dataIndex + 3]; - b1 = base64Alphabet[base64Data[dataIndex]]; - b2 = base64Alphabet[base64Data[dataIndex + 1]]; - if (marker0 != PAD && marker1 != PAD) { - //No PAD e.g 3cQl - b3 = base64Alphabet[marker0]; - b4 = base64Alphabet[marker1]; - decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); - decodedData[encodedIndex + 1] = - (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); - decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); - } else if (marker0 == PAD) { - //Two PAD e.g. 3c[Pad][Pad] - decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); - } else if (marker1 == PAD) { - //One PAD e.g. 3cQ[Pad] - b3 = base64Alphabet[marker0]; - decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); - decodedData[encodedIndex + 1] = - (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); - } - encodedIndex += 3; - } - return decodedData; - } - /** - * Discards any whitespace from a base-64 encoded block. - * - * @param data The base-64 encoded data to discard the whitespace - * from. - * @return The data, less whitespace (see RFC 2045). - */ - static byte[] discardWhitespace(byte[] data) { - byte groomedData[] = new byte[data.length]; - int bytesCopied = 0; - for (int i = 0; i < data.length; i++) { - switch (data[i]) { - case (byte) ' ' : - case (byte) '\n' : - case (byte) '\r' : - case (byte) '\t' : - break; - default: - groomedData[bytesCopied++] = data[i]; - } - } - byte packedData[] = new byte[bytesCopied]; - System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); - return packedData; - } - /** - * Discards any characters outside of the base64 alphabet, per - * the requirements on page 25 of RFC 2045 - "Any characters - * outside of the base64 alphabet are to be ignored in base64 - * encoded data." - * - * @param data The base-64 encoded data to groom - * @return The data, less non-base64 characters (see RFC 2045). - */ - static byte[] discardNonBase64(byte[] data) { - byte groomedData[] = new byte[data.length]; - int bytesCopied = 0; - for (int i = 0; i < data.length; i++) { - if (isBase64(data[i])) { - groomedData[bytesCopied++] = data[i]; - } - } - byte packedData[] = new byte[bytesCopied]; - System.arraycopy(groomedData, 0, packedData, 0, bytesCopied); - return packedData; - } - // Implementation of the Encoder Interface - /** - * Encodes an Object using the base64 algorithm. This method - * is provided in order to satisfy the requirements of the - * Encoder interface, and will throw an EncoderException if the - * supplied object is not of type byte[]. - * - * @param pObject Object to encode - * @return An object (of type byte[]) containing the - * base64 encoded data which corresponds to the byte[] supplied. - * @throws EncoderException if the parameter supplied is not - * of type byte[] - */ - public Object encode(Object pObject) throws EncoderException { - if (!(pObject instanceof byte[])) { - throw new EncoderException( - "Parameter supplied to Base64 encode is not a byte[]"); - } - return encode((byte[]) pObject); - } - /** - * Encodes a byte[] containing binary data, into a byte[] containing - * characters in the Base64 alphabet. - * - * @param pArray a byte array containing binary data - * @return A byte array containing only Base64 character data - */ - public byte[] encode(byte[] pArray) { - return encodeBase64(pArray, false); - } diff --git a/clients/java/src/org/apache/commons/codec/binary/BinaryCodec.java b/clients/java/src/org/apache/commons/codec/binary/BinaryCodec.java deleted file mode 100644 index 663261a..0000000 --- a/clients/java/src/org/apache/commons/codec/binary/BinaryCodec.java +++ /dev/null @@ -1,285 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec.binary; -import org.apache.commons.codec.BinaryDecoder; -import org.apache.commons.codec.BinaryEncoder; -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.EncoderException; - * Translates between byte arrays and strings of "0"s and "1"s. - * @todo may want to add more bit vector functions like and/or/xor/nand - * @todo also might be good to generate boolean[] - * from byte[] et. cetera. - * @author Apache Software Foundation - * @since 1.3 - * @version $Id $ -public class BinaryCodec implements BinaryDecoder, BinaryEncoder { - /* - * tried to avoid using ArrayUtils to minimize dependencies while using these empty arrays - dep is just not worth - * it. - */ - /** Empty char array. */ - private static final char[] EMPTY_CHAR_ARRAY = new char[0]; - /** Empty byte array. */ - private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; - /** Mask for bit 0 of a byte. */ - private static final int BIT_0 = 1; - /** Mask for bit 1 of a byte. */ - private static final int BIT_1 = 0x02; - /** Mask for bit 2 of a byte. */ - private static final int BIT_2 = 0x04; - /** Mask for bit 3 of a byte. */ - private static final int BIT_3 = 0x08; - /** Mask for bit 4 of a byte. */ - private static final int BIT_4 = 0x10; - /** Mask for bit 5 of a byte. */ - private static final int BIT_5 = 0x20; - /** Mask for bit 6 of a byte. */ - private static final int BIT_6 = 0x40; - /** Mask for bit 7 of a byte. */ - private static final int BIT_7 = 0x80; - private static final int[] BITS = {BIT_0, BIT_1, BIT_2, BIT_3, BIT_4, BIT_5, BIT_6, BIT_7}; - /** - * Converts an array of raw binary data into an array of ascii 0 and 1 characters. - * - * @param raw - * the raw binary data to convert - * @return 0 and 1 ascii character bytes one for each bit of the argument - * @see org.apache.commons.codec.BinaryEncoder#encode(byte[]) - */ - public byte[] encode(byte[] raw) { - return toAsciiBytes(raw); - } - /** - * Converts an array of raw binary data into an array of ascii 0 and 1 chars. - * - * @param raw - * the raw binary data to convert - * @return 0 and 1 ascii character chars one for each bit of the argument - * @throws EncoderException - * if the argument is not a byte[] - * @see org.apache.commons.codec.Encoder#encode(java.lang.Object) - */ - public Object encode(Object raw) throws EncoderException { - if (!(raw instanceof byte[])) { - throw new EncoderException("argument not a byte array"); - } - return toAsciiChars((byte[]) raw); - } - /** - * Decodes a byte array where each byte represents an ascii '0' or '1'. - * - * @param ascii - * each byte represents an ascii '0' or '1' - * @return the raw encoded binary where each bit corresponds to a byte in the byte array argument - * @throws DecoderException - * if argument is not a byte[], char[] or String - * @see org.apache.commons.codec.Decoder#decode(java.lang.Object) - */ - public Object decode(Object ascii) throws DecoderException { - if (ascii == null) { - return EMPTY_BYTE_ARRAY; - } - if (ascii instanceof byte[]) { - return fromAscii((byte[]) ascii); - } - if (ascii instanceof char[]) { - return fromAscii((char[]) ascii); - } - if (ascii instanceof String) { - return fromAscii(((String) ascii).toCharArray()); - } - throw new DecoderException("argument not a byte array"); - } - /** - * Decodes a byte array where each byte represents an ascii '0' or '1'. - * - * @param ascii - * each byte represents an ascii '0' or '1' - * @return the raw encoded binary where each bit corresponds to a byte in the byte array argument - * @see org.apache.commons.codec.Decoder#decode(Object) - */ - public byte[] decode(byte[] ascii) { - return fromAscii(ascii); - } - /** - * Decodes a String where each char of the String represents an ascii '0' or '1'. - * - * @param ascii - * String of '0' and '1' characters - * @return the raw encoded binary where each bit corresponds to a byte in the byte array argument - * @see org.apache.commons.codec.Decoder#decode(Object) - */ - public byte[] toByteArray(String ascii) { - if (ascii == null) { - return EMPTY_BYTE_ARRAY; - } - return fromAscii(ascii.toCharArray()); - } - // ------------------------------------------------------------------------ - // - // static codec operations - // - // ------------------------------------------------------------------------ - /** - * Decodes a byte array where each char represents an ascii '0' or '1'. - * - * @param ascii - * each char represents an ascii '0' or '1' - * @return the raw encoded binary where each bit corresponds to a char in the char array argument - */ - public static byte[] fromAscii(char[] ascii) { - if (ascii == null || ascii.length == 0) { - return EMPTY_BYTE_ARRAY; - } - // get length/8 times bytes with 3 bit shifts to the right of the length - byte[] l_raw = new byte[ascii.length >> 3]; - /* - * We decr index jj by 8 as we go along to not recompute indices using multiplication every time inside the - * loop. - */ - for (int ii = 0, jj = ascii.length - 1; ii < l_raw.length; ii++, jj -= 8) { - for (int bits = 0; bits < BITS.length; ++bits) { - if (ascii[jj - bits] == '1') { - l_raw[ii] |= BITS[bits]; - } - } - } - return l_raw; - } - /** - * Decodes a byte array where each byte represents an ascii '0' or '1'. - * - * @param ascii - * each byte represents an ascii '0' or '1' - * @return the raw encoded binary where each bit corresponds to a byte in the byte array argument - */ - public static byte[] fromAscii(byte[] ascii) { - if (ascii == null || ascii.length == 0) { - return EMPTY_BYTE_ARRAY; - } - // get length/8 times bytes with 3 bit shifts to the right of the length - byte[] l_raw = new byte[ascii.length >> 3]; - /* - * We decr index jj by 8 as we go along to not recompute indices using multiplication every time inside the - * loop. - */ - for (int ii = 0, jj = ascii.length - 1; ii < l_raw.length; ii++, jj -= 8) { - for (int bits = 0; bits < BITS.length; ++bits) { - if (ascii[jj - bits] == '1') { - l_raw[ii] |= BITS[bits]; - } - } - } - return l_raw; - } - /** - * Converts an array of raw binary data into an array of ascii 0 and 1 character bytes - each byte is a truncated - * char. - * - * @param raw - * the raw binary data to convert - * @return an array of 0 and 1 character bytes for each bit of the argument - * @see org.apache.commons.codec.BinaryEncoder#encode(byte[]) - */ - public static byte[] toAsciiBytes(byte[] raw) { - if (raw == null || raw.length == 0) { - return EMPTY_BYTE_ARRAY; - } - // get 8 times the bytes with 3 bit shifts to the left of the length - byte[] l_ascii = new byte[raw.length << 3]; - /* - * We decr index jj by 8 as we go along to not recompute indices using multiplication every time inside the - * loop. - */ - for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) { - for (int bits = 0; bits < BITS.length; ++bits) { - if ((raw[ii] & BITS[bits]) == 0) { - l_ascii[jj - bits] = '0'; - } else { - l_ascii[jj - bits] = '1'; - } - } - } - return l_ascii; - } - /** - * Converts an array of raw binary data into an array of ascii 0 and 1 characters. - * - * @param raw - * the raw binary data to convert - * @return an array of 0 and 1 characters for each bit of the argument - * @see org.apache.commons.codec.BinaryEncoder#encode(byte[]) - */ - public static char[] toAsciiChars(byte[] raw) { - if (raw == null || raw.length == 0) { - return EMPTY_CHAR_ARRAY; - } - // get 8 times the bytes with 3 bit shifts to the left of the length - char[] l_ascii = new char[raw.length << 3]; - /* - * We decr index jj by 8 as we go along to not recompute indices using multiplication every time inside the - * loop. - */ - for (int ii = 0, jj = l_ascii.length - 1; ii < raw.length; ii++, jj -= 8) { - for (int bits = 0; bits < BITS.length; ++bits) { - if ((raw[ii] & BITS[bits]) == 0) { - l_ascii[jj - bits] = '0'; - } else { - l_ascii[jj - bits] = '1'; - } - } - } - return l_ascii; - } - /** - * Converts an array of raw binary data into a String of ascii 0 and 1 characters. - * - * @param raw - * the raw binary data to convert - * @return a String of 0 and 1 characters representing the binary data - * @see org.apache.commons.codec.BinaryEncoder#encode(byte[]) - */ - public static String toAsciiString(byte[] raw) { - return new String(toAsciiChars(raw)); - } diff --git a/clients/java/src/org/apache/commons/codec/binary/Hex.java b/clients/java/src/org/apache/commons/codec/binary/Hex.java deleted file mode 100644 index 85d41ff..0000000 --- a/clients/java/src/org/apache/commons/codec/binary/Hex.java +++ /dev/null @@ -1,192 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec.binary; -import org.apache.commons.codec.BinaryDecoder; -import org.apache.commons.codec.BinaryEncoder; -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.EncoderException; - * Hex encoder and decoder. - * @since 1.1 - * @author Apache Software Foundation - * @version $Id: Hex.java,v 1.13 2004/04/18 18:22:33 ggregory Exp $ -public class Hex implements BinaryEncoder, BinaryDecoder { - /** - * Used building output as Hex - */ - private static final char[] DIGITS = { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' - }; - /** - * Converts an array of characters representing hexidecimal values into an - * array of bytes of those same values. The returned array will be half the - * length of the passed array, as it takes two characters to represent any - * given byte. An exception is thrown if the passed char array has an odd - * number of elements. - * - * @param data An array of characters containing hexidecimal digits - * @return A byte array containing binary data decoded from - * the supplied char array. - * @throws DecoderException Thrown if an odd number or illegal of characters - * is supplied - */ - public static byte[] decodeHex(char[] data) throws DecoderException { - int len = data.length; - if ((len & 0x01) != 0) { - throw new DecoderException("Odd number of characters."); - } - byte[] out = new byte[len >> 1]; - // two characters form the hex value. - for (int i = 0, j = 0; j < len; i++) { - int f = toDigit(data[j], j) << 4; - j++; - f = f | toDigit(data[j], j); - j++; - out[i] = (byte) (f & 0xFF); - } - return out; - } - /** - * Converts a hexadecimal character to an integer. - * - * @param ch A character to convert to an integer digit - * @param index The index of the character in the source - * @return An integer - * @throws DecoderException Thrown if ch is an illegal hex character - */ - protected static int toDigit(char ch, int index) throws DecoderException { - int digit = Character.digit(ch, 16); - if (digit == -1) { - throw new DecoderException("Illegal hexadecimal charcter " + ch + " at index " + index); - } - return digit; - } - /** - * Converts an array of bytes into an array of characters representing the hexidecimal values of each byte in order. - * The returned array will be double the length of the passed array, as it takes two characters to represent any - * given byte. - * - * @param data - * a byte[] to convert to Hex characters - * @return A char[] containing hexidecimal characters - */ - public static char[] encodeHex(byte[] data) { - int l = data.length; - char[] out = new char[l << 1]; - // two characters form the hex value. - for (int i = 0, j = 0; i < l; i++) { - out[j++] = DIGITS[(0xF0 & data[i]) >>> 4 ]; - out[j++] = DIGITS[ 0x0F & data[i] ]; - } - return out; - } - /** - * Converts an array of character bytes representing hexidecimal values into an - * array of bytes of those same values. The returned array will be half the - * length of the passed array, as it takes two characters to represent any - * given byte. An exception is thrown if the passed char array has an odd - * number of elements. - * - * @param array An array of character bytes containing hexidecimal digits - * @return A byte array containing binary data decoded from - * the supplied byte array (representing characters). - * @throws DecoderException Thrown if an odd number of characters is supplied - * to this function - * @see #decodeHex(char[]) - */ - public byte[] decode(byte[] array) throws DecoderException { - return decodeHex(new String(array).toCharArray()); - /** - * Converts a String or an array of character bytes representing hexidecimal values into an - * array of bytes of those same values. The returned array will be half the - * length of the passed String or array, as it takes two characters to represent any - * given byte. An exception is thrown if the passed char array has an odd - * number of elements. - * - * @param object A String or, an array of character bytes containing hexidecimal digits - * @return A byte array containing binary data decoded from - * the supplied byte array (representing characters). - * @throws DecoderException Thrown if an odd number of characters is supplied - * to this function or the object is not a String or char[] - * @see #decodeHex(char[]) - */ - public Object decode(Object object) throws DecoderException { - try { - char[] charArray = object instanceof String ? ((String) object).toCharArray() : (char[]) object; - return decodeHex(charArray); - } catch (ClassCastException e) { - throw new DecoderException(e.getMessage()); - /** - * Converts an array of bytes into an array of bytes for the characters representing the - * hexidecimal values of each byte in order. The returned array will be - * double the length of the passed array, as it takes two characters to - * represent any given byte. - * - * @param array a byte[] to convert to Hex characters - * @return A byte[] containing the bytes of the hexidecimal characters - * @see #encodeHex(byte[]) - */ - public byte[] encode(byte[] array) { - return new String(encodeHex(array)).getBytes(); - /** - * Converts a String or an array of bytes into an array of characters representing the - * hexidecimal values of each byte in order. The returned array will be - * double the length of the passed String or array, as it takes two characters to - * represent any given byte. - * - * @param object a String, or byte[] to convert to Hex characters - * @return A char[] containing hexidecimal characters - * @throws EncoderException Thrown if the given object is not a String or byte[] - * @see #encodeHex(byte[]) - */ - public Object encode(Object object) throws EncoderException { - try { - byte[] byteArray = object instanceof String ? ((String) object).getBytes() : (byte[]) object; - return encodeHex(byteArray); - } catch (ClassCastException e) { - throw new EncoderException(e.getMessage()); diff --git a/clients/java/src/org/apache/commons/codec/binary/package.html b/clients/java/src/org/apache/commons/codec/binary/package.html deleted file mode 100644 index 71b63cd..0000000 --- a/clients/java/src/org/apache/commons/codec/binary/package.html +++ /dev/null @@ -1,20 +0,0 @@ - Base64, Binary, and Hexadecimal String encoding and decoding. diff --git a/clients/java/src/org/apache/commons/codec/digest/DigestUtils.java b/clients/java/src/org/apache/commons/codec/digest/DigestUtils.java deleted file mode 100644 index 57852e6..0000000 --- a/clients/java/src/org/apache/commons/codec/digest/DigestUtils.java +++ /dev/null @@ -1,153 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec.digest; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import org.apache.commons.codec.binary.Hex; - * Operations to simplifiy common {@link java.security.MessageDigest} tasks. This - * class is thread safe. - * @author Apache Software Foundation -public class DigestUtils { - /** - * Returns a MessageDigest for the given
algorithm
.
- *
- * @param algorithm The MessageDigest algorithm name.
- * @return An MD5 digest instance.
- * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
- */
- static MessageDigest getDigest(String algorithm) {
- try {
- return MessageDigest.getInstance(algorithm);
- } catch (NoSuchAlgorithmException e) {
- throw new RuntimeException(e.getMessage());
- }
- }
- /**
- * Returns an MD5 MessageDigest.
- *
- * @return An MD5 digest instance.
- * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
- */
- private static MessageDigest getMd5Digest() {
- return getDigest("MD5");
- }
- /**
- * Returns an SHA digest.
- *
- * @return An SHA digest instance.
- * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
- */
- private static MessageDigest getShaDigest() {
- return getDigest("SHA");
- }
- /**
- * Calculates the MD5 digest and returns the value as a 16 element
- *
byte[]
.
- *
- * @param data Data to digest
- * @return MD5 digest
- */
- public static byte[] md5(byte[] data) {
- return getMd5Digest().digest(data);
- }
- /**
- * Calculates the MD5 digest and returns the value as a 16 element
- *
byte[]
.
- *
- * @param data Data to digest
- * @return MD5 digest
- */
- public static byte[] md5(String data) {
- return md5(data.getBytes());
- }
- /**
- * Calculates the MD5 digest and returns the value as a 32 character
- * hex string.
- *
- * @param data Data to digest
- * @return MD5 digest as a hex string
- */
- public static String md5Hex(byte[] data) {
- return new String(Hex.encodeHex(md5(data)));
- }
- /**
- * Calculates the MD5 digest and returns the value as a 32 character
- * hex string.
- *
- * @param data Data to digest
- * @return MD5 digest as a hex string
- */
- public static String md5Hex(String data) {
- return new String(Hex.encodeHex(md5(data)));
- }
- /**
- * Calculates the SHA digest and returns the value as a
- *
byte[]
.
- *
- * @param data Data to digest
- * @return SHA digest
- */
- public static byte[] sha(byte[] data) {
- return getShaDigest().digest(data);
- }
- /**
- * Calculates the SHA digest and returns the value as a
- *
byte[]
.
- *
- * @param data Data to digest
- * @return SHA digest
- */
- public static byte[] sha(String data) {
- return sha(data.getBytes());
- }
- /**
- * Calculates the SHA digest and returns the value as a hex string.
- *
- * @param data Data to digest
- * @return SHA digest as a hex string
- */
- public static String shaHex(byte[] data) {
- return new String(Hex.encodeHex(sha(data)));
- }
- /**
- * Calculates the SHA digest and returns the value as a hex string.
- *
- * @param data Data to digest
- * @return SHA digest as a hex string
- */
- public static String shaHex(String data) {
- return new String(Hex.encodeHex(sha(data)));
- }
diff --git a/clients/java/src/org/apache/commons/codec/digest/package.html b/clients/java/src/org/apache/commons/codec/digest/package.html
deleted file mode 100644
index ea5cfbc..0000000
--- a/clients/java/src/org/apache/commons/codec/digest/package.html
+++ /dev/null
@@ -1,20 +0,0 @@
- Operations to simplifiy common
MessageDigest
tasks.
diff --git a/clients/java/src/org/apache/commons/codec/language/DoubleMetaphone.java b/clients/java/src/org/apache/commons/codec/language/DoubleMetaphone.java
deleted file mode 100644
index e5a0b8d..0000000
--- a/clients/java/src/org/apache/commons/codec/language/DoubleMetaphone.java
+++ /dev/null
@@ -1,1103 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.language;
-import org.apache.commons.codec.EncoderException;
-import org.apache.commons.codec.StringEncoder;
- * Encodes a string into a double metaphone value.
- * This Implementation is based on the algorithm by
Lawrence Philips
.
- *
obj
is a
String
(like
Metaphone
).
- *
- * @param obj Object to encode (should be of type String)
- * @return An encoded Object (will be of type String)
- * @throws EncoderException encode parameter is not of type String
- */
- public Object encode(Object obj) throws EncoderException {
- if (!(obj instanceof String)) {
- throw new EncoderException("DoubleMetaphone encode parameter is not of type String");
- }
- return doubleMetaphone((String) obj);
- }
- /**
- * Encode the value using DoubleMetaphone.
- *
- * @param value String to encode
- * @return An encoded String
- */
- public String encode(String value) {
- return doubleMetaphone(value);
- }
- /**
- * Check if the Double Metaphone values of two
String
values
- * are equal.
- *
- * @param value1 The left-hand side of the encoded {@link String#equals(Object)}.
- * @param value2 The right-hand side of the encoded {@link String#equals(Object)}.
- * @return
true
if the encoded
String
s are equal;
- *
false
otherwise.
- * @see #isDoubleMetaphoneEqual(String,String,boolean)
- */
- public boolean isDoubleMetaphoneEqual(String value1, String value2) {
- return isDoubleMetaphoneEqual(value1, value2, false);
- }
- /**
- * Check if the Double Metaphone values of two
String
values
- * are equal, optionally using the alternate value.
- *
- * @param value1 The left-hand side of the encoded {@link String#equals(Object)}.
- * @param value2 The right-hand side of the encoded {@link String#equals(Object)}.
- * @param alternate use the alternate value if
true
.
- * @return
true
if the encoded
String
s are equal;
- *
false
otherwise.
- */
- public boolean isDoubleMetaphoneEqual(String value1,
- String value2,
- boolean alternate) {
- return doubleMetaphone(value1, alternate).equals(doubleMetaphone
- (value2, alternate));
- }
- /**
- * Returns the maxCodeLen.
- * @return int
- */
- public int getMaxCodeLen() {
- return this.maxCodeLen;
- }
- /**
- * Sets the maxCodeLen.
- * @param maxCodeLen The maxCodeLen to set
- */
- public void setMaxCodeLen(int maxCodeLen) {
- this.maxCodeLen = maxCodeLen;
- }
- //-- BEGIN HANDLERS --//
- /**
- * Handles 'A', 'E', 'I', 'O', 'U', and 'Y' cases
- */
- private int handleAEIOUY(String value, DoubleMetaphoneResult result, int
- index) {
- if (index == 0) {
- result.append('A');
- }
- return index + 1;
- }
- /**
- * Handles 'C' cases
- */
- private int handleC(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (conditionC0(value, index)) { // very confusing, moved out
- result.append('K');
- index += 2;
- } else if (index == 0 && contains(value, index, 6, "CAESAR")) {
- result.append('S');
- index += 2;
- } else if (contains(value, index, 2, "CH")) {
- index = handleCH(value, result, index);
- } else if (contains(value, index, 2, "CZ") &&
- !contains(value, index - 2, 4, "WICZ")) {
- //-- "Czerny" --//
- result.append('S', 'X');
- index += 2;
- } else if (contains(value, index + 1, 3, "CIA")) {
- //-- "focaccia" --//
- result.append('X');
- index += 3;
- } else if (contains(value, index, 2, "CC") &&
- !(index == 1 && charAt(value, 0) == 'M')) {
- //-- double "cc" but not "McClelland" --//
- return handleCC(value, result, index);
- } else if (contains(value, index, 2, "CK", "CG", "CQ")) {
- result.append('K');
- index += 2;
- } else if (contains(value, index, 2, "CI", "CE", "CY")) {
- //-- Italian vs. English --//
- if (contains(value, index, 3, "CIO", "CIE", "CIA")) {
- result.append('S', 'X');
- } else {
- result.append('S');
- }
- index += 2;
- } else {
- result.append('K');
- if (contains(value, index + 1, 2, " C", " Q", " G")) {
- //-- Mac Caffrey, Mac Gregor --//
- index += 3;
- } else if (contains(value, index + 1, 1, "C", "K", "Q") &&
- !contains(value, index + 1, 2, "CE", "CI")) {
- index += 2;
- } else {
- index++;
- }
- }
- return index;
- }
- /**
- * Handles 'CC' cases
- */
- private int handleCC(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (contains(value, index + 2, 1, "I", "E", "H") &&
- !contains(value, index + 2, 2, "HU")) {
- //-- "bellocchio" but not "bacchus" --//
- if ((index == 1 && charAt(value, index - 1) == 'A') ||
- contains(value, index - 1, 5, "UCCEE", "UCCES")) {
- //-- "accident", "accede", "succeed" --//
- result.append("KS");
- } else {
- //-- "bacci", "bertucci", other Italian --//
- result.append('X');
- }
- index += 3;
- } else { // Pierce's rule
- result.append('K');
- index += 2;
- }
- return index;
- }
- /**
- * Handles 'CH' cases
- */
- private int handleCH(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (index > 0 && contains(value, index, 4, "CHAE")) { // Michael
- result.append('K', 'X');
- return index + 2;
- } else if (conditionCH0(value, index)) {
- //-- Greek roots ("chemistry", "chorus", etc.) --//
- result.append('K');
- return index + 2;
- } else if (conditionCH1(value, index)) {
- //-- Germanic, Greek, or otherwise 'ch' for 'kh' sound --//
- result.append('K');
- return index + 2;
- } else {
- if (index > 0) {
- if (contains(value, 0, 2, "MC")) {
- result.append('K');
- } else {
- result.append('X', 'K');
- }
- } else {
- result.append('X');
- }
- return index + 2;
- }
- }
- /**
- * Handles 'D' cases
- */
- private int handleD(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (contains(value, index, 2, "DG")) {
- //-- "Edge" --//
- if (contains(value, index + 2, 1, "I", "E", "Y")) {
- result.append('J');
- index += 3;
- //-- "Edgar" --//
- } else {
- result.append("TK");
- index += 2;
- }
- } else if (contains(value, index, 2, "DT", "DD")) {
- result.append('T');
- index += 2;
- } else {
- result.append('T');
- index++;
- }
- return index;
- }
- /**
- * Handles 'G' cases
- */
- private int handleG(String value,
- DoubleMetaphoneResult result,
- int index,
- boolean slavoGermanic) {
- if (charAt(value, index + 1) == 'H') {
- index = handleGH(value, result, index);
- } else if (charAt(value, index + 1) == 'N') {
- if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) {
- result.append("KN", "N");
- } else if (!contains(value, index + 2, 2, "EY") &&
- charAt(value, index + 1) != 'Y' && !slavoGermanic) {
- result.append("N", "KN");
- } else {
- result.append("KN");
- }
- index = index + 2;
- } else if (contains(value, index + 1, 2, "LI") && !slavoGermanic) {
- result.append("KL", "L");
- index += 2;
- } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) {
- //-- -ges-, -gep-, -gel-, -gie- at beginning --//
- result.append('K', 'J');
- index += 2;
- } else if ((contains(value, index + 1, 2, "ER") ||
- charAt(value, index + 1) == 'Y') &&
- !contains(value, 0, 6, "DANGER", "RANGER", "MANGER") &&
- !contains(value, index - 1, 1, "E", "I") &&
- !contains(value, index - 1, 3, "RGY", "OGY")) {
- //-- -ger-, -gy- --//
- result.append('K', 'J');
- index += 2;
- } else if (contains(value, index + 1, 1, "E", "I", "Y") ||
- contains(value, index - 1, 4, "AGGI", "OGGI")) {
- //-- Italian "biaggi" --//
- if ((contains(value, 0 ,4, "VAN ", "VON ") || contains(value, 0, 3, "SCH")) || contains(value, index + 1, 2, "ET")) {
- //-- obvious germanic --//
- result.append('K');
- } else if (contains(value, index + 1, 4, "IER")) {
- result.append('J');
- } else {
- result.append('J', 'K');
- }
- index += 2;
- } else if (charAt(value, index + 1) == 'G') {
- index += 2;
- result.append('K');
- } else {
- index++;
- result.append('K');
- }
- return index;
- }
- /**
- * Handles 'GH' cases
- */
- private int handleGH(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (index > 0 && !isVowel(charAt(value, index - 1))) {
- result.append('K');
- index += 2;
- } else if (index == 0) {
- if (charAt(value, index + 2) == 'I') {
- result.append('J');
- } else {
- result.append('K');
- }
- index += 2;
- } else if ((index > 1 && contains(value, index - 2, 1, "B", "H", "D")) ||
- (index > 2 && contains(value, index - 3, 1, "B", "H", "D")) ||
- (index > 3 && contains(value, index - 4, 1, "B", "H"))) {
- //-- Parker's rule (with some further refinements) - "hugh"
- index += 2;
- } else {
- if (index > 2 && charAt(value, index - 1) == 'U' &&
- contains(value, index - 3, 1, "C", "G", "L", "R", "T")) {
- //-- "laugh", "McLaughlin", "cough", "gough", "rough", "tough"
- result.append('F');
- } else if (index > 0 && charAt(value, index - 1) != 'I') {
- result.append('K');
- }
- index += 2;
- }
- return index;
- }
- /**
- * Handles 'H' cases
- */
- private int handleH(String value,
- DoubleMetaphoneResult result,
- int index) {
- //-- only keep if first & before vowel or between 2 vowels --//
- if ((index == 0 || isVowel(charAt(value, index - 1))) &&
- isVowel(charAt(value, index + 1))) {
- result.append('H');
- index += 2;
- //-- also takes car of "HH" --//
- } else {
- index++;
- }
- return index;
- }
- /**
- * Handles 'J' cases
- */
- private int handleJ(String value, DoubleMetaphoneResult result, int index,
- boolean slavoGermanic) {
- if (contains(value, index, 4, "JOSE") || contains(value, 0, 4, "SAN ")) {
- //-- obvious Spanish, "Jose", "San Jacinto" --//
- if ((index == 0 && (charAt(value, index + 4) == ' ') ||
- value.length() == 4) || contains(value, 0, 4, "SAN ")) {
- result.append('H');
- } else {
- result.append('J', 'H');
- }
- index++;
- } else {
- if (index == 0 && !contains(value, index, 4, "JOSE")) {
- result.append('J', 'A');
- } else if (isVowel(charAt(value, index - 1)) && !slavoGermanic &&
- (charAt(value, index + 1) == 'A' || charAt(value, index + 1) == 'O')) {
- result.append('J', 'H');
- } else if (index == value.length() - 1) {
- result.append('J', ' ');
- } else if (!contains(value, index + 1, 1, L_T_K_S_N_M_B_Z) && !contains(value, index - 1, 1, "S", "K", "L")) {
- result.append('J');
- }
- if (charAt(value, index + 1) == 'J') {
- index += 2;
- } else {
- index++;
- }
- }
- return index;
- }
- /**
- * Handles 'L' cases
- */
- private int handleL(String value,
- DoubleMetaphoneResult result,
- int index) {
- result.append('L');
- if (charAt(value, index + 1) == 'L') {
- if (conditionL0(value, index)) {
- result.appendAlternate(' ');
- }
- index += 2;
- } else {
- index++;
- }
- return index;
- }
- /**
- * Handles 'P' cases
- */
- private int handleP(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (charAt(value, index + 1) == 'H') {
- result.append('F');
- index += 2;
- } else {
- result.append('P');
- index = contains(value, index + 1, 1, "P", "B") ? index + 2 : index + 1;
- }
- return index;
- }
- /**
- * Handles 'R' cases
- */
- private int handleR(String value,
- DoubleMetaphoneResult result,
- int index,
- boolean slavoGermanic) {
- if (index == value.length() - 1 && !slavoGermanic &&
- contains(value, index - 2, 2, "IE") &&
- !contains(value, index - 4, 2, "ME", "MA")) {
- result.appendAlternate('R');
- } else {
- result.append('R');
- }
- return charAt(value, index + 1) == 'R' ? index + 2 : index + 1;
- }
- /**
- * Handles 'S' cases
- */
- private int handleS(String value,
- DoubleMetaphoneResult result,
- int index,
- boolean slavoGermanic) {
- if (contains(value, index - 1, 3, "ISL", "YSL")) {
- //-- special cases "island", "isle", "carlisle", "carlysle" --//
- index++;
- } else if (index == 0 && contains(value, index, 5, "SUGAR")) {
- //-- special case "sugar-" --//
- result.append('X', 'S');
- index++;
- } else if (contains(value, index, 2, "SH")) {
- if (contains(value, index + 1, 4,
- "HEIM", "HOEK", "HOLM", "HOLZ")) {
- //-- germanic --//
- result.append('S');
- } else {
- result.append('X');
- }
- index += 2;
- } else if (contains(value, index, 3, "SIO", "SIA") || contains(value, index, 4, "SIAN")) {
- //-- Italian and Armenian --//
- if (slavoGermanic) {
- result.append('S');
- } else {
- result.append('S', 'X');
- }
- index += 3;
- } else if ((index == 0 && contains(value, index + 1, 1, "M", "N", "L", "W")) || contains(value, index + 1, 1, "Z")) {
- //-- german & anglicisations, e.g. "smith" match "schmidt" //
- // "snider" match "schneider" --//
- //-- also, -sz- in slavic language altho in hungarian it //
- // is pronounced "s" --//
- result.append('S', 'X');
- index = contains(value, index + 1, 1, "Z") ? index + 2 : index + 1;
- } else if (contains(value, index, 2, "SC")) {
- index = handleSC(value, result, index);
- } else {
- if (index == value.length() - 1 && contains(value, index - 2,
- 2, "AI", "OI")){
- //-- french e.g. "resnais", "artois" --//
- result.appendAlternate('S');
- } else {
- result.append('S');
- }
- index = contains(value, index + 1, 1, "S", "Z") ? index + 2 : index + 1;
- }
- return index;
- }
- /**
- * Handles 'SC' cases
- */
- private int handleSC(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (charAt(value, index + 2) == 'H') {
- //-- Schlesinger's rule --//
- if (contains(value, index + 3,
- 2, "OO", "ER", "EN", "UY", "ED", "EM")) {
- //-- Dutch origin, e.g. "school", "schooner" --//
- if (contains(value, index + 3, 2, "ER", "EN")) {
- //-- "schermerhorn", "schenker" --//
- result.append("X", "SK");
- } else {
- result.append("SK");
- }
- } else {
- if (index == 0 && !isVowel(charAt(value, 3)) && charAt(value, 3) != 'W') {
- result.append('X', 'S');
- } else {
- result.append('X');
- }
- }
- } else if (contains(value, index + 2, 1, "I", "E", "Y")) {
- result.append('S');
- } else {
- result.append("SK");
- }
- return index + 3;
- }
- /**
- * Handles 'T' cases
- */
- private int handleT(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (contains(value, index, 4, "TION")) {
- result.append('X');
- index += 3;
- } else if (contains(value, index, 3, "TIA", "TCH")) {
- result.append('X');
- index += 3;
- } else if (contains(value, index, 2, "TH") || contains(value, index,
- 3, "TTH")) {
- if (contains(value, index + 2, 2, "OM", "AM") ||
- //-- special case "thomas", "thames" or germanic --//
- contains(value, 0, 4, "VAN ", "VON ") ||
- contains(value, 0, 3, "SCH")) {
- result.append('T');
- } else {
- result.append('0', 'T');
- }
- index += 2;
- } else {
- result.append('T');
- index = contains(value, index + 1, 1, "T", "D") ? index + 2 : index + 1;
- }
- return index;
- }
- /**
- * Handles 'W' cases
- */
- private int handleW(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (contains(value, index, 2, "WR")) {
- //-- can also be in middle of word --//
- result.append('R');
- index += 2;
- } else {
- if (index == 0 && (isVowel(charAt(value, index + 1)) ||
- contains(value, index, 2, "WH"))) {
- if (isVowel(charAt(value, index + 1))) {
- //-- Wasserman should match Vasserman --//
- result.append('A', 'F');
- } else {
- //-- need Uomo to match Womo --//
- result.append('A');
- }
- index++;
- } else if ((index == value.length() - 1 && isVowel(charAt(value, index - 1))) ||
- contains(value, index - 1,
- 5, "EWSKI", "EWSKY", "OWSKI", "OWSKY") ||
- contains(value, 0, 3, "SCH")) {
- //-- Arnow should match Arnoff --//
- result.appendAlternate('F');
- index++;
- } else if (contains(value, index, 4, "WICZ", "WITZ")) {
- //-- Polish e.g. "filipowicz" --//
- result.append("TS", "FX");
- index += 4;
- } else {
- index++;
- }
- }
- return index;
- }
- /**
- * Handles 'X' cases
- */
- private int handleX(String value,
- DoubleMetaphoneResult result,
- int index) {
- if (index == 0) {
- result.append('S');
- index++;
- } else {
- if (!((index == value.length() - 1) &&
- (contains(value, index - 3, 3, "IAU", "EAU") ||
- contains(value, index - 2, 2, "AU", "OU")))) {
- //-- French e.g. breaux --//
- result.append("KS");
- }
- index = contains(value, index + 1, 1, "C", "X") ? index + 2 : index + 1;
- }
- return index;
- }
- /**
- * Handles 'Z' cases
- */
- private int handleZ(String value, DoubleMetaphoneResult result, int index,
- boolean slavoGermanic) {
- if (charAt(value, index + 1) == 'H') {
- //-- Chinese pinyin e.g. "zhao" or Angelina "Zhang" --//
- result.append('J');
- index += 2;
- } else {
- if (contains(value, index + 1, 2, "ZO", "ZI", "ZA") || (slavoGermanic && (index > 0 && charAt(value, index - 1) != 'T'))) {
- result.append("S", "TS");
- } else {
- result.append('S');
- }
- index = charAt(value, index + 1) == 'Z' ? index + 2 : index + 1;
- }
- return index;
- }
- //-- BEGIN CONDITIONS --//
- /**
- * Complex condition 0 for 'C'
- */
- private boolean conditionC0(String value, int index) {
- if (contains(value, index, 4, "CHIA")) {
- return true;
- } else if (index <= 1) {
- return false;
- } else if (isVowel(charAt(value, index - 2))) {
- return false;
- } else if (!contains(value, index - 1, 3, "ACH")) {
- return false;
- } else {
- char c = charAt(value, index + 2);
- return (c != 'I' && c != 'E')
- || contains(value, index - 2, 6, "BACHER", "MACHER");
- /**
- * Complex condition 0 for 'CH'
- */
- private boolean conditionCH0(String value, int index) {
- if (index != 0) {
- return false;
- } else if (!contains(value, index + 1, 5, "HARAC", "HARIS") &&
- !contains(value, index + 1, 3, "HOR", "HYM", "HIA", "HEM")) {
- return false;
- } else if (contains(value, 0, 5, "CHORE")) {
- return false;
- } else {
- return true;
- }
- }
- /**
- * Complex condition 1 for 'CH'
- */
- private boolean conditionCH1(String value, int index) {
- return ((contains(value, 0, 4, "VAN ", "VON ") || contains(value, 0,
- 3, "SCH")) ||
- contains(value, index - 2, 6, "ORCHES", "ARCHIT", "ORCHID") ||
- contains(value, index + 2, 1, "T", "S") ||
- ((contains(value, index - 1, 1, "A", "O", "U", "E") || index == 0) &&
- (contains(value, index + 2, 1, L_R_N_M_B_H_F_V_W_SPACE) || index + 1 == value.length() - 1)));
- }
- /**
- * Complex condition 0 for 'L'
- */
- private boolean conditionL0(String value, int index) {
- if (index == value.length() - 3 &&
- contains(value, index - 1, 4, "ILLO", "ILLA", "ALLE")) {
- return true;
- } else if ((contains(value, index - 1, 2, "AS", "OS") ||
- contains(value, value.length() - 1, 1, "A", "O")) &&
- contains(value, index - 1, 4, "ALLE")) {
- return true;
- } else {
- return false;
- }
- }
- /**
- * Complex condition 0 for 'M'
- */
- private boolean conditionM0(String value, int index) {
- if (charAt(value, index + 1) == 'M') {
- return true;
- return contains(value, index - 1, 3, "UMB")
- && ((index + 1) == value.length() - 1 || contains(value,
- index + 2, 2, "ER"));
- //-- BEGIN HELPER FUNCTIONS --//
- /**
- * Determines whether or not a value is of slavo-germanic orgin. A value is
- * of slavo-germanic origin if it contians any of 'W', 'K', 'CZ', or 'WITZ'.
- */
- private boolean isSlavoGermanic(String value) {
- return value.indexOf('W') > -1 || value.indexOf('K') > -1 ||
- value.indexOf("CZ") > -1 || value.indexOf("WITZ") > -1;
- }
- /**
- * Determines whether or not a character is a vowel or not
- */
- private boolean isVowel(char ch) {
- return VOWELS.indexOf(ch) != -1;
- }
- /**
- * Determines whether or not the value starts with a silent letter. It will
- * return
true
if the value starts with any of 'GN', 'KN',
- * 'PN', 'WR' or 'PS'.
- */
- private boolean isSilentStart(String value) {
- boolean result = false;
- for (int i = 0; i < SILENT_START.length; i++) {
- if (value.startsWith(SILENT_START[i])) {
- result = true;
- break;
- }
- }
- return result;
- }
- /**
- * Cleans the input
- */
- private String cleanInput(String input) {
- if (input == null) {
- return null;
- input = input.trim();
- if (input.length() == 0) {
- return null;
- return input.toUpperCase();
- /**
- * Gets the character at index
index
if available, otherwise
- * it returns
Character.MIN_VALUE
so that there is some sort
- * of a default
- */
- protected char charAt(String value, int index) {
- if (index < 0 || index >= value.length()) {
- return Character.MIN_VALUE;
- }
- return value.charAt(index);
- }
- /**
- * Shortcut method with 1 criteria
- */
- private static boolean contains(String value, int start, int length,
- String criteria) {
- return contains(value, start, length,
- new String[] { criteria });
- }
- /**
- * Shortcut method with 2 criteria
- */
- private static boolean contains(String value, int start, int length,
- String criteria1, String criteria2) {
- return contains(value, start, length,
- new String[] { criteria1, criteria2 });
- }
- /**
- * Shortcut method with 3 criteria
- */
- private static boolean contains(String value, int start, int length,
- String criteria1, String criteria2,
- String criteria3) {
- return contains(value, start, length,
- new String[] { criteria1, criteria2, criteria3 });
- }
- /**
- * Shortcut method with 4 criteria
- */
- private static boolean contains(String value, int start, int length,
- String criteria1, String criteria2,
- String criteria3, String criteria4) {
- return contains(value, start, length,
- new String[] { criteria1, criteria2, criteria3,
- criteria4 });
- }
- /**
- * Shortcut method with 5 criteria
- */
- private static boolean contains(String value, int start, int length,
- String criteria1, String criteria2,
- String criteria3, String criteria4,
- String criteria5) {
- return contains(value, start, length,
- new String[] { criteria1, criteria2, criteria3,
- criteria4, criteria5 });
- }
- /**
- * Shortcut method with 6 criteria
- */
- private static boolean contains(String value, int start, int length,
- String criteria1, String criteria2,
- String criteria3, String criteria4,
- String criteria5, String criteria6) {
- return contains(value, start, length,
- new String[] { criteria1, criteria2, criteria3,
- criteria4, criteria5, criteria6 });
- }
- /**
- * Determines whether
value
contains any of the criteria
- starting
- * at index
start
and matching up to length
length
- */
- protected static boolean contains(String value, int start, int length,
- String[] criteria) {
- boolean result = false;
- if (start >= 0 && start + length <= value.length()) {
- String target = value.substring(start, start + length);
- for (int i = 0; i < criteria.length; i++) {
- if (target.equals(criteria[i])) {
- result = true;
- break;
- }
- }
- }
- return result;
- }
- //-- BEGIN INNER CLASSES --//
- /**
- * Inner class for storing results, since there is the optional alternate
- * encoding.
- */
- public class DoubleMetaphoneResult {
- private StringBuffer primary = new StringBuffer(getMaxCodeLen());
- private StringBuffer alternate = new StringBuffer(getMaxCodeLen());
- private int maxLength;
- public DoubleMetaphoneResult(int maxLength) {
- this.maxLength = maxLength;
- }
- public void append(char value) {
- appendPrimary(value);
- appendAlternate(value);
- }
- public void append(char primary, char alternate) {
- appendPrimary(primary);
- appendAlternate(alternate);
- }
- public void appendPrimary(char value) {
- if (this.primary.length() < this.maxLength) {
- this.primary.append(value);
- }
- }
- public void appendAlternate(char value) {
- if (this.alternate.length() < this.maxLength) {
- this.alternate.append(value);
- }
- }
- public void append(String value) {
- appendPrimary(value);
- appendAlternate(value);
- }
- public void append(String primary, String alternate) {
- appendPrimary(primary);
- appendAlternate(alternate);
- }
- public void appendPrimary(String value) {
- int addChars = this.maxLength - this.primary.length();
- if (value.length() <= addChars) {
- this.primary.append(value);
- } else {
- this.primary.append(value.substring(0, addChars));
- }
- }
- public void appendAlternate(String value) {
- int addChars = this.maxLength - this.alternate.length();
- if (value.length() <= addChars) {
- this.alternate.append(value);
- } else {
- this.alternate.append(value.substring(0, addChars));
- }
- }
- public String getPrimary() {
- return this.primary.toString();
- }
- public String getAlternate() {
- return this.alternate.toString();
- }
- public boolean isComplete() {
- return this.primary.length() >= this.maxLength &&
- this.alternate.length() >= this.maxLength;
- }
- }
diff --git a/clients/java/src/org/apache/commons/codec/language/Metaphone.java b/clients/java/src/org/apache/commons/codec/language/Metaphone.java
deleted file mode 100644
index dd9cbda..0000000
--- a/clients/java/src/org/apache/commons/codec/language/Metaphone.java
+++ /dev/null
@@ -1,399 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.language;
-import org.apache.commons.codec.EncoderException;
-import org.apache.commons.codec.StringEncoder;
- * Encodes a string into a metaphone value.
- * Initial Java implementation by
William B. Brogden. December, 1997
.
- * Permission given by
wbrogden
for code to be used anywhere.
- *
Hanging on the Metaphone
by
Lawrence Philips
in
Computer Language of Dec. 1990, p
- * 39.
- * @author Apache Software Foundation
- * @version $Id: Metaphone.java,v 1.20 2004/06/05 18:32:04 ggregory Exp $
-public class Metaphone implements StringEncoder {
- /**
- * Five values in the English language
- */
- private String vowels = "AEIOU" ;
- /**
- * Variable used in Metaphone algorithm
- */
- private String frontv = "EIY" ;
- /**
- * Variable used in Metaphone algorithm
- */
- private String varson = "CSPTG" ;
- /**
- * The max code length for metaphone is 4
- */
- private int maxCodeLen = 4 ;
- /**
- * Creates an instance of the Metaphone encoder
- */
- public Metaphone() {
- super();
- }
- /**
- * Find the metaphone value of a String. This is similar to the
- * soundex algorithm, but better at finding similar sounding words.
- * All input is converted to upper case.
- * Limitations: Input format is expected to be a single ASCII word
- * with only characters in the A - Z range, no punctuation or numbers.
- *
- * @param txt String to find the metaphone code for
- * @return A metaphone code corresponding to the String supplied
- */
- public String metaphone(String txt) {
- boolean hard = false ;
- if ((txt == null) || (txt.length() == 0)) {
- return "" ;
- }
- // single character is itself
- if (txt.length() == 1) {
- return txt.toUpperCase() ;
- }
- char[] inwd = txt.toUpperCase().toCharArray() ;
- StringBuffer local = new StringBuffer(40); // manipulate
- StringBuffer code = new StringBuffer(10) ; // output
- // handle initial 2 characters exceptions
- switch(inwd[0]) {
- case 'K' :
- case 'G' :
- case 'P' : /* looking for KN, etc*/
- if (inwd[1] == 'N') {
- local.append(inwd, 1, inwd.length - 1);
- } else {
- local.append(inwd);
- }
- break;
- case 'A': /* looking for AE */
- if (inwd[1] == 'E') {
- local.append(inwd, 1, inwd.length - 1);
- } else {
- local.append(inwd);
- }
- break;
- case 'W' : /* looking for WR or WH */
- if (inwd[1] == 'R') { // WR -> R
- local.append(inwd, 1, inwd.length - 1);
- break ;
- }
- if (inwd[1] == 'H') {
- local.append(inwd, 1, inwd.length - 1);
- local.setCharAt(0, 'W'); // WH -> W
- } else {
- local.append(inwd);
- }
- break;
- case 'X' : /* initial X becomes S */
- inwd[0] = 'S';
- local.append(inwd);
- break ;
- default :
- local.append(inwd);
- } // now local has working string with initials fixed
- int wdsz = local.length();
- int n = 0 ;
- while ((code.length() < this.getMaxCodeLen()) &&
- (n < wdsz) ) { // max code size of 4 works well
- char symb = local.charAt(n) ;
- // remove duplicate letters except C
- if ((symb != 'C') && (isPreviousChar( local, n, symb )) ) {
- n++ ;
- } else { // not dup
- switch(symb) {
- case 'A' : case 'E' : case 'I' : case 'O' : case 'U' :
- if (n == 0) {
- code.append(symb);
- }
- break ; // only use vowel if leading char
- case 'B' :
- if ( isPreviousChar(local, n, 'M') &&
- isLastChar(wdsz, n) ) { // B is silent if word ends in MB
- break;
- }
- code.append(symb);
- break;
- case 'C' : // lots of C special cases
- /* discard if SCI, SCE or SCY */
- if ( isPreviousChar(local, n, 'S') &&
- !isLastChar(wdsz, n) &&
- (this.frontv.indexOf(local.charAt(n + 1)) >= 0) ) {
- break;
- }
- if (regionMatch(local, n, "CIA")) { // "CIA" -> X
- code.append('X');
- break;
- }
- if (!isLastChar(wdsz, n) &&
- (this.frontv.indexOf(local.charAt(n + 1)) >= 0)) {
- code.append('S');
- break; // CI,CE,CY -> S
- }
- if (isPreviousChar(local, n, 'S') &&
- isNextChar(local, n, 'H') ) { // SCH->sk
- code.append('K') ;
- break ;
- }
- if (isNextChar(local, n, 'H')) { // detect CH
- if ((n == 0) &&
- (wdsz >= 3) &&
- isVowel(local,2) ) { // CH consonant -> K consonant
- code.append('K');
- } else {
- code.append('X'); // CHvowel -> X
- }
- } else {
- code.append('K');
- }
- break ;
- case 'D' :
- if (!isLastChar(wdsz, n + 1) &&
- isNextChar(local, n, 'G') &&
- (this.frontv.indexOf(local.charAt(n + 2)) >= 0)) { // DGE DGI DGY -> J
- code.append('J'); n += 2 ;
- } else {
- code.append('T');
- }
- break ;
- case 'G' : // GH silent at end or before consonant
- if (isLastChar(wdsz, n + 1) &&
- isNextChar(local, n, 'H')) {
- break;
- }
- if (!isLastChar(wdsz, n + 1) &&
- isNextChar(local,n,'H') &&
- !isVowel(local,n+2)) {
- break;
- }
- if ((n > 0) &&
- ( regionMatch(local, n, "GN") ||
- regionMatch(local, n, "GNED") ) ) {
- break; // silent G
- }
- if (isPreviousChar(local, n, 'G')) {
- hard = true ;
- } else {
- hard = false ;
- }
- if (!isLastChar(wdsz, n) &&
- (this.frontv.indexOf(local.charAt(n + 1)) >= 0) &&
- (!hard)) {
- code.append('J');
- } else {
- code.append('K');
- }
- break ;
- case 'H':
- if (isLastChar(wdsz, n)) {
- break ; // terminal H
- }
- if ((n > 0) &&
- (this.varson.indexOf(local.charAt(n - 1)) >= 0)) {
- break;
- }
- if (isVowel(local,n+1)) {
- code.append('H'); // Hvowel
- }
- break;
- case 'F':
- case 'J' :
- case 'L' :
- case 'M':
- case 'N' :
- case 'R' :
- code.append(symb);
- break;
- case 'K' :
- if (n > 0) { // not initial
- if (!isPreviousChar(local, n, 'C')) {
- code.append(symb);
- }
- } else {
- code.append(symb); // initial K
- }
- break ;
- case 'P' :
- if (isNextChar(local,n,'H')) {
- // PH -> F
- code.append('F');
- } else {
- code.append(symb);
- }
- break ;
- case 'Q' :
- code.append('K');
- break;
- case 'S' :
- if (regionMatch(local,n,"SH") ||
- regionMatch(local,n,"SIO") ||
- regionMatch(local,n,"SIA")) {
- code.append('X');
- } else {
- code.append('S');
- }
- break;
- case 'T' :
- if (regionMatch(local,n,"TIA") ||
- regionMatch(local,n,"TIO")) {
- code.append('X');
- break;
- }
- if (regionMatch(local,n,"TCH")) {
- // Silent if in "TCH"
- break;
- }
- // substitute numeral 0 for TH (resembles theta after all)
- if (regionMatch(local,n,"TH")) {
- code.append('0');
- } else {
- code.append('T');
- }
- break ;
- case 'V' :
- code.append('F'); break ;
- case 'W' : case 'Y' : // silent if not followed by vowel
- if (!isLastChar(wdsz,n) &&
- isVowel(local,n+1)) {
- code.append(symb);
- }
- break ;
- case 'X' :
- code.append('K'); code.append('S');
- break ;
- case 'Z' :
- code.append('S'); break ;
- } // end switch
- n++ ;
- } // end else from symb != 'C'
- if (code.length() > this.getMaxCodeLen()) {
- code.setLength(this.getMaxCodeLen());
- }
- }
- return code.toString();
- }
- private boolean isVowel(StringBuffer string, int index) {
- return (this.vowels.indexOf(string.charAt(index)) >= 0);
- private boolean isPreviousChar(StringBuffer string, int index, char c) {
- boolean matches = false;
- if( index > 0 &&
- index < string.length() ) {
- matches = string.charAt(index - 1) == c;
- return matches;
- private boolean isNextChar(StringBuffer string, int index, char c) {
- boolean matches = false;
- if( index >= 0 &&
- index < string.length() - 1 ) {
- matches = string.charAt(index + 1) == c;
- return matches;
- private boolean regionMatch(StringBuffer string, int index, String test) {
- boolean matches = false;
- if( index >= 0 &&
- (index + test.length() - 1) < string.length() ) {
- String substring = string.substring( index, index + test.length());
- matches = substring.equals( test );
- return matches;
- private boolean isLastChar(int wdsz, int n) {
- return n + 1 == wdsz;
- /**
- * Encodes an Object using the metaphone algorithm. This method
- * is provided in order to satisfy the requirements of the
- * Encoder interface, and will throw an EncoderException if the
- * supplied object is not of type java.lang.String.
- *
- * @param pObject Object to encode
- * @return An object (or type java.lang.String) containing the
- * metaphone code which corresponds to the String supplied.
- * @throws EncoderException if the parameter supplied is not
- * of type java.lang.String
- */
- public Object encode(Object pObject) throws EncoderException {
- if (!(pObject instanceof java.lang.String)) {
- throw new EncoderException("Parameter supplied to Metaphone encode is not of type java.lang.String");
- }
- return metaphone((String) pObject);
- }
- /**
- * Encodes a String using the Metaphone algorithm.
- *
- * @param pString String object to encode
- * @return The metaphone code corresponding to the String supplied
- */
- public String encode(String pString) {
- return metaphone(pString);
- }
- /**
- * Tests is the metaphones of two strings are identical.
- *
- * @param str1 First of two strings to compare
- * @param str2 Second of two strings to compare
- * @return true if the metaphones of these strings are identical,
- * false otherwise.
- */
- public boolean isMetaphoneEqual(String str1, String str2) {
- return metaphone(str1).equals(metaphone(str2));
- }
- /**
- * Returns the maxCodeLen.
- * @return int
- */
- public int getMaxCodeLen() { return this.maxCodeLen; }
- /**
- * Sets the maxCodeLen.
- * @param maxCodeLen The maxCodeLen to set
- */
- public void setMaxCodeLen(int maxCodeLen) { this.maxCodeLen = maxCodeLen; }
diff --git a/clients/java/src/org/apache/commons/codec/language/RefinedSoundex.java b/clients/java/src/org/apache/commons/codec/language/RefinedSoundex.java
deleted file mode 100644
index 693ddca..0000000
--- a/clients/java/src/org/apache/commons/codec/language/RefinedSoundex.java
+++ /dev/null
@@ -1,183 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.language;
-import org.apache.commons.codec.EncoderException;
-import org.apache.commons.codec.StringEncoder;
- * Encodes a string into a Refined Soundex value. A refined soundex code is
- * optimized for spell checking words. Soundex method originally developed by
- *
Margaret Odell
and
Robert Russell
.
- * @author Apache Software Foundation
- * @version $Id: RefinedSoundex.java,v 1.21 2004/06/05 18:32:04 ggregory Exp $
-public class RefinedSoundex implements StringEncoder {
- /**
- * This static variable contains an instance of the RefinedSoundex using
- * the US_ENGLISH mapping.
- */
- public static final RefinedSoundex US_ENGLISH = new RefinedSoundex();
- /**
- * RefinedSoundex is *refined* for a number of reasons one being that the
- * mappings have been altered. This implementation contains default
- * mappings for US English.
- */
- public static final char[] US_ENGLISH_MAPPING = "01360240043788015936020505".toCharArray();
- /**
- * Every letter of the alphabet is "mapped" to a numerical value. This char
- * array holds the values to which each letter is mapped. This
- * implementation contains a default map for US_ENGLISH
- */
- private char[] soundexMapping;
- /**
- * Creates an instance of the RefinedSoundex object using the default US
- * English mapping.
- */
- public RefinedSoundex() {
- this(US_ENGLISH_MAPPING);
- }
- /**
- * Creates a refined soundex instance using a custom mapping. This
- * constructor can be used to customize the mapping, and/or possibly
- * provide an internationalized mapping for a non-Western character set.
- * @param mapping
- * Mapping array to use when finding the corresponding code for
- * a given character
- */
- public RefinedSoundex(char[] mapping) {
- this.soundexMapping = mapping;
- }
- /**
- * Returns the number of characters in the two encoded Strings that are the
- * same. This return value ranges from 0 to the length of the shortest
- * encoded String: 0 indicates little or no similarity, and 4 out of 4 (for
- * example) indicates strong similarity or identical values. For refined
- * Soundex, the return value can be greater than 4.
- * @param s1
- * A String that will be encoded and compared.
- * @param s2
- * A String that will be encoded and compared.
- * @return The number of characters in the two encoded Strings that are the
- * same from 0 to to the length of the shortest encoded String.
- * @see SoundexUtils#difference(StringEncoder,String,String)
- * @see
- * MS T-SQL DIFFERENCE
- * @throws EncoderException
- * if an error occurs encoding one of the strings
- * @since 1.3
- */
- public int difference(String s1, String s2) throws EncoderException {
- return SoundexUtils.difference(this, s1, s2);
- }
- /**
- * Encodes an Object using the refined soundex algorithm. This method is
- * provided in order to satisfy the requirements of the Encoder interface,
- * and will throw an EncoderException if the supplied object is not of type
- * java.lang.String.
- * @param pObject
- * Object to encode
- * @return An object (or type java.lang.String) containing the refined
- * soundex code which corresponds to the String supplied.
- * @throws EncoderException
- * if the parameter supplied is not of type java.lang.String
- */
- public Object encode(Object pObject) throws EncoderException {
- if (!(pObject instanceof java.lang.String)) {
- throw new EncoderException("Parameter supplied to RefinedSoundex encode is not of type java.lang.String");
- }
- return soundex((String) pObject);
- }
- /**
- * Encodes a String using the refined soundex algorithm.
- * @param pString
- * A String object to encode
- * @return A Soundex code corresponding to the String supplied
- */
- public String encode(String pString) {
- return soundex(pString);
- }
- /**
- * Returns the mapping code for a given character. The mapping codes are
- * maintained in an internal char array named soundexMapping, and the
- * default values of these mappings are US English.
- * @param c
- * char to get mapping for
- * @return A character (really a numeral) to return for the given char
- */
- char getMappingCode(char c) {
- if (!Character.isLetter(c)) {
- return 0;
- }
- return this.soundexMapping[Character.toUpperCase(c) - 'A'];
- }
- /**
- * Retreives the Refined Soundex code for a given String object.
- * @param str
- * String to encode using the Refined Soundex algorithm
- * @return A soundex code for the String supplied
- */
- public String soundex(String str) {
- if (str == null) {
- return null;
- }
- str = SoundexUtils.clean(str);
- if (str.length() == 0) {
- return str;
- }
- StringBuffer sBuf = new StringBuffer();
- sBuf.append(str.charAt(0));
- char last, current;
- last = '*';
- for (int i = 0; i < str.length(); i++) {
- current = getMappingCode(str.charAt(i));
- if (current == last) {
- continue;
- } else if (current != 0) {
- sBuf.append(current);
- }
- last = current;
- }
- return sBuf.toString();
- }
diff --git a/clients/java/src/org/apache/commons/codec/language/Soundex.java b/clients/java/src/org/apache/commons/codec/language/Soundex.java
deleted file mode 100644
index c4a88bd..0000000
--- a/clients/java/src/org/apache/commons/codec/language/Soundex.java
+++ /dev/null
@@ -1,271 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.language;
-import org.apache.commons.codec.EncoderException;
-import org.apache.commons.codec.StringEncoder;
- * Encodes a string into a Soundex value. Soundex is an encoding used to relate similar names, but can also be used as a
- * general purpose scheme to find word with similar phonemes.
- * @author Apache Software Foundation
- * @version $Id: Soundex.java,v 1.26 2004/07/07 23:15:24 ggregory Exp $
-public class Soundex implements StringEncoder {
- /**
- * An instance of Soundex using the US_ENGLISH_MAPPING mapping.
- *
- * @see #US_ENGLISH_MAPPING
- */
- public static final Soundex US_ENGLISH = new Soundex();
- /**
- * This is a default mapping of the 26 letters used in US English. A value of
0
for a letter position
- * means do not encode.
- *
- * (This constant is provided as both an implementation convenience and to allow Javadoc to pick - * up the value for the constant values page.) - *
- * - * @see #US_ENGLISH_MAPPING - */ - public static final String US_ENGLISH_MAPPING_STRING = "01230120022455012623010202"; - /** - * This is a default mapping of the 26 letters used in US English. A value of
0
for a letter position
- * means do not encode.
- *
- * @see Soundex#Soundex(char[])
- */
- public static final char[] US_ENGLISH_MAPPING = US_ENGLISH_MAPPING_STRING.toCharArray();
- /**
- * Encodes the Strings and returns the number of characters in the two encoded Strings that are the same. This
- * return value ranges from 0 through 4: 0 indicates little or no similarity, and 4 indicates strong similarity or
- * identical values.
- *
- * @param s1
- * A String that will be encoded and compared.
- * @param s2
- * A String that will be encoded and compared.
- * @return The number of characters in the two encoded Strings that are the same from 0 to 4.
- *
- * @see SoundexUtils#difference(StringEncoder,String,String)
- * @see
MS
- * T-SQL DIFFERENCE
- *
- * @throws EncoderException
- * if an error occurs encoding one of the strings
- * @since 1.3
- */
- public int difference(String s1, String s2) throws EncoderException {
- return SoundexUtils.difference(this, s1, s2);
- }
- /**
- * The maximum length of a Soundex code - Soundex codes are only four characters by definition.
- *
- * @deprecated This feature is not needed since the encoding size must be constant. Will be removed in 2.0.
- */
- private int maxLength = 4;
- /**
- * Every letter of the alphabet is "mapped" to a numerical value. This char array holds the values to which each
- * letter is mapped. This implementation contains a default map for US_ENGLISH
- */
- private char[] soundexMapping;
- /**
- * Creates an instance using US_ENGLISH_MAPPING
- *
- * @see Soundex#Soundex(char[])
- * @see Soundex#US_ENGLISH_MAPPING
- */
- public Soundex() {
- this(US_ENGLISH_MAPPING);
- }
- /**
- * Creates a soundex instance using the given mapping. This constructor can be used to provide an internationalized
- * mapping for a non-Western character set.
- *
- * Every letter of the alphabet is "mapped" to a numerical value. This char array holds the values to which each
- * letter is mapped. This implementation contains a default map for US_ENGLISH
- *
- * @param mapping
- * Mapping array to use when finding the corresponding code for a given character
- */
- public Soundex(char[] mapping) {
- this.setSoundexMapping(mapping);
- }
- /**
- * Encodes an Object using the soundex algorithm. This method is provided in order to satisfy the requirements of
- * the Encoder interface, and will throw an EncoderException if the supplied object is not of type java.lang.String.
- *
- * @param pObject
- * Object to encode
- * @return An object (or type java.lang.String) containing the soundex code which corresponds to the String
- * supplied.
- * @throws EncoderException
- * if the parameter supplied is not of type java.lang.String
- * @throws IllegalArgumentException
- * if a character is not mapped
- */
- public Object encode(Object pObject) throws EncoderException {
- if (!(pObject instanceof String)) {
- throw new EncoderException("Parameter supplied to Soundex encode is not of type java.lang.String");
- }
- return soundex((String) pObject);
- }
- /**
- * Encodes a String using the soundex algorithm.
- *
- * @param pString
- * A String object to encode
- * @return A Soundex code corresponding to the String supplied
- * @throws IllegalArgumentException
- * if a character is not mapped
- */
- public String encode(String pString) {
- return soundex(pString);
- }
- /**
- * Used internally by the SoundEx algorithm.
- *
- * Consonants from the same code group separated by W or H are treated as one.
- *
- * @param str
- * the cleaned working string to encode (in upper case).
- * @param index
- * the character position to encode
- * @return Mapping code for a particular character
- * @throws IllegalArgumentException
- * if the character is not mapped
- */
- private char getMappingCode(String str, int index) {
- char mappedChar = this.map(str.charAt(index));
- // HW rule check
- if (index > 1 && mappedChar != '0') {
- char hwChar = str.charAt(index - 1);
- if ('H' == hwChar || 'W' == hwChar) {
- char preHWChar = str.charAt(index - 2);
- char firstCode = this.map(preHWChar);
- if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) {
- return 0;
- }
- }
- }
- return mappedChar;
- }
- /**
- * Returns the maxLength. Standard Soundex
- *
- * @deprecated This feature is not needed since the encoding size must be constant. Will be removed in 2.0.
- * @return int
- */
- public int getMaxLength() {
- return this.maxLength;
- }
- /**
- * Returns the soundex mapping.
- *
- * @return soundexMapping.
- */
- private char[] getSoundexMapping() {
- return this.soundexMapping;
- }
- /**
- * Maps the given upper-case character to it's Soudex code.
- *
- * @param ch
- * An upper-case character.
- * @return A Soundex code.
- * @throws IllegalArgumentException
- * Thrown if
ch
is not mapped.
- */
- private char map(char ch) {
- int index = ch - 'A';
- if (index < 0 || index >= this.getSoundexMapping().length) {
- throw new IllegalArgumentException("The character is not mapped: " + ch);
- }
- return this.getSoundexMapping()[index];
- }
- /**
- * Sets the maxLength.
- *
- * @deprecated This feature is not needed since the encoding size must be constant. Will be removed in 2.0.
- * @param maxLength
- * The maxLength to set
- */
- public void setMaxLength(int maxLength) {
- this.maxLength = maxLength;
- }
- /**
- * Sets the soundexMapping.
- *
- * @param soundexMapping
- * The soundexMapping to set.
- */
- private void setSoundexMapping(char[] soundexMapping) {
- this.soundexMapping = soundexMapping;
- }
- /**
- * Retreives the Soundex code for a given String object.
- *
- * @param str
- * String to encode using the Soundex algorithm
- * @return A soundex code for the String supplied
- * @throws IllegalArgumentException
- * if a character is not mapped
- */
- public String soundex(String str) {
- if (str == null) {
- return null;
- }
- str = SoundexUtils.clean(str);
- if (str.length() == 0) {
- return str;
- }
- char out[] = {'0', '0', '0', '0'};
- char last, mapped;
- int incount = 1, count = 1;
- out[0] = str.charAt(0);
- last = getMappingCode(str, 0);
- while ((incount < str.length()) && (count < out.length)) {
- mapped = getMappingCode(str, incount++);
- if (mapped != 0) {
- if ((mapped != '0') && (mapped != last)) {
- out[count++] = mapped;
- }
- last = mapped;
- }
- }
- return new String(out);
- }
\ No newline at end of file
diff --git a/clients/java/src/org/apache/commons/codec/language/SoundexUtils.java b/clients/java/src/org/apache/commons/codec/language/SoundexUtils.java
deleted file mode 100644
index 27dfd7d..0000000
--- a/clients/java/src/org/apache/commons/codec/language/SoundexUtils.java
+++ /dev/null
@@ -1,122 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.language;
-import org.apache.commons.codec.EncoderException;
-import org.apache.commons.codec.StringEncoder;
- * Utility methods for {@link Soundex} and {@link RefinedSoundex} classes.
- * @author Apache Software Foundation
- * @version $Id: SoundexUtils.java,v 1.5 2004/03/17 18:31:35 ggregory Exp $
- * @since 1.3
-final class SoundexUtils {
- /**
- * Cleans up the input string before Soundex processing by only returning
- * upper case letters.
- * @param str
- * The String to clean.
- * @return A clean String.
- */
- static String clean(String str) {
- if (str == null || str.length() == 0) {
- return str;
- }
- int len = str.length();
- char[] chars = new char[len];
- int count = 0;
- for (int i = 0; i < len; i++) {
- if (Character.isLetter(str.charAt(i))) {
- chars[count++] = str.charAt(i);
- }
- }
- if (count == len) {
- return str.toUpperCase();
- }
- return new String(chars, 0, count).toUpperCase();
- }
- /**
- * Encodes the Strings and returns the number of characters in the two
- * encoded Strings that are the same.
- *
true
if SPACE characters are to be transformed,
false
otherwise
- */
- public boolean isEncodeBlanks() {
- return this.encodeBlanks;
- }
- /**
- * Defines whether optional tranformation of SPACE characters is to be used
- *
- * @param b
- *
true
if SPACE characters are to be transformed,
false
otherwise
- */
- public void setEncodeBlanks(boolean b) {
- this.encodeBlanks = b;
- }
\ No newline at end of file
diff --git a/clients/java/src/org/apache/commons/codec/net/QuotedPrintableCodec.java b/clients/java/src/org/apache/commons/codec/net/QuotedPrintableCodec.java
deleted file mode 100644
index 2bc7a32..0000000
--- a/clients/java/src/org/apache/commons/codec/net/QuotedPrintableCodec.java
+++ /dev/null
@@ -1,387 +0,0 @@
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
-package org.apache.commons.codec.net;
-import java.io.ByteArrayOutputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.BitSet;
-import org.apache.commons.codec.BinaryDecoder;
-import org.apache.commons.codec.BinaryEncoder;
-import org.apache.commons.codec.DecoderException;
-import org.apache.commons.codec.EncoderException;
-import org.apache.commons.codec.StringDecoder;
-import org.apache.commons.codec.StringEncoder;
- * Codec for the Quoted-Printable section of
RFC 1521
.
- * The Quoted-Printable encoding is intended to represent data that largely consists of octets that correspond to
- * printable characters in the ASCII character set. It encodes the data in such a way that the resulting octets are
- * unlikely to be modified by mail transport. If the data being encoded are mostly ASCII text, the encoded form of the
- * data remains largely recognizable by humans. A body which is entirely ASCII may also be encoded in Quoted-Printable
- * to ensure the integrity of the data should the message pass through a character- translating, and/or line-wrapping
- * gateway.
- * Note:
- * Rules #3, #4, and #5 of the quoted-printable spec are not implemented yet because the complete quoted-printable spec
- * does not lend itself well into the byte[] oriented codec framework. Complete the codec once the steamable codec
- * framework is ready. The motivation behind providing the codec in a partial form is that it can already come in handy
- * for those applications that do not require quoted-printable line formatting (rules #3, #4, #5), for instance Q codec.
- * @see
RFC 1521 MIME (Multipurpose Internet Mail Extensions) Part One:
- * Mechanisms for Specifying and Describing the Format of Internet Message Bodies
- * @author Apache Software Foundation
- * @since 1.3
- * @version $Id: QuotedPrintableCodec.java,v 1.7 2004/04/09 22:21:07 ggregory Exp $
-public class QuotedPrintableCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder {
- /**
- * The default charset used for string decoding and encoding.
- */
- private String charset = StringEncodings.UTF8;
- /**
- * BitSet of printable characters as defined in RFC 1521.
- */
- private static final BitSet PRINTABLE_CHARS = new BitSet(256);
- private static byte ESCAPE_CHAR = '=';
- private static byte TAB = 9;
- private static byte SPACE = 32;
- // Static initializer for printable chars collection
- static {
- // alpha characters
- for (int i = 33; i <= 60; i++) {
- PRINTABLE_CHARS.set(i);
- }
- for (int i = 62; i <= 126; i++) {
- PRINTABLE_CHARS.set(i);
- }
- PRINTABLE_CHARS.set(TAB);
- PRINTABLE_CHARS.set(SPACE);
- }
- /**
- * Default constructor.
- */
- public QuotedPrintableCodec() {
- super();
- }
- /**
- * Constructor which allows for the selection of a default charset
- *
- * @param charset
- * the default string charset to use.
- */
- public QuotedPrintableCodec(String charset) {
- super();
- this.charset = charset;
- }
- /**
- * Encodes byte into its quoted-printable representation.
- *
- * @param b
- * byte to encode
- * @param buffer
- * the buffer to write to
- */
- private static final void encodeQuotedPrintable(int b, ByteArrayOutputStream buffer) {
- buffer.write(ESCAPE_CHAR);
- char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
- char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
- buffer.write(hex1);
- buffer.write(hex2);
- }
- /**
- * Encodes an array of bytes into an array of quoted-printable 7-bit characters. Unsafe characters are escaped.
- *
- *
- * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in - * RFC 1521 and is suitable for encoding binary data and unformatted text. - *
- * - * @param printable - * bitset of characters deemed quoted-printable - * @param bytes - * array of bytes to be encoded - * @return array of bytes containing quoted-printable data - */ - public static final byte[] encodeQuotedPrintable(BitSet printable, byte[] bytes) { - if (bytes == null) { - return null; - } - if (printable == null) { - printable = PRINTABLE_CHARS; - } - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - for (int i = 0; i < bytes.length; i++) { - int b = bytes[i]; - if (b < 0) { - b = 256 + b; - } - if (printable.get(b)) { - buffer.write(b); - } else { - encodeQuotedPrintable(b, buffer); - } - } - return buffer.toByteArray(); - } - /** - * Decodes an array quoted-printable characters into an array of original bytes. Escaped characters are converted - * back to their original representation. - * - *- * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in - * RFC 1521. - *
- * - * @param bytes - * array of quoted-printable characters - * @return array of original bytes - * @throws DecoderException - * Thrown if quoted-printable decoding is unsuccessful - */ - public static final byte[] decodeQuotedPrintable(byte[] bytes) throws DecoderException { - if (bytes == null) { - return null; - } - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - for (int i = 0; i < bytes.length; i++) { - int b = bytes[i]; - if (b == ESCAPE_CHAR) { - try { - int u = Character.digit((char) bytes[++i], 16); - int l = Character.digit((char) bytes[++i], 16); - if (u == -1 || l == -1) { - throw new DecoderException("Invalid quoted-printable encoding"); - } - buffer.write((char) ((u << 4) + l)); - } catch (ArrayIndexOutOfBoundsException e) { - throw new DecoderException("Invalid quoted-printable encoding"); - } - } else { - buffer.write(b); - } - } - return buffer.toByteArray(); - } - /** - * Encodes an array of bytes into an array of quoted-printable 7-bit characters. Unsafe characters are escaped. - * - *- * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in - * RFC 1521 and is suitable for encoding binary data and unformatted text. - *
- * - * @param bytes - * array of bytes to be encoded - * @return array of bytes containing quoted-printable data - */ - public byte[] encode(byte[] bytes) { - return encodeQuotedPrintable(PRINTABLE_CHARS, bytes); - } - /** - * Decodes an array of quoted-printable characters into an array of original bytes. Escaped characters are converted - * back to their original representation. - * - *- * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in - * RFC 1521. - *
- * - * @param bytes - * array of quoted-printable characters - * @return array of original bytes - * @throws DecoderException - * Thrown if quoted-printable decoding is unsuccessful - */ - public byte[] decode(byte[] bytes) throws DecoderException { - return decodeQuotedPrintable(bytes); - } - /** - * Encodes a string into its quoted-printable form using the default string charset. Unsafe characters are escaped. - * - *- * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in - * RFC 1521 and is suitable for encoding binary data. - *
- * - * @param pString - * string to convert to quoted-printable form - * @return quoted-printable string - * - * @throws EncoderException - * Thrown if quoted-printable encoding is unsuccessful - * - * @see #getDefaultCharset() - */ - public String encode(String pString) throws EncoderException { - if (pString == null) { - return null; - } - try { - return encode(pString, getDefaultCharset()); - } catch (UnsupportedEncodingException e) { - throw new EncoderException(e.getMessage()); - } - } - /** - * Decodes a quoted-printable string into its original form using the specified string charset. Escaped characters - * are converted back to their original representation. - * - * @param pString - * quoted-printable string to convert into its original form - * @param charset - * the original string charset - * @return original string - * @throws DecoderException - * Thrown if quoted-printable decoding is unsuccessful - * @throws UnsupportedEncodingException - * Thrown if charset is not supported - */ - public String decode(String pString, String charset) throws DecoderException, UnsupportedEncodingException { - if (pString == null) { - return null; - } - return new String(decode(pString.getBytes(StringEncodings.US_ASCII)), charset); - } - /** - * Decodes a quoted-printable string into its original form using the default string charset. Escaped characters are - * converted back to their original representation. - * - * @param pString - * quoted-printable string to convert into its original form - * @return original string - * @throws DecoderException - * Thrown if quoted-printable decoding is unsuccessful - * @throws UnsupportedEncodingException - * Thrown if charset is not supported - * @see #getDefaultCharset() - */ - public String decode(String pString) throws DecoderException { - if (pString == null) { - return null; - } - try { - return decode(pString, getDefaultCharset()); - } catch (UnsupportedEncodingException e) { - throw new DecoderException(e.getMessage()); - } - } - /** - * Encodes an object into its quoted-printable safe form. Unsafe characters are escaped. - * - * @param pObject - * string to convert to a quoted-printable form - * @return quoted-printable object - * @throws EncoderException - * Thrown if quoted-printable encoding is not applicable to objects of this type or if encoding is - * unsuccessful - */ - public Object encode(Object pObject) throws EncoderException { - if (pObject == null) { - return null; - } else if (pObject instanceof byte[]) { - return encode((byte[]) pObject); - } else if (pObject instanceof String) { - return encode((String) pObject); - } else { - throw new EncoderException("Objects of type " - + pObject.getClass().getName() - + " cannot be quoted-printable encoded"); - } - } - /** - * Decodes a quoted-printable object into its original form. Escaped characters are converted back to their original - * representation. - * - * @param pObject - * quoted-printable object to convert into its original form - * @return original object - * @throws DecoderException - * Thrown if quoted-printable decoding is not applicable to objects of this type if decoding is - * unsuccessful - */ - public Object decode(Object pObject) throws DecoderException { - if (pObject == null) { - return null; - } else if (pObject instanceof byte[]) { - return decode((byte[]) pObject); - } else if (pObject instanceof String) { - return decode((String) pObject); - } else { - throw new DecoderException("Objects of type " - + pObject.getClass().getName() - + " cannot be quoted-printable decoded"); - } - } - /** - * Returns the default charset used for string decoding and encoding. - * - * @return the default string charset. - */ - public String getDefaultCharset() { - return this.charset; - } - /** - * Encodes a string into its quoted-printable form using the specified charset. Unsafe characters are escaped. - * - *- * This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in - * RFC 1521 and is suitable for encoding binary data and unformatted text. - *
- * - * @param pString - * string to convert to quoted-printable form - * @param charset - * the charset for pString - * @return quoted-printable string - * - * @throws UnsupportedEncodingException - * Thrown if the charset is not supported - */ - public String encode(String pString, String charset) throws UnsupportedEncodingException { - if (pString == null) { - return null; - } - return new String(encode(pString.getBytes(charset)), StringEncodings.US_ASCII); - } \ No newline at end of file diff --git a/clients/java/src/org/apache/commons/codec/net/RFC1522Codec.java b/clients/java/src/org/apache/commons/codec/net/RFC1522Codec.java deleted file mode 100644 index 1931790..0000000 --- a/clients/java/src/org/apache/commons/codec/net/RFC1522Codec.java +++ /dev/null @@ -1,161 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec.net; -import java.io.UnsupportedEncodingException; -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.EncoderException; - * Implements methods common to all codecs defined in RFC 1522. - * RFC 1522 - * describes techniques to allow the encoding of non-ASCII text in - * various portions of a RFC 822 [2] message header, in a manner which - * is unlikely to confuse existing message handling software. - * @see - * MIME (Multipurpose Internet Mail Extensions) Part Two: - * Message Header Extensions for Non-ASCII Text - * @author Apache Software Foundation - * @since 1.3 - * @version $Id: RFC1522Codec.java,v 1.2 2004/04/09 22:21:43 ggregory Exp $ -abstract class RFC1522Codec { - /** - * Applies an RFC 1522 compliant encoding scheme to the given string of text with the - * given charset. This method constructs the "encoded-word" header common to all the - * RFC 1522 codecs and then invokes {@link #doEncoding(byte [])} method of a concrete - * class to perform the specific enconding. - * - * @param text a string to encode - * @param charset a charset to be used - * - * @return RFC 1522 compliant "encoded-word" - * - * @throws EncoderException thrown if there is an error conidition during the Encoding - * process. - * @throws UnsupportedEncodingException thrown if charset is not supported - * - * @see JRE character - * encoding names - */ - protected String encodeText(final String text, final String charset) - throws EncoderException, UnsupportedEncodingException - { - if (text == null) { - return null; - } - StringBuffer buffer = new StringBuffer(); - buffer.append("=?"); - buffer.append(charset); - buffer.append('?'); - buffer.append(getEncoding()); - buffer.append('?'); - byte [] rawdata = doEncoding(text.getBytes(charset)); - buffer.append(new String(rawdata, StringEncodings.US_ASCII)); - buffer.append("?="); - return buffer.toString(); - } - /** - * Applies an RFC 1522 compliant decoding scheme to the given string of text. This method - * processes the "encoded-word" header common to all the RFC 1522 codecs and then invokes - * {@link #doEncoding(byte [])} method of a concrete class to perform the specific deconding. - * - * @param text a string to decode - * - * @throws DecoderException thrown if there is an error conidition during the Decoding - * process. - * @throws UnsupportedEncodingException thrown if charset specified in the "encoded-word" - * header is not supported - */ - protected String decodeText(final String text) - throws DecoderException, UnsupportedEncodingException - { - if (text == null) { - return null; - } - if ((!text.startsWith("=?")) || (!text.endsWith("?="))) { - throw new DecoderException("RFC 1522 violation: malformed encoded content"); - } - int termnator = text.length() - 2; - int from = 2; - int to = text.indexOf("?", from); - if ((to == -1) || (to == termnator)) { - throw new DecoderException("RFC 1522 violation: charset token not found"); - } - String charset = text.substring(from, to); - if (charset.equals("")) { - throw new DecoderException("RFC 1522 violation: charset not specified"); - } - from = to + 1; - to = text.indexOf("?", from); - if ((to == -1) || (to == termnator)) { - throw new DecoderException("RFC 1522 violation: encoding token not found"); - } - String encoding = text.substring(from, to); - if (!getEncoding().equalsIgnoreCase(encoding)) { - throw new DecoderException("This codec cannot decode " + - encoding + " encoded content"); - } - from = to + 1; - to = text.indexOf("?", from); - byte[] data = text.substring(from, to).getBytes(StringEncodings.US_ASCII); - data = doDecoding(data); - return new String(data, charset); - } - /** - * Returns the codec name (referred to as encoding in the RFC 1522) - * - * @return name of the codec - */ - protected abstract String getEncoding(); - /** - * Encodes an array of bytes using the defined encoding scheme - * - * @param bytes Data to be encoded - * - * @return A byte array containing the encoded data - * - * @throws EncoderException thrown if the Encoder encounters a failure condition - * during the encoding process. - */ - protected abstract byte[] doEncoding(byte[] bytes) throws EncoderException; - /** - * Decodes an array of bytes using the defined encoding scheme - * - * @param bytes Data to be decoded - * - * @return a byte array that contains decoded data - * - * @throws DecoderException A decoder exception is thrown if a Decoder encounters a - * failure condition during the decode process. - */ - protected abstract byte[] doDecoding(byte[] bytes) throws DecoderException; diff --git a/clients/java/src/org/apache/commons/codec/net/StringEncodings.java b/clients/java/src/org/apache/commons/codec/net/StringEncodings.java deleted file mode 100644 index 1f0fad0..0000000 --- a/clients/java/src/org/apache/commons/codec/net/StringEncodings.java +++ /dev/null @@ -1,52 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec.net; - * String encodings used in this package. - * @author Apache Software Foundation - * @since 1.3 - * @version $Id: StringEncodings.java,v 1.2 2004/04/09 22:21:07 ggregory Exp $ -interface StringEncodings { - /** - *- * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin block of the Unicode character set. - *
- *- * Every implementation of the Java platform is required to support this character encoding. - *
- * - * @see JRE character - * encoding names - */ - String US_ASCII = "US-ASCII"; - /** - *- * Eight-bit Unicode Transformation Format. - *
- *- * Every implementation of the Java platform is required to support this character encoding. - *
- * - * @see JRE character - * encoding names - */ - String UTF8 = "UTF-8"; \ No newline at end of file diff --git a/clients/java/src/org/apache/commons/codec/net/URLCodec.java b/clients/java/src/org/apache/commons/codec/net/URLCodec.java deleted file mode 100644 index d4ccca4..0000000 --- a/clients/java/src/org/apache/commons/codec/net/URLCodec.java +++ /dev/null @@ -1,364 +0,0 @@ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -package org.apache.commons.codec.net; -import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; -import java.util.BitSet; -import org.apache.commons.codec.BinaryDecoder; -import org.apache.commons.codec.BinaryEncoder; -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.EncoderException; -import org.apache.commons.codec.StringDecoder; -import org.apache.commons.codec.StringEncoder; - *Implements the 'www-form-urlencoded' encoding scheme, - * also misleadingly known as URL encoding.
- *For more detailed information please refer to - * Chapter 17.13.4 'Form content types' of the - * HTML 4.01 Specification
- * This codec is meant to be a replacement for standard Java classes - * {@link java.net.URLEncoder} and {@link java.net.URLDecoder} - * on older Java platforms, as these classes in Java versions below - * 1.4 rely on the platform's default charset encoding. - * @author Apache Software Foundation - * @since 1.2 - * @version $Id: URLCodec.java,v 1.19 2004/03/29 07:59:00 ggregory Exp $ -public class URLCodec implements BinaryEncoder, BinaryDecoder, StringEncoder, StringDecoder { - /** - * The default charset used for string decoding and encoding. - */ - protected String charset = StringEncodings.UTF8; - protected static byte ESCAPE_CHAR = '%'; - /** - * BitSet of www-form-url safe characters. - */ - protected static final BitSet WWW_FORM_URL = new BitSet(256); - // Static initializer for www_form_url - static { - // alpha characters - for (int i = 'a'; i <= 'z'; i++) { - WWW_FORM_URL.set(i); - } - for (int i = 'A'; i <= 'Z'; i++) { - WWW_FORM_URL.set(i); - } - // numeric characters - for (int i = '0'; i <= '9'; i++) { - WWW_FORM_URL.set(i); - } - // special chars - WWW_FORM_URL.set('-'); - WWW_FORM_URL.set('_'); - WWW_FORM_URL.set('.'); - WWW_FORM_URL.set('*'); - // blank to be replaced with + - WWW_FORM_URL.set(' '); - } - /** - * Default constructor. - */ - public URLCodec() { - super(); - } - /** - * Constructor which allows for the selection of a default charset - * - * @param charset the default string charset to use. - */ - public URLCodec(String charset) { - super(); - this.charset = charset; - } - /** - * Encodes an array of bytes into an array of URL safe 7-bit - * characters. Unsafe characters are escaped. - * - * @param urlsafe bitset of characters deemed URL safe - * @param bytes array of bytes to convert to URL safe characters - * @return array of bytes containing URL safe characters - */ - public static final byte[] encodeUrl(BitSet urlsafe, byte[] bytes) - { - if (bytes == null) { - return null; - } - if (urlsafe == null) { - urlsafe = WWW_FORM_URL; - } - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - for (int i = 0; i < bytes.length; i++) { - int b = bytes[i]; - if (b < 0) { - b = 256 + b; - } - if (urlsafe.get(b)) { - if (b == ' ') { - b = '+'; - } - buffer.write(b); - } else { - buffer.write('%'); - char hex1 = Character.toUpperCase( - Character.forDigit((b >> 4) & 0xF, 16)); - char hex2 = Character.toUpperCase( - Character.forDigit(b & 0xF, 16)); - buffer.write(hex1); - buffer.write(hex2); - } - } - return buffer.toByteArray(); - } - /** - * Decodes an array of URL safe 7-bit characters into an array of - * original bytes. Escaped characters are converted back to their - * original representation. - * - * @param bytes array of URL safe characters - * @return array of original bytes - * @throws DecoderException Thrown if URL decoding is unsuccessful - */ - public static final byte[] decodeUrl(byte[] bytes) - throws DecoderException - { - if (bytes == null) { - return null; - } - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - for (int i = 0; i < bytes.length; i++) { - int b = bytes[i]; - if (b == '+') { - buffer.write(' '); - } else if (b == '%') { - try { - int u = Character.digit((char)bytes[++i], 16); - int l = Character.digit((char)bytes[++i], 16); - if (u == -1 || l == -1) { - throw new DecoderException("Invalid URL encoding"); - } - buffer.write((char)((u << 4) + l)); - } catch(ArrayIndexOutOfBoundsException e) { - throw new DecoderException("Invalid URL encoding"); - } - } else { - buffer.write(b); - } - } - return buffer.toByteArray(); - } - /** - * Encodes an array of bytes into an array of URL safe 7-bit - * characters. Unsafe characters are escaped. - * - * @param bytes array of bytes to convert to URL safe characters - * @return array of bytes containing URL safe characters - */ - public byte[] encode(byte[] bytes) { - return encodeUrl(WWW_FORM_URL, bytes); - } - /** - * Decodes an array of URL safe 7-bit characters into an array of - * original bytes. Escaped characters are converted back to their - * original representation. - * - * @param bytes array of URL safe characters - * @return array of original bytes - * @throws DecoderException Thrown if URL decoding is unsuccessful - */ - public byte[] decode(byte[] bytes) throws DecoderException { - return decodeUrl(bytes); - } - /** - * Encodes a string into its URL safe form using the specified - * string charset. Unsafe characters are escaped. - * - * @param pString string to convert to a URL safe form - * @param charset the charset for pString - * @return URL safe string - * @throws UnsupportedEncodingException Thrown if charset is not - * supported - */ - public String encode(String pString, String charset) - throws UnsupportedEncodingException - { - if (pString == null) { - return null; - } - return new String(encode(pString.getBytes(charset)), StringEncodings.US_ASCII); - } - /** - * Encodes a string into its URL safe form using the default string - * charset. Unsafe characters are escaped. - * - * @param pString string to convert to a URL safe form - * @return URL safe string - * @throws EncoderException Thrown if URL encoding is unsuccessful - * - * @see #getDefaultCharset() - */ - public String encode(String pString) throws EncoderException { - if (pString == null) { - return null; - } - try { - return encode(pString, getDefaultCharset()); - } catch(UnsupportedEncodingException e) { - throw new EncoderException(e.getMessage()); - } - } - /** - * Decodes a URL safe string into its original form using the - * specified encoding. Escaped characters are converted back - * to their original representation. - * - * @param pString URL safe string to convert into its original form - * @param charset the original string charset - * @return original string - * @throws DecoderException Thrown if URL decoding is unsuccessful - * @throws UnsupportedEncodingException Thrown if charset is not - * supported - */ - public String decode(String pString, String charset) - throws DecoderException, UnsupportedEncodingException - { - if (pString == null) { - return null; - } - return new String(decode(pString.getBytes(StringEncodings.US_ASCII)), charset); - } - /** - * Decodes a URL safe string into its original form using the default - * string charset. Escaped characters are converted back to their - * original representation. - * - * @param pString URL safe string to convert into its original form - * @return original string - * @throws DecoderException Thrown if URL decoding is unsuccessful - * - * @see #getDefaultCharset() - */ - public String decode(String pString) throws DecoderException { - if (pString == null) { - return null; - } - try { - return decode(pString, getDefaultCharset()); - } catch(UnsupportedEncodingException e) { - throw new DecoderException(e.getMessage()); - } - } - /** - * Encodes an object into its URL safe form. Unsafe characters are - * escaped. - * - * @param pObject string to convert to a URL safe form - * @return URL safe object - * @throws EncoderException Thrown if URL encoding is not - * applicable to objects of this type or - * if encoding is unsuccessful - */ - public Object encode(Object pObject) throws EncoderException { - if (pObject == null) { - return null; - } else if (pObject instanceof byte[]) { - return encode((byte[])pObject); - } else if (pObject instanceof String) { - return encode((String)pObject); - } else { - throw new EncoderException("Objects of type " + - pObject.getClass().getName() + " cannot be URL encoded"); - } - } - /** - * Decodes a URL safe object into its original form. Escaped - * characters are converted back to their original representation. - * - * @param pObject URL safe object to convert into its original form - * @return original object - * @throws DecoderException Thrown if URL decoding is not - * applicable to objects of this type - * if decoding is unsuccessful - */ - public Object decode(Object pObject) throws DecoderException { - if (pObject == null) { - return null; - } else if (pObject instanceof byte[]) { - return decode((byte[])pObject); - } else if (pObject instanceof String) { - return decode((String)pObject); - } else { - throw new DecoderException("Objects of type " + - pObject.getClass().getName() + " cannot be URL decoded"); - } - } - /** - * The
String
encoding used for decoding and encoding.
- *
- * @return Returns the encoding.
- *
- * @deprecated use #getDefaultCharset()
- */
- public String getEncoding() {
- return this.charset;
- }
- /**
- * The default charset used for string decoding and encoding.
- *
- * @return the default string charset.
- */
- public String getDefaultCharset() {
- return this.charset;
- }
diff --git a/clients/java/src/org/apache/commons/codec/net/package.html b/clients/java/src/org/apache/commons/codec/net/package.html
deleted file mode 100644
index b47f41b..0000000
--- a/clients/java/src/org/apache/commons/codec/net/package.html
+++ /dev/null
@@ -1,22 +0,0 @@
- Network related encoding and decoding.
diff --git a/clients/java/src/org/apache/commons/codec/overview.html b/clients/java/src/org/apache/commons/codec/overview.html
deleted file mode 100644
index ab1fe00..0000000
--- a/clients/java/src/org/apache/commons/codec/overview.html
+++ /dev/null
@@ -1,28 +0,0 @@
-This document is the API specification for the Apache Jakarta Commons Codec Library, version 1.3.
-This library requires a JRE version of 1.2.2 or greater.
-The hypertext links originating from this document point to Sun's version 1.3 API as the 1.2.2 API documentation
-is no longer on-line.
\ No newline at end of file
diff --git a/clients/java/src/org/apache/commons/codec/package.html b/clients/java/src/org/apache/commons/codec/package.html
deleted file mode 100644
index 5e1a3cf..0000000
--- a/clients/java/src/org/apache/commons/codec/package.html
+++ /dev/null
@@ -1,99 +0,0 @@
-
A small set of interfaces used by - the various implementations in the sub-packages.
-Definitive implementations of commonly used encoders and decoders.
-Codec is currently comprised of a modest set of utilities and a - simple framework for String encoding and decoding in three categories: - Binary Encoders, Language Encoders, and Network Encoders.
-Codec contains network related encoders
- org.apache.commons.codec.net.URLCodec - Implements the 'www-form-urlencoded' encoding scheme. - Production diff --git a/clients/java/src/org/apache/commons/httpclient/AutoCloseInputStream.java b/clients/java/src/org/apache/commons/httpclient/AutoCloseInputStream.java deleted file mode 100644 index d7a6afa..0000000 --- a/clients/java/src/org/apache/commons/httpclient/AutoCloseInputStream.java +++ /dev/null @@ -1,203 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/AutoCloseInputStream.java,v 1.9 2004/04/18 23:51:34 jsdever Exp $ - * $Revision: 505890 $ - * $Date: 2007-02-11 12:25:25 +0100 (Sun, 11 Feb 2007) $ - * ==================================================================== - * 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 - *
len
bytes of data from the stream.
- *
- * @param b a
byte
array to read data into
- * @param off an offset within the array to store data
- * @param len the maximum number of bytes to read
- * @return the number of bytes read or -1 for EOF
- * @throws IOException if there are errors reading
- */
- public int read(byte[] b, int off, int len) throws IOException {
- int l = -1;
- if (isReadAllowed()) {
- l = super.read(b, off, len);
- checkClose(l);
- }
- return l;
- }
- /**
- * Reads some number of bytes from the input stream and stores them into the
- * buffer array b.
- *
- * @param b a
byte
array to read data into
- * @return the number of bytes read or -1 for EOF
- * @throws IOException if there are errors reading
- */
- public int read(byte[] b) throws IOException {
- int l = -1;
- if (isReadAllowed()) {
- l = super.read(b);
- checkClose(l);
- }
- return l;
- }
- /**
- * Obtains the number of bytes that can be read without blocking.
- *
- * @return the number of bytes available without blocking
- * @throws IOException in case of a problem
- */
- public int available() throws IOException {
- int a = 0; // not -1
- if (isReadAllowed()) {
- a = super.available();
- // no checkClose() here, available() can't trigger EOF
- }
- return a;
- }
- /**
- * Close the stream, and also close the underlying stream if it is not
- * already closed.
- * @throws IOException If an IO problem occurs.
- */
- public void close() throws IOException {
- if (!selfClosed) {
- selfClosed = true;
- notifyWatcher();
- }
- }
- /**
- * Close the underlying stream should the end of the stream arrive.
- *
- * @param readResult The result of the read operation to check.
- * @throws IOException If an IO problem occurs.
- */
- private void checkClose(int readResult) throws IOException {
- if (readResult == -1) {
- notifyWatcher();
- }
- }
- /**
- * See whether a read of the underlying stream should be allowed, and if
- * not, check to see whether our stream has already been closed!
- *
- * @return
true
if it is still OK to read from the stream.
- * @throws IOException If an IO problem occurs.
- */
- private boolean isReadAllowed() throws IOException {
- if (!streamOpen && selfClosed) {
- throw new IOException("Attempted read on closed stream.");
- }
- return streamOpen;
- }
- /**
- * Notify the watcher that the contents have been consumed.
- * @throws IOException If an IO problem occurs.
- */
- private void notifyWatcher() throws IOException {
- if (streamOpen) {
- super.close();
- streamOpen = false;
- if (watcher != null) {
- watcher.responseConsumed();
- }
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/ChunkedInputStream.java b/clients/java/src/org/apache/commons/httpclient/ChunkedInputStream.java
deleted file mode 100644
index efa5ae7..0000000
--- a/clients/java/src/org/apache/commons/httpclient/ChunkedInputStream.java
+++ /dev/null
@@ -1,373 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ChunkedInputStream.java,v 1.24 2004/10/10 15:18:55 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
Transparently coalesces chunks of a HTTP stream that uses - * Transfer-Encoding chunked.
- *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 invocation of subsequent HTTP 1.1 calls, while - * not requiring the client to remember to read the entire contents of the - * response.
- * @author Ortwin Glueck - * @author Sean C. Sullivan - * @author Martin Elwin - * @author Eric Johnson - * @author Mike Bowler - * @author Michael Becke - * @author Oleg Kalnichevski - * @since 2.0 -public class ChunkedInputStream extends InputStream { - /** The inputstream that we're wrapping */ - private InputStream in; - /** The chunk size */ - private int chunkSize; - /** The current position within the current chunk */ - private int pos; - /** True if we'are at the beginning of stream */ - private boolean bof = true; - /** True if we've reached the end of stream */ - private boolean eof = false; - /** True if this stream is closed */ - private boolean closed = false; - /** The method that this stream came from */ - private HttpMethod method = null; - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(ChunkedInputStream.class); - /** - * ChunkedInputStream constructor that associates the chunked input stream with a - * {@link HttpMethod HTTP method}. Usually it should be the same {@link HttpMethod - * HTTP method} the chunked input stream originates from. If chunked input stream - * contains any footers (trailing headers), they will be added to the associated - * {@link HttpMethod HTTP method}. - * - * @param in the raw input stream - * @param method the HTTP method to associate this input stream with. Can be null . - * - * @throws IOException If an IO error occurs - */ - public ChunkedInputStream( - final InputStream in, final HttpMethod method) throws IOException { - if (in == null) { - throw new IllegalArgumentException("InputStream parameter may not be null"); - } - this.in = in; - this.method = method; - this.pos = 0; - } - /** - * ChunkedInputStream constructor - * - * @param in the raw input stream - * - * @throws IOException If an IO error occurs - */ - public ChunkedInputStream(final InputStream in) throws IOException { - this(in, null); - } - /** - *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.
- * - *Trailer headers are read automcatically at the end of the stream and - * can be obtained with the getResponseFooters() method.
- * - * @return -1 of the end of the stream has been reached or the next data - * byte - * @throws IOException If an IO problem occurs - * - * @see HttpMethod#getResponseFooters() - */ - public int read() throws IOException { - if (closed) { - throw new IOException("Attempted read from closed stream."); - } - if (eof) { - return -1; - } - if (pos >= chunkSize) { - nextChunk(); - if (eof) { - return -1; - } - } - pos++; - return in.read(); - } - /** - * 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. - * @see java.io.InputStream#read(byte[], int, int) - * @throws IOException if an IO problem occurs. - */ - 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 (pos >= chunkSize) { - nextChunk(); - if (eof) { - return -1; - } - } - len = Math.min(len, chunkSize - pos); - int count = in.read(b, off, len); - pos += count; - return count; - } - /** - * 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. - * @see java.io.InputStream#read(byte[]) - * @throws IOException if an IO problem occurs. - */ - public int read (byte[] b) throws IOException { - return read(b, 0, b.length); - } - /** - * Read the CRLF terminator. - * @throws IOException If an IO error occurs. - */ - private void readCRLF() throws IOException { - int cr = in.read(); - int lf = in.read(); - if ((cr != '\r') || (lf != '\n')) { - throw new IOException( - "CRLF expected at end of chunk: " + cr + "/" + lf); - } - } - /** - * Read the next chunk. - * @throws IOException If an IO error occurs. - */ - private void nextChunk() throws IOException { - if (!bof) { - readCRLF(); - } - chunkSize = getChunkSizeFromInputStream(in); - bof = false; - 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 true if a valid chunk must be present, - * false otherwise. - * - * @return the chunk size as integer - * - * @throws IOException when the chunk size could not be parsed - */ - private static int getChunkSizeFromInputStream(final InputStream in) - throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // States: 0=normal, 1=\r was scanned, 2=inside quoted string, -1=end - int state = 0; - while (state != -1) { - int b = in.read(); - if (b == -1) { - throw new IOException("chunked stream ended unexpectedly"); - } - switch (state) { - case 0: - switch (b) { - case '\r': - state = 1; - break; - case '\"': - state = 2; - /* fall through */ - default: - baos.write(b); - } - break; - case 1: - if (b == '\n') { - state = -1; - } else { - // this was not CRLF - throw new IOException("Protocol violation: Unexpected" - + " single newline character in chunk size"); - } - break; - case 2: - switch (b) { - case '\\': - b = in.read(); - baos.write(b); - break; - case '\"': - state = 0; - /* fall through */ - default: - baos.write(b); - } - break; - default: throw new RuntimeException("assertion failed"); - } - } - //parse data - String dataString = EncodingUtil.getAsciiString(baos.toByteArray()); - int separator = dataString.indexOf(';'); - dataString = (separator > 0) - ? dataString.substring(0, separator).trim() - : dataString.trim(); - int result; - try { - result = Integer.parseInt(dataString.trim(), 16); - } catch (NumberFormatException e) { - throw new IOException ("Bad chunk size: " + dataString); - } - return result; - } - /** - * Reads and stores the Trailer headers. - * @throws IOException If an IO problem occurs - */ - private void parseTrailerHeaders() throws IOException { - Header[] footers = null; - try { - String charset = "US-ASCII"; - if (this.method != null) { - charset = this.method.getParams().getHttpElementCharset(); - } - footers = HttpParser.parseHeaders(in, charset); - } catch(HttpException e) { - LOG.error("Error parsing trailer headers", e); - IOException ioe = new IOException(e.getMessage()); - ExceptionUtil.initCause(ioe, e); - throw ioe; - } - if (this.method != null) { - for (int i = 0; i < footers.length; i++) { - this.method.addResponseFooter(footers[i]); - } - } - } - /** - * 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 If an IO problem occurs. - */ - public void close() throws IOException { - if (!closed) { - try { - if (!eof) { - exhaustInputStream(this); - } - } finally { - eof = true; - closed = true; - } - } - } - /** - * Exhaust an input stream, reading until EOF has been encountered. - * - *Note that this function is intended as a non-public utility. - * This is a little weird, but it seemed silly to make a utility - * class for this one function, so instead it is just static and - * shared that way.
- * - * @param inStream The {@link InputStream} to exhaust. - * @throws IOException If an IO problem occurs - */ - static void exhaustInputStream(InputStream inStream) throws IOException { - // read and discard the remainder of the message - byte buffer[] = new byte[1024]; - while (inStream.read(buffer) >= 0) { - ; - } - } diff --git a/clients/java/src/org/apache/commons/httpclient/ChunkedOutputStream.java b/clients/java/src/org/apache/commons/httpclient/ChunkedOutputStream.java deleted file mode 100644 index 4fe20d5..0000000 --- a/clients/java/src/org/apache/commons/httpclient/ChunkedOutputStream.java +++ /dev/null @@ -1,202 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ChunkedOutputStream.java,v 1.16 2004/05/13 04:03:25 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *- * This implementation adds User-Agent , Host , - * and Proxy-Authorization headers, when appropriate. - *
- * - * @param state the client state - * @param conn the {@link HttpConnection} the headers will eventually be - * written to - * @throws IOException when an error occurs writing the request - * @throws HttpException when a HTTP protocol error occurs - * - * @see #writeRequestHeaders - */ - protected void addRequestHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter ConnectMethod.addRequestHeaders(HttpState, " - + "HttpConnection)"); - addUserAgentRequestHeader(state, conn); - addHostRequestHeader(state, conn); - addProxyConnectionHeader(state, conn); - } - /** - * Execute this method and create a tunneled HttpConnection. If the method - * is successful (i.e. the status is a 2xx) tunnelCreated() will be called - * on the connection. - * - * @param state the current http state - * @param conn the connection to write to - * @return the http status code from execution - * @throws HttpException when an error occurs writing the headers - * @throws IOException when an error occurs writing the headers - * - * @see HttpConnection#tunnelCreated() - */ - public int execute(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter ConnectMethod.execute(HttpState, HttpConnection)"); - int code = super.execute(state, conn); - if (LOG.isDebugEnabled()) { - LOG.debug("CONNECT status code " + code); - } - return code; - } - /** - * Special Connect request. - * - * @param state the current http state - * @param conn the connection to write to - * @throws IOException when an error occurs writing the request - * @throws HttpException when an error occurs writing the request - */ - protected void writeRequestLine(HttpState state, HttpConnection conn) - throws IOException, HttpException { - StringBuffer buffer = new StringBuffer(); - buffer.append(getName()); - buffer.append(' '); - if (this.targethost != null) { - buffer.append(getPath()); - } else { - int port = conn.getPort(); - if (port == -1) { - port = conn.getProtocol().getDefaultPort(); - } - buffer.append(conn.getHost()); - buffer.append(':'); - buffer.append(port); - } - buffer.append(" "); - buffer.append(getEffectiveVersion()); - String line = buffer.toString(); - conn.printLine(line, getParams().getHttpElementCharset()); - if (Wire.HEADER_WIRE.enabled()) { - Wire.HEADER_WIRE.output(line); - } - } - /** - * Returns
true
if the status code is anything other than
- * SC_OK,
false
otherwise.
- *
- * @see HttpMethodBase#shouldCloseConnection(HttpConnection)
- * @see HttpStatus#SC_OK
- *
- * @return
true
if the connection should be closed
- */
- protected boolean shouldCloseConnection(HttpConnection conn) {
- if (getStatusCode() == HttpStatus.SC_OK) {
- Header connectionHeader = null;
- if (!conn.isTransparent()) {
- connectionHeader = getResponseHeader("proxy-connection");
- }
- if (connectionHeader == null) {
- connectionHeader = getResponseHeader("connection");
- }
- if (connectionHeader != null) {
- if (connectionHeader.getValue().equalsIgnoreCase("close")) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Invalid header encountered '" + connectionHeader.toExternalForm()
- + "' in response " + getStatusLine().toString());
- }
- }
- }
- return false;
- } else {
- return super.shouldCloseConnection(conn);
- }
- }
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(ConnectMethod.class);
diff --git a/clients/java/src/org/apache/commons/httpclient/ConnectTimeoutException.java b/clients/java/src/org/apache/commons/httpclient/ConnectTimeoutException.java
deleted file mode 100644
index 23695b6..0000000
--- a/clients/java/src/org/apache/commons/httpclient/ConnectTimeoutException.java
+++ /dev/null
@@ -1,76 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ConnectTimeoutException.java,v 1.5 2004/07/05 22:46:58 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
Implementation note: Choices abound. One approach would pass - * through the {@link InputStream#mark} and {@link InputStream#reset} calls to - * the underlying stream. That's tricky, though, because you then have to - * start duplicating the work of keeping track of how much a reset rewinds. - * Further, you have to watch out for the "readLimit", and since the semantics - * for the readLimit leave room for differing implementations, you might get - * into a lot of trouble.
- *Alternatively, you could make this class extend {@link java.io.BufferedInputStream} - * and then use the protected members of that class to avoid duplicated effort. - * That solution has the side effect of adding yet another possible layer of - * buffering.
- *Then, there is the simple choice, which this takes - simply don't - * support {@link InputStream#mark} and {@link InputStream#reset}. That choice - * has the added benefit of keeping this class very simple.
- * @author Ortwin Glueck - * @author Eric Johnson - * @author Mike Bowler - * @since 2.0 -public class ContentLengthInputStream extends InputStream { - /** - * 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 InputStream wrappedStream = null; - /** - * @deprecated use {@link #ContentLengthInputStream(InputStream, long)} - * - * Creates a new length limited stream - * - * @param in The stream to wrap - * @param contentLength The maximum number of bytes that can be read from - * the stream. Subsequent read operations will return -1. - */ - public ContentLengthInputStream(InputStream in, int contentLength) { - this(in, (long)contentLength); - } - /** - * Creates a new length limited stream - * - * @param in The stream to wrap - * @param contentLength The maximum number of bytes that can be read from - * the stream. Subsequent read operations will return -1. - * - * @since 3.0 - */ - public ContentLengthInputStream(InputStream in, long contentLength) { - super(); - this.wrappedStream = in; - this.contentLength = contentLength; - } - /** - *Reads until the end of the known length of content.
- * - *Does not close the underlying socket input, but instead leaves it - * primed to parse the next response.
- * @throws IOException If an IO problem occurs. - */ - public void close() throws IOException { - if (!closed) { - try { - ChunkedInputStream.exhaustInputStream(this); - } finally { - // close after above so that we don't throw an exception trying - // to read after closed! - closed = true; - } - } - } - /** - * 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; - } - pos++; - return this.wrappedStream.read(); - } - /** - * 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.wrappedStream.read(b, off, len); - 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 { - // make sure we don't skip more bytes than are - // still available - long length = Math.min(n, contentLength - pos); - // skip and keep track of the bytes actually skipped - length = this.wrappedStream.skip(length); - // only add the skipped bytes to the current position - // if bytes were actually skipped - if (length > 0) { - pos += length; - } - return length; - } - public int available() throws IOException { - if (this.closed) { - return 0; - } - int avail = this.wrappedStream.available(); - if (this.pos + avail > this.contentLength ) { - avail = (int)(this.contentLength - this.pos); - } - return avail; - } diff --git a/clients/java/src/org/apache/commons/httpclient/Cookie.java b/clients/java/src/org/apache/commons/httpclient/Cookie.java deleted file mode 100644 index 682ff9b..0000000 --- a/clients/java/src/org/apache/commons/httpclient/Cookie.java +++ /dev/null @@ -1,536 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Cookie.java,v 1.44 2004/06/05 16:49:20 olegk Exp $ - * $Revision: 531354 $ - * $Date: 2007-04-23 08:53:20 +0200 (Mon, 23 Apr 2007) $ - * ==================================================================== - * 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 - *Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.
- * @return Expiration {@link Date}, or null . - * - * @see #setExpiryDate(java.util.Date) - * - */ - public Date getExpiryDate() { - return cookieExpiryDate; - } - /** - * Sets expiration date. - *Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.
- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - public void setExpiryDate (Date expiryDate) { - cookieExpiryDate = expiryDate; - } - /** - * Returns false if the cookie should be discarded at the end - * of the "session"; true otherwise. - * - * @return false if the cookie should be discarded at the end - * of the "session"; true otherwise - */ - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - public String getDomain() { - return cookieDomain; - } - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - public void setDomain(String domain) { - if (domain != null) { - int ndx = domain.indexOf(":"); - if (ndx != -1) { - domain = domain.substring(0, ndx); - } - cookieDomain = domain.toLowerCase(); - } - } - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - public String getPath() { - return cookiePath; - } - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - public void setPath(String path) { - cookiePath = path; - } - /** - * @return
true
if this cookie should only be sent over secure connections.
- * @see #setSecure(boolean)
- */
- public boolean getSecure() {
- return isSecure;
- }
- /**
- * Sets the secure attribute of the cookie.
- *
- * When true the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #getSecure() - */ - public void setSecure (boolean secure) { - isSecure = secure; - } - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - public int getVersion() { - return cookieVersion; - } - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - public void setVersion(int version) { - cookieVersion = version; - } - /** - * Returns true if this cookie has expired. - * - * @return true if the cookie has expired. - */ - public boolean isExpired() { - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= System.currentTimeMillis()); - } - /** - * Returns true if this cookie has expired according to the time passed in. - * - * @param now The current time. - * - * @return true if the cookie expired. - */ - public boolean isExpired(Date now) { - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= now.getTime()); - } - /** - * Indicates whether the cookie had a path specified in a - * path attribute of the Set-Cookie header. This value - * is important for generating the Cookie header because - * some cookie specifications require that the Cookie header - * should only include a path attribute if the cookie's path - * was specified in the Set-Cookie header. - * - * @param value true if the cookie's path was explicitly - * set, false otherwise. - * - * @see #isPathAttributeSpecified - */ - public void setPathAttributeSpecified(boolean value) { - hasPathAttribute = value; - } - /** - * Returns true if cookie's path was set via a path attribute - * in the Set-Cookie header. - * - * @return value true if the cookie's path was explicitly - * set, false otherwise. - * - * @see #setPathAttributeSpecified - */ - public boolean isPathAttributeSpecified() { - return hasPathAttribute; - } - /** - * Indicates whether the cookie had a domain specified in a - * domain attribute of the Set-Cookie header. This value - * is important for generating the Cookie header because - * some cookie specifications require that the Cookie header - * should only include a domain attribute if the cookie's domain - * was specified in the Set-Cookie header. - * - * @param value true if the cookie's domain was explicitly - * set, false otherwise. - * - * @see #isDomainAttributeSpecified - */ - public void setDomainAttributeSpecified(boolean value) { - hasDomainAttribute = value; - } - /** - * Returns true if cookie's domain was set via a domain - * attribute in the Set-Cookie header. - * - * @return value true if the cookie's domain was explicitly - * set, false otherwise. - * - * @see #setDomainAttributeSpecified - */ - public boolean isDomainAttributeSpecified() { - return hasDomainAttribute; - } - /** - * Returns a hash code in keeping with the - * {@link Object#hashCode} general hashCode contract. - * @return A hash code - */ - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.getName()); - hash = LangUtils.hashCode(hash, this.cookieDomain); - hash = LangUtils.hashCode(hash, this.cookiePath); - return hash; - } - /** - * Two cookies are equal if the name, path and domain match. - * @param obj The object to compare against. - * @return true if the two objects are equal. - */ - public boolean equals(Object obj) { - if (obj == null) return false; - if (this == obj) return true; - if (obj instanceof Cookie) { - Cookie that = (Cookie) obj; - return LangUtils.equals(this.getName(), that.getName()) - && LangUtils.equals(this.cookieDomain, that.cookieDomain) - && LangUtils.equals(this.cookiePath, that.cookiePath); - } else { - return false; - } - } - /** - * Return a textual representation of the cookie. - * - * @return string. - */ - public String toExternalForm() { - CookieSpec spec = null; - if (getVersion() > 0) { - spec = CookiePolicy.getDefaultSpec(); - } else { - spec = CookiePolicy.getCookieSpec(CookiePolicy.NETSCAPE); - } - return spec.formatCookie(this); - } - /** - *
Compares two cookies to determine order for cookie header.
- *Most specific should be first.
- *This method is implemented so a cookie can be used as a comparator for - * a SortedSet of cookies. Specifically it's used above in the - * createCookieHeader method.
- * @param o1 The first object to be compared - * @param o2 The second object to be compared - * @return See {@link java.util.Comparator#compare(Object,Object)} - */ - public int compare(Object o1, Object o2) { - LOG.trace("enter Cookie.compare(Object, Object)"); - if (!(o1 instanceof Cookie)) { - throw new ClassCastException(o1.getClass().getName()); - } - if (!(o2 instanceof Cookie)) { - throw new ClassCastException(o2.getClass().getName()); - } - Cookie c1 = (Cookie) o1; - Cookie c2 = (Cookie) o2; - if (c1.getPath() == null && c2.getPath() == null) { - return 0; - } else if (c1.getPath() == null) { - // null is assumed to be "/" - if (c2.getPath().equals(CookieSpec.PATH_DELIM)) { - return 0; - } else { - return -1; - } - } else if (c2.getPath() == null) { - // null is assumed to be "/" - if (c1.getPath().equals(CookieSpec.PATH_DELIM)) { - return 0; - } else { - return 1; - } - } else { - return c1.getPath().compareTo(c2.getPath()); - } - } - /** - * Return a textual representation of the cookie. - * - * @return string. - * - * @see #toExternalForm - */ - public String toString() { - return toExternalForm(); - } - // ----------------------------------------------------- Instance Variables - /** Comment attribute. */ - private String cookieComment; - /** Domain attribute. */ - private String cookieDomain; - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - /** Path attribute. */ - private String cookiePath; - /** My secure flag. */ - private boolean isSecure; - /** - * Specifies if the set-cookie header included a Path attribute for this - * cookie - */ - private boolean hasPathAttribute = false; - /** - * Specifies if the set-cookie header included a Domain attribute for this - * cookie - */ - private boolean hasDomainAttribute = false; - /** The version of the cookie specification I was created from. */ - private int cookieVersion = 0; - // -------------------------------------------------------------- Constants - /** Log object for this class */ - private static final Log LOG = LogFactory.getLog(Cookie.class); diff --git a/clients/java/src/org/apache/commons/httpclient/Credentials.java b/clients/java/src/org/apache/commons/httpclient/Credentials.java deleted file mode 100644 index eaa5ff5..0000000 --- a/clients/java/src/org/apache/commons/httpclient/Credentials.java +++ /dev/null @@ -1,44 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Credentials.java,v 1.9 2004/04/18 23:51:34 jsdever Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *Authentication credentials.
- * This is just a marker interface, the current implementation has no methods. - * @author Unascribed - * @author Mike Bowler - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ -public interface Credentials { diff --git a/clients/java/src/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java b/clients/java/src/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java deleted file mode 100644 index 9321a37..0000000 --- a/clients/java/src/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java +++ /dev/null @@ -1,148 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/DefaultHttpMethodRetryHandler.java,v 1.3 2004/12/20 11:47:46 olegk Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
retryCount
and
requestSentRetryEnabled
to determine
- * if the given method should be retried.
- *
- * @see HttpMethodRetryHandler#retryMethod(HttpMethod, IOException, int)
- */
- public boolean retryMethod(
- final HttpMethod method,
- final IOException exception,
- int executionCount) {
- if (method == null) {
- throw new IllegalArgumentException("HTTP method may not be null");
- }
- if (exception == null) {
- throw new IllegalArgumentException("Exception parameter may not be null");
- }
- // HttpMethod interface is the WORST thing ever done to HttpClient
- if (method instanceof HttpMethodBase) {
- if (((HttpMethodBase)method).isAborted()) {
- return false;
- }
- }
- if (executionCount > this.retryCount) {
- // Do not retry if over max retry count
- return false;
- }
- if (exception instanceof NoHttpResponseException) {
- // Retry if the server dropped connection on us
- return true;
- }
- if (exception instanceof InterruptedIOException) {
- // Timeout
- return false;
- }
- if (exception instanceof UnknownHostException) {
- // Unknown host
- return false;
- }
- if (exception instanceof NoRouteToHostException) {
- // Host unreachable
- return false;
- }
- if (SSL_HANDSHAKE_EXCEPTION != null && SSL_HANDSHAKE_EXCEPTION.isInstance(exception)) {
- // SSL handshake exception
- return false;
- }
- if (!method.isRequestSent() || this.requestSentRetryEnabled) {
- // Retry if the request has not been sent fully or
- // if it's OK to retry methods that have been sent
- return true;
- }
- // otherwise do not retry
- return false;
- }
- /**
- * @return
true
if this handler will retry methods that have
- * successfully sent their request,
false
otherwise
- */
- public boolean isRequestSentRetryEnabled() {
- return requestSentRetryEnabled;
- }
- /**
- * @return the maximum number of times a method will be retried
- */
- public int getRetryCount() {
- return retryCount;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/DefaultMethodRetryHandler.java b/clients/java/src/org/apache/commons/httpclient/DefaultMethodRetryHandler.java
deleted file mode 100644
index 5be321f..0000000
--- a/clients/java/src/org/apache/commons/httpclient/DefaultMethodRetryHandler.java
+++ /dev/null
@@ -1,102 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/DefaultMethodRetryHandler.java,v 1.4 2004/07/05 22:46:58 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
retryCount
and
requestSentRetryEnabled
to determine
- * if the given method should be retried.
- *
- * @see MethodRetryHandler#retryMethod(HttpMethod, HttpConnection, HttpRecoverableException, int, boolean)
- */
- public boolean retryMethod(
- HttpMethod method,
- HttpConnection connection,
- HttpRecoverableException recoverableException,
- int executionCount,
- boolean requestSent
- ) {
- return ((!requestSent || requestSentRetryEnabled) && (executionCount <= retryCount));
- }
- /**
- * @return
true
if this handler will retry methods that have
- * successfully sent their request,
false
otherwise
- */
- public boolean isRequestSentRetryEnabled() {
- return requestSentRetryEnabled;
- }
- /**
- * @return the maximum number of times a method will be retried
- */
- public int getRetryCount() {
- return retryCount;
- }
- /**
- * @param requestSentRetryEnabled a flag indicating if methods that have
- * successfully sent their request should be retried
- */
- public void setRequestSentRetryEnabled(boolean requestSentRetryEnabled) {
- this.requestSentRetryEnabled = requestSentRetryEnabled;
- }
- /**
- * @param retryCount the maximum number of times a method can be retried
- */
- public void setRetryCount(int retryCount) {
- this.retryCount = retryCount;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/Header.java b/clients/java/src/org/apache/commons/httpclient/Header.java
deleted file mode 100644
index 05edb16..0000000
--- a/clients/java/src/org/apache/commons/httpclient/Header.java
+++ /dev/null
@@ -1,145 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Header.java,v 1.17 2004/09/15 20:42:17 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
An HTTP header.
- * @author Remy Maucherat - * @author Mike Bowler - * @author Oleg Kalnichevski - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ -public class Header extends NameValuePair { - // ----------------------------------------------------------- Constructors - /** - * Autogenerated header flag. - */ - private boolean isAutogenerated = false; - /** - * Default constructor. - */ - public Header() { - this(null, null); - } - /** - * Constructor with name and value - * - * @param name the header name - * @param value the header value - */ - public Header(String name, String value) { - super(name, value); - } - /** - * Constructor with name and value - * - * @param name the header name - * @param value the header value - * @param isAutogenerated true if the header is autogenerated, - * false otherwise. - * - * @since 3.0 - */ - public Header(String name, String value, boolean isAutogenerated) { - super(name, value); - this.isAutogenerated = isAutogenerated; - } - // --------------------------------------------------------- Public Methods - /** - * Returns a {@link String} representation of the header. - * - * @return stringHEAD - */ - public String toExternalForm() { - return ((null == getName() ? "" : getName()) - + ": " - + (null == getValue() ? "" : getValue()) - + "\r\n"); - } - /** - * Returns a {@link String} representation of the header. - * - * @return stringHEAD - */ - public String toString() { - return toExternalForm(); - } - /** - * Returns an array of {@link HeaderElement}s - * constructed from my value. - * - * @see HeaderElement#parse - * @throws HttpException if the header cannot be parsed - * @return an array of header elements - * - * @deprecated Use #getElements - */ - public HeaderElement[] getValues() throws HttpException { - return HeaderElement.parse(getValue()); - } - /** - * Returns an array of {@link HeaderElement}s - * constructed from my value. - * - * @see HeaderElement#parseElements(String) - * - * @return an array of header elements - * - * @since 3.0 - */ - public HeaderElement[] getElements() { - return HeaderElement.parseElements(getValue()); - } - /** - * Returns the value of the auto-generated header flag. - * - * @return true if the header is autogenerated, - * false otherwise. - * - * @since 3.0 - */ - public boolean isAutogenerated() { - return isAutogenerated; - } diff --git a/clients/java/src/org/apache/commons/httpclient/HeaderElement.java b/clients/java/src/org/apache/commons/httpclient/HeaderElement.java deleted file mode 100644 index 44f8cfb..0000000 --- a/clients/java/src/org/apache/commons/httpclient/HeaderElement.java +++ /dev/null @@ -1,299 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderElement.java,v 1.23 2004/05/13 04:03:25 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *One element of an HTTP header's value.
- * 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: - * 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 - * 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 null will be stored instead. - * This class represents an individual header element, containing - * both a name/value pair (value may be null ) and optionally - * a set of additional parameters. - * This class also exposes a {@link #parse} method for parsing a - * {@link Header} value into an array of elements. - * @see Header - * @author B.C. Holmes - * @author Park, Sung-Gu - * @author Mike Bowler - * @author Oleg Kalnichevski - * @since 1.0 - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ -public class HeaderElement extends NameValuePair { - // ----------------------------------------------------------- Constructors - /** - * Default constructor. - */ - public HeaderElement() { - this(null, null, null); - } - /** - * Constructor. - * @param name my name - * @param value my (possibly null ) value - */ - public HeaderElement(String name, String value) { - this(name, value, null); - } - /** - * Constructor with name, value and parameters. - * - * @param name my name - * @param value my (possibly null ) value - * @param parameters my (possibly null ) parameters - */ - public HeaderElement(String name, String value, - NameValuePair[] parameters) { - super(name, value); - this.parameters = parameters; - } - /** - * Constructor with array of characters. - * - * @param chars the array of characters - * @param offset - the initial offset. - * @param length - the length. - * - * @since 3.0 - */ - public HeaderElement(char[] chars, int offset, int length) { - this(); - if (chars == null) { - return; - } - ParameterParser parser = new ParameterParser(); - List params = parser.parse(chars, offset, length, ';'); - if (params.size() > 0) { - NameValuePair element = (NameValuePair) params.remove(0); - setName(element.getName()); - setValue(element.getValue()); - if (params.size() > 0) { - this.parameters = (NameValuePair[]) - params.toArray(new NameValuePair[params.size()]); - } - } - } - /** - * Constructor with array of characters. - * - * @param chars the array of characters - * - * @since 3.0 - */ - public HeaderElement(char[] chars) { - this(chars, 0, chars.length); - } - // -------------------------------------------------------- Constants - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(HeaderElement.class); - // ----------------------------------------------------- Instance Variables - /** My parameters, if any. */ - private NameValuePair[] parameters = null; - // ------------------------------------------------------------- Properties - /** - * Get parameters, if any. - * - * @since 2.0 - * @return parameters as an array of {@link NameValuePair}s - */ - public NameValuePair[] getParameters() { - return this.parameters; - } - // --------------------------------------------------------- Public Methods - /** - * This parses the value part of a header. The result is an array of - * HeaderElement objects. - * - * @param headerValue the array of char representation of the header value - * (as received from the web server). - * @return array of {@link HeaderElement}s. - * - * @since 3.0 - */ - public static final HeaderElement[] parseElements(char[] headerValue) { - LOG.trace("enter HeaderElement.parseElements(char[])"); - if (headerValue == null) { - return new HeaderElement[] {}; - } - List elements = new ArrayList(); - int i = 0; - int from = 0; - int len = headerValue.length; - boolean qouted = false; - while (i < len) { - char ch = headerValue[i]; - if (ch == '"') { - qouted = !qouted; - } - HeaderElement element = null; - if ((!qouted) && (ch == ',')) { - element = new HeaderElement(headerValue, from, i); - from = i + 1; - } else if (i == len - 1) { - element = new HeaderElement(headerValue, from, len); - } - if ((element != null) && (element.getName() != null)) { - elements.add(element); - } - i++; - } - return (HeaderElement[]) - elements.toArray(new HeaderElement[elements.size()]); - } - /** - * This parses the value part of a header. The result is an array of - * HeaderElement objects. - * - * @param headerValue the string representation of the header value - * (as received from the web server). - * @return array of {@link HeaderElement}s. - * - * @since 3.0 - */ - public static final HeaderElement[] parseElements(String headerValue) { - LOG.trace("enter HeaderElement.parseElements(String)"); - if (headerValue == null) { - return new HeaderElement[] {}; - } - return parseElements(headerValue.toCharArray()); - } - /** - * This parses the value part of a header. The result is an array of - * HeaderElement objects. - * - * @param headerValue the string representation of the header value - * (as received from the web server). - * @return array of {@link HeaderElement}s. - * @throws HttpException if the above syntax rules are violated. - * - * @deprecated Use #parseElements(String). - */ - public static final HeaderElement[] parse(String headerValue) - throws HttpException { - LOG.trace("enter HeaderElement.parse(String)"); - if (headerValue == null) { - return new HeaderElement[] {}; - } - return parseElements(headerValue.toCharArray()); - } - /** - * Returns parameter with the given name, if found. Otherwise null - * is returned - * - * @param name The name to search by. - * @return NameValuePair parameter with the given name - */ - public NameValuePair getParameterByName(String name) { - LOG.trace("enter HeaderElement.getParameterByName(String)"); - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - NameValuePair found = null; - NameValuePair parameters[] = getParameters(); - if (parameters != null) { - for (int i = 0; i < parameters.length; i++) { - NameValuePair current = parameters[ i ]; - if (current.getName().equalsIgnoreCase(name)) { - found = current; - break; - } - } - } - return found; - } diff --git a/clients/java/src/org/apache/commons/httpclient/HeaderGroup.java b/clients/java/src/org/apache/commons/httpclient/HeaderGroup.java deleted file mode 100644 index b9246bd..0000000 --- a/clients/java/src/org/apache/commons/httpclient/HeaderGroup.java +++ /dev/null @@ -1,230 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HeaderGroup.java,v 1.8 2004/05/13 04:03:25 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
Header name comparison is case insensitive.
- *
- * @param name the name of the header(s) to get
- * @return a header with a condensed value or
null
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 new Header(headers[0].getName(), headers[0].getValue());
- } else {
- StringBuffer valueBuffer = new StringBuffer(headers[0].getValue());
- for (int i = 1; i < headers.length; i++) {
- valueBuffer.append(", ");
- valueBuffer.append(headers[i].getValue());
- }
- return new Header(name.toLowerCase(), valueBuffer.toString());
- }
- }
- /**
- * Gets all of the headers with the given name. The returned array
- * maintains the relative order in which the headers were added.
- *
- *
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 (Iterator headerIter = headers.iterator(); headerIter.hasNext();) { - Header header = (Header) headerIter.next(); - if (header.getName().equalsIgnoreCase(name)) { - headersFound.add(header); - } - } - return (Header[]) headersFound.toArray(new Header[headersFound.size()]); - } - /** - * Gets the first header with the given name. - * - *
Header name comparison is case insensitive.
- *
- * @param name the name of the header to get
- * @return the first header or
null
- */
- public Header getFirstHeader(String name) {
- for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
- Header header = (Header) headerIter.next();
- if (header.getName().equalsIgnoreCase(name)) {
- return header;
- }
- }
- return null;
- }
- /**
- * Gets the last header with the given name.
- *
- *
Header name comparison is case insensitive.
- *
- * @param name the name of the header to get
- * @return the last header or
null
- */
- 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.
- *
- *
Header name comparison is case insensitive.
- *
- * @param name the header name to test for
- * @return
true
if at least one header with the name is
- * contained,
false
otherwise
- */
- public boolean containsHeader(String name) {
- for (Iterator headerIter = headers.iterator(); headerIter.hasNext();) {
- Header header = (Header) headerIter.next();
- 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 3.0
- */
- public Iterator getIterator() {
- return this.headers.iterator();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HostConfiguration.java b/clients/java/src/org/apache/commons/httpclient/HostConfiguration.java
deleted file mode 100644
index 8cc8b9e..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HostConfiguration.java
+++ /dev/null
@@ -1,526 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HostConfiguration.java,v 1.23 2005/01/14 21:16:40 olegk Exp $
- * $Revision: 510585 $
- * $Date: 2007-02-22 17:52:16 +0100 (Thu, 22 Feb 2007) $
- * ====================================================================
- * 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
- *
null
. This value should be treated as immutable and only used in
- * lookups and other such places to represent "any" host config.
- */
- public static final HostConfiguration ANY_HOST_CONFIGURATION = new HostConfiguration();
- /** The host to use. */
- private HttpHost host = null;
- /** The host name of the proxy server */
- private ProxyHost proxyHost = null;
- /** The local address to use when creating the socket, or null to use the default */
- private InetAddress localAddress = null;
- /** Parameters specific to this host */
- private HostParams params = new HostParams();
- /**
- * Constructor for HostConfiguration.
- */
- public HostConfiguration() {
- super();
- }
- /**
- * Copy constructor for HostConfiguration
- *
- * @param hostConfiguration the hostConfiguration to copy
- */
- public HostConfiguration (final HostConfiguration hostConfiguration) {
- init(hostConfiguration);
- }
- private void init(final HostConfiguration hostConfiguration) {
- // wrap all of the assignments in a synchronized block to avoid
- // having to negotiate the monitor for each method call
- synchronized (hostConfiguration) {
- try {
- if (hostConfiguration.host != null) {
- this.host = (HttpHost) hostConfiguration.host.clone();
- } else {
- this.host = null;
- }
- if (hostConfiguration.proxyHost != null) {
- this.proxyHost = (ProxyHost) hostConfiguration.proxyHost.clone();
- } else {
- this.proxyHost = null;
- }
- this.localAddress = hostConfiguration.getLocalAddress();
- this.params = (HostParams)hostConfiguration.getParams().clone();
- } catch (CloneNotSupportedException e) {
- throw new IllegalArgumentException("Host configuration could not be cloned");
- }
- }
- }
- /**
- * @see java.lang.Object#clone()
- */
- public Object clone() {
- HostConfiguration copy;
- try {
- copy = (HostConfiguration) super.clone();
- } catch (CloneNotSupportedException e) {
- throw new IllegalArgumentException("Host configuration could not be cloned");
- }
- copy.init(this);
- return copy;
- }
- /**
- * @see java.lang.Object#toString()
- */
- public synchronized String toString() {
- boolean appendComma = false;
- StringBuffer b = new StringBuffer(50);
- b.append("HostConfiguration[");
- if (this.host != null) {
- appendComma = true;
- b.append("host=").append(this.host);
- }
- if (this.proxyHost != null) {
- if (appendComma) {
- b.append(", ");
- } else {
- appendComma = true;
- }
- b.append("proxyHost=").append(this.proxyHost);
- }
- if (this.localAddress != null) {
- if (appendComma) {
- b.append(", ");
- } else {
- appendComma = true;
- }
- b.append("localAddress=").append(this.localAddress);
- if (appendComma) {
- b.append(", ");
- } else {
- appendComma = true;
- }
- b.append("params=").append(this.params);
- }
- b.append("]");
- return b.toString();
- }
- /**
- * Tests if the host configuration equals the configuration set on the
- * connection. True only if the host, port, protocol, local address and virtual address
- * are equal. If no host configuration has been set false will be returned.
- *
- * @param connection the connection to test against
- * @return
true
if the connection's host information equals that of this
- * configuration
- *
- * @see #proxyEquals(HttpConnection)
- */
- public synchronized boolean hostEquals(final HttpConnection connection) {
- if (connection == null) {
- throw new IllegalArgumentException("Connection may not be null");
- }
- if (this.host != null) {
- if (!this.host.getHostName().equalsIgnoreCase(connection.getHost())) {
- return false;
- }
- if (this.host.getPort() != connection.getPort()) {
- return false;
- }
- if (!this.host.getProtocol().equals(connection.getProtocol())) {
- return false;
- }
- if (this.localAddress != null) {
- if (!this.localAddress.equals(connection.getLocalAddress())) {
- return false;
- }
- } else {
- if (connection.getLocalAddress() != null) {
- return false;
- }
- }
- return true;
- } else {
- return false;
- }
- }
- /**
- * Tests if the proxy configuration equals the configuration set on the
- * connection. True only if the proxyHost and proxyPort are equal.
- *
- * @param connection the connection to test against
- * @return
true
if the connection's proxy information equals that of this
- * configuration
- *
- * @see #hostEquals(HttpConnection)
- */
- public synchronized boolean proxyEquals(final HttpConnection connection) {
- if (connection == null) {
- throw new IllegalArgumentException("Connection may not be null");
- }
- if (this.proxyHost != null) {
- return
- this.proxyHost.getHostName().equalsIgnoreCase(connection.getProxyHost())
- && this.proxyHost.getPort() == connection.getProxyPort();
- } else {
- return connection.getProxyHost() == null;
- }
- }
- /**
- * Returns true if the host is set.
- * @return
true
if the host is set.
- *
- * @deprecated no longer used
- */
- public synchronized boolean isHostSet() {
- return this.host != null;
- }
- /**
- * Sets the given host
- *
- * @param host the host
- */
- public synchronized void setHost(final HttpHost host) {
- this.host = host;
- }
- /**
- * Sets the given host, port and protocol
- *
- * @param host the host(IP or DNS name)
- * @param port The port
- * @param protocol The protocol.
- */
- public synchronized void setHost(final String host, int port, final String protocol) {
- this.host = new HttpHost(host, port, Protocol.getProtocol(protocol));
- }
- /**
- * Sets the given host, virtual host, port and protocol.
- *
- * @param host the host(IP or DNS name)
- * @param virtualHost the virtual host name or
null
- * @param port the host port or -1 to use protocol default
- * @param protocol the protocol
- *
- * @deprecated #setHost(String, int, Protocol)
- */
- public synchronized void setHost(final String host, final String virtualHost, int port,
- final Protocol protocol) {
- setHost(host, port, protocol);
- this.params.setVirtualHost(virtualHost);
- }
- /**
- * Sets the given host, port and protocol.
- *
- * @param host the host(IP or DNS name)
- * @param port The port
- * @param protocol the protocol
- */
- public synchronized void setHost(final String host, int port, final Protocol protocol) {
- if (host == null) {
- throw new IllegalArgumentException("host must not be null");
- }
- if (protocol == null) {
- throw new IllegalArgumentException("protocol must not be null");
- }
- this.host = new HttpHost(host, port, protocol);
- }
- /**
- * Sets the given host and port. Uses the default protocol "http".
- *
- * @param host the host(IP or DNS name)
- * @param port The port
- */
- public synchronized void setHost(final String host, int port) {
- setHost(host, port, Protocol.getProtocol("http"));
- }
- /**
- * Set the given host. Uses the default protocol("http") and its port.
- *
- * @param host The host(IP or DNS name).
- */
- public synchronized void setHost(final String host) {
- Protocol defaultProtocol = Protocol.getProtocol("http");
- setHost(host, defaultProtocol.getDefaultPort(), defaultProtocol);
- }
- /**
- * Sets the protocol, host and port from the given URI.
- * @param uri the URI.
- */
- public synchronized void setHost(final URI uri) {
- try {
- setHost(uri.getHost(), uri.getPort(), uri.getScheme());
- } catch (URIException e) {
- throw new IllegalArgumentException(e.toString());
- }
- }
- /**
- * Return the host url.
- *
- * @return The host url.
- */
- public synchronized String getHostURL() {
- if (this.host == null) {
- throw new IllegalStateException("Host must be set to create a host URL");
- } else {
- return this.host.toURI();
- }
- }
- /**
- * Returns the host.
- *
- * @return the host(IP or DNS name), or
null
if not set
- *
- * @see #isHostSet()
- */
- public synchronized String getHost() {
- if (this.host != null) {
- return this.host.getHostName();
- } else {
- return null;
- }
- }
- /**
- * Returns the virtual host.
- *
- * @return the virtual host name, or
null
if not set
- *
- * @deprecated use HostParams
- */
- public synchronized String getVirtualHost() {
- return this.params.getVirtualHost();
- }
- /**
- * Returns the port.
- *
- * @return the host port, or
-1
if not set
- *
- * @see #isHostSet()
- */
- public synchronized int getPort() {
- if (this.host != null) {
- return this.host.getPort();
- } else {
- return -1;
- }
- }
- /**
- * Returns the protocol.
- * @return The protocol.
- */
- public synchronized Protocol getProtocol() {
- if (this.host != null) {
- return this.host.getProtocol();
- } else {
- return null;
- }
- }
- /**
- * Tests if the proxy host/port have been set.
- *
- * @return
true
if a proxy server has been set.
- *
- * @see #setProxy(String, int)
- *
- * @deprecated no longer used
- */
- public synchronized boolean isProxySet() {
- return this.proxyHost != null;
- }
- /**
- * Sets the given proxy host
- *
- * @param proxyHost the proxy host
- */
- public synchronized void setProxyHost(final ProxyHost proxyHost) {
- this.proxyHost = proxyHost;
- }
- /**
- * Set the proxy settings.
- * @param proxyHost The proxy host
- * @param proxyPort The proxy port
- */
- public synchronized void setProxy(final String proxyHost, int proxyPort) {
- this.proxyHost = new ProxyHost(proxyHost, proxyPort);
- }
- /**
- * Returns the proxyHost.
- *
- * @return the proxy host, or
null
if not set
- *
- * @see #isProxySet()
- */
- public synchronized String getProxyHost() {
- if (this.proxyHost != null) {
- return this.proxyHost.getHostName();
- } else {
- return null;
- }
- }
- /**
- * Returns the proxyPort.
- *
- * @return the proxy port, or
-1
if not set
- *
- * @see #isProxySet()
- */
- public synchronized int getProxyPort() {
- if (this.proxyHost != null) {
- return this.proxyHost.getPort();
- } else {
- return -1;
- }
- }
- /**
- * Set the local address to be used when creating connections.
- * If this is unset, the default address will be used.
- * This is useful for specifying the interface to use on multi-homed or clustered systems.
- *
- * @param localAddress the local address to use
- */
- public synchronized void setLocalAddress(InetAddress localAddress) {
- this.localAddress = localAddress;
- }
- /**
- * Return the local address to be used when creating connections.
- * If this is unset, the default address should be used.
- *
- * @return the local address to be used when creating Sockets, or
null
- */
- public synchronized InetAddress getLocalAddress() {
- return this.localAddress;
- }
- /**
- * Returns {@link HostParams HTTP protocol parameters} associated with this host.
- *
- * @return HTTP parameters.
- *
- * @since 3.0
- */
- public HostParams getParams() {
- return this.params;
- }
- /**
- * Assigns {@link HostParams HTTP protocol parameters} specific to this host.
- *
- * @since 3.0
- *
- * @see HostParams
- */
- public void setParams(final HostParams params) {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- this.params = params;
- }
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public synchronized boolean equals(final Object o) {
- if (o instanceof HostConfiguration) {
- // shortcut if we're comparing with ourselves
- if (o == this) {
- return true;
- }
- HostConfiguration that = (HostConfiguration) o;
- return LangUtils.equals(this.host, that.host)
- && LangUtils.equals(this.proxyHost, that.proxyHost)
- && LangUtils.equals(this.localAddress, that.localAddress);
- } else {
- return false;
- }
- }
- /**
- * @see java.lang.Object#hashCode()
- */
- public synchronized int hashCode() {
- int hash = LangUtils.HASH_SEED;
- hash = LangUtils.hashCode(hash, this.host);
- hash = LangUtils.hashCode(hash, this.proxyHost);
- hash = LangUtils.hashCode(hash, this.localAddress);
- return hash;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpClient.java b/clients/java/src/org/apache/commons/httpclient/HttpClient.java
deleted file mode 100644
index b9ed99d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpClient.java
+++ /dev/null
@@ -1,502 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpClient.java,v 1.98 2004/10/07 16:14:15 olegk Exp $
- * $Revision: 509577 $
- * $Date: 2007-02-20 15:28:18 +0100 (Tue, 20 Feb 2007) $
- * ====================================================================
- * 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
- *
null
, the host configuration returned by {@link #getHostConfiguration} will be used.
- * @param method the {@link HttpMethod HTTP method} to execute.
- * @return the method's response code
- *
- * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
- * can be recovered from.
- * @throws HttpException If a protocol exception occurs. Usually protocol exceptions
- * cannot be recovered from.
- * @since 2.0
- */
- public int executeMethod(final HostConfiguration hostConfiguration, final HttpMethod method)
- throws IOException, HttpException {
- LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod)");
- return executeMethod(hostConfiguration, method, null);
- }
- /**
- * Executes the given {@link HttpMethod HTTP method} using the given custom
- * {@link HostConfiguration host configuration} with the given custom
- * {@link HttpState HTTP state}.
- *
- * @param hostconfig The {@link HostConfiguration host configuration} to use.
- * If
null
, the host configuration returned by {@link #getHostConfiguration} will be used.
- * @param method the {@link HttpMethod HTTP method} to execute.
- * @param state the {@link HttpState HTTP state} to use when executing the method.
- * If
null
, the state returned by {@link #getState} will be used.
- *
- * @return the method's response code
- *
- * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
- * can be recovered from.
- * @throws HttpException If a protocol exception occurs. Usually protocol exceptions
- * cannot be recovered from.
- * @since 2.0
- */
- public int executeMethod(HostConfiguration hostconfig,
- final HttpMethod method, final HttpState state)
- throws IOException, HttpException {
- LOG.trace("enter HttpClient.executeMethod(HostConfiguration,HttpMethod,HttpState)");
- if (method == null) {
- throw new IllegalArgumentException("HttpMethod parameter may not be null");
- }
- HostConfiguration defaulthostconfig = getHostConfiguration();
- if (hostconfig == null) {
- hostconfig = defaulthostconfig;
- }
- URI uri = method.getURI();
- if (hostconfig == defaulthostconfig || uri.isAbsoluteURI()) {
- // make a deep copy of the host defaults
- hostconfig = (HostConfiguration) hostconfig.clone();
- if (uri.isAbsoluteURI()) {
- hostconfig.setHost(uri);
- }
- }
- HttpMethodDirector methodDirector = new HttpMethodDirector(
- getHttpConnectionManager(),
- hostconfig,
- this.params,
- (state == null ? getState() : state));
- methodDirector.executeMethod(method);
- return method.getStatusCode();
- }
- /**
- * Returns the default host.
- *
- * @return The default host.
- *
- * @deprecated use #getHostConfiguration()
- */
- public String getHost() {
- return hostConfiguration.getHost();
- }
- /**
- * Returns the default port.
- *
- * @return The default port.
- *
- * @deprecated use #getHostConfiguration()
- */
- public int getPort() {
- return hostConfiguration.getPort();
- }
- /**
- * Returns the {@link HostConfiguration host configuration} associated with the
- * HttpClient.
- *
- * @return {@link HostConfiguration host configuration}
- *
- * @since 2.0
- */
- public synchronized HostConfiguration getHostConfiguration() {
- return hostConfiguration;
- }
- /**
- * Assigns the {@link HostConfiguration host configuration} to use with the
- * HttpClient.
- *
- * @param hostConfiguration The {@link HostConfiguration host configuration} to set
- *
- * @since 2.0
- */
- public synchronized void setHostConfiguration(HostConfiguration hostConfiguration) {
- this.hostConfiguration = hostConfiguration;
- }
- /**
- * Returns the {@link HttpConnectionManager HTTP connection manager} associated
- * with the HttpClient.
- *
- * @return {@link HttpConnectionManager HTTP connection manager}
- *
- * @since 2.0
- */
- public synchronized HttpConnectionManager getHttpConnectionManager() {
- return httpConnectionManager;
- }
- /**
- * Assigns the {@link HttpConnectionManager HTTP connection manager} to use with
- * the HttpClient.
- *
- * @param httpConnectionManager The {@link HttpConnectionManager HTTP connection manager}
- * to set
- *
- * @since 2.0
- */
- public synchronized void setHttpConnectionManager(
- HttpConnectionManager httpConnectionManager
- ) {
- this.httpConnectionManager = httpConnectionManager;
- if (this.httpConnectionManager != null) {
- this.httpConnectionManager.getParams().setDefaults(this.params);
- }
- }
- /**
- * Returns {@link HttpClientParams HTTP protocol parameters} associated with this HttpClient.
- *
- * @since 3.0
- *
- * @see HttpClientParams
- */
- public HttpClientParams getParams() {
- return this.params;
- }
- /**
- * Assigns {@link HttpClientParams HTTP protocol parameters} for this HttpClient.
- *
- * @since 3.0
- *
- * @see HttpClientParams
- */
- public void setParams(final HttpClientParams params) {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- this.params = params;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpClientError.java b/clients/java/src/org/apache/commons/httpclient/HttpClientError.java
deleted file mode 100644
index c82397b..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpClientError.java
+++ /dev/null
@@ -1,57 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpClientError.java,v 1.4 2004/05/13 04:03:25 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
true
if the connection is open
- */
- public boolean isOpen() {
- return isOpen;
- }
- /**
- * Closes the connection if stale.
- *
- * @return
true
if the connection was stale and therefore closed,
- *
false
otherwise.
- *
- * @see #isStale()
- *
- * @since 3.0
- */
- public boolean closeIfStale() throws IOException {
- if (isOpen && isStale()) {
- LOG.debug("Connection is stale, closing...");
- close();
- return true;
- }
- return false;
- }
- /**
- * Tests if stale checking is enabled.
- *
- * @return
true
if enabled
- *
- * @see #isStale()
- *
- * @deprecated Use {@link HttpConnectionParams#isStaleCheckingEnabled()},
- * {@link HttpConnection#getParams()}.
- */
- public boolean isStaleCheckingEnabled() {
- return this.params.isStaleCheckingEnabled();
- }
- /**
- * Sets whether or not isStale() will be called when testing if this connection is open.
- *
- *
Setting this flag to
false
will increase performance when reusing
- * connections, but it will also make them less reliable. Stale checking ensures that
- * connections are viable before they are used. When set to
false
some
- * method executions will result in IOExceptions and they will have to be retried.
true
to enable isStale()
- *
- * @see #isStale()
- * @see #isOpen()
- *
- * @deprecated Use {@link HttpConnectionParams#setStaleCheckingEnabled(boolean)},
- * {@link HttpConnection#getParams()}.
- */
- public void setStaleCheckingEnabled(boolean staleCheckEnabled) {
- this.params.setStaleCheckingEnabled(staleCheckEnabled);
- }
- /**
- * Determines whether this connection is "stale", which is to say that either
- * it is no longer open, or an attempt to read the connection would fail.
- *
- *
Unfortunately, due to the limitations of the JREs prior to 1.4, it is - * not possible to test a connection to see if both the read and write channels - * are open - except by reading and writing. This leads to a difficulty when - * some connections leave the "write" channel open, but close the read channel - * and ignore the request. This function attempts to ameliorate that - * problem by doing a test read, assuming that the caller will be doing a - * write followed by a read, rather than the other way around. - *
- * - *To avoid side-effects, the underlying connection is wrapped by a - * {@link BufferedInputStream}, so although data might be read, what is visible - * to clients of the connection will not change with this call.true if the connection is already closed, or a read would - * fail. - */ - protected boolean isStale() throws IOException { - boolean isStale = true; - if (isOpen) { - // the connection is open, but now we have to see if we can read it - // assume the connection is not stale. - isStale = false; - try { - if (inputStream.available() <= 0) { - try { - socket.setSoTimeout(1); - inputStream.mark(1); - int byteRead = inputStream.read(); - if (byteRead == -1) { - // again - if the socket is reporting all data read, - // probably stale - isStale = true; - } else { - inputStream.reset(); - } - } finally { - socket.setSoTimeout(this.params.getSoTimeout()); - } - } - } catch (InterruptedIOException e) { - if (!ExceptionUtil.isSocketTimeoutException(e)) { - throw e; - } - // aha - the connection is NOT stale - continue on! - } catch (IOException e) { - // oops - the connection is stale, the read or soTimeout failed. - LOG.debug( - "An error occurred while reading from the socket, is appears to be stale", - e - ); - isStale = true; - } - } - return isStale; - } - /** - * Returns true if the connection is established via a proxy, - * false otherwise. - * - * @return true if a proxy is used to establish the connection, - * false otherwise. - */ - public boolean isProxied() { - return (!(null == proxyHostName || 0 >= proxyPortNumber)); - } - /** - * Set the state to keep track of the last response for the last request. - * - *
The connection managers use this to ensure that previous requests are - * properly closed before a new request is attempted. That way, a GET - * request need not be read in its entirety before a new request is issued. - * Instead, this stream can be closed as appropriate.
- * - * @param inStream The stream associated with an HttpMethod. - */ - public void setLastResponseInputStream(InputStream inStream) { - lastResponseInputStream = inStream; - } - /** - * Returns the stream used to read the last response's body. - * - *Clients will generally not need to call this function unless - * using HttpConnection directly, instead of calling {@link HttpClient#executeMethod}. - * For those clients, call this function, and if it returns a non-null stream, - * close the stream before attempting to execute a method. Note that - * calling "close" on the stream returned by this function may close - * the connection if the previous response contained a "Connection: close" header.
- * - * @return An {@link InputStream} corresponding to the body of the last - * response. - */ - public InputStream getLastResponseInputStream() { - return lastResponseInputStream; - } - // --------------------------------------------------- Other Public Methods - /** - * Returns {@link HttpConnectionParams HTTP protocol parameters} associated with this method. - * - * @return HTTP parameters. - * - * @since 3.0 - */ - public HttpConnectionParams getParams() { - return this.params; - } - /** - * Assigns {@link HttpConnectionParams HTTP protocol parameters} for this method. - * - * @since 3.0 - * - * @see HttpConnectionParams - */ - public void setParams(final HttpConnectionParams params) { - if (params == null) { - throw new IllegalArgumentException("Parameters may not be null"); - } - this.params = params; - } - /** - * Set the {@link Socket}'s timeout, via {@link Socket#setSoTimeout}. If the - * connection is already open, the SO_TIMEOUT is changed. If no connection - * is open, then subsequent connections will use the timeout value. - *
- * Note: This is not a connection timeout but a timeout on network traffic!
- *
- * @param timeout the timeout value
- * @throws SocketException - if there is an error in the underlying
- * protocol, such as a TCP error.
- *
- * @deprecated Use {@link HttpConnectionParams#setSoTimeout(int)},
- * {@link HttpConnection#getParams()}.
- */
- public void setSoTimeout(int timeout)
- throws SocketException, IllegalStateException {
- this.params.setSoTimeout(timeout);
- if (this.socket != null) {
- this.socket.setSoTimeout(timeout);
- }
- }
- /**
- * Sets
SO_TIMEOUT
value directly on the underlying {@link Socket socket}.
- * This method does not change the default read timeout value set via
- * {@link HttpConnectionParams}.
- *
- * @param timeout the timeout value
- * @throws SocketException - if there is an error in the underlying
- * protocol, such as a TCP error.
- * @throws IllegalStateException if not connected
- *
- * @since 3.0
- */
- public void setSocketTimeout(int timeout)
- throws SocketException, IllegalStateException {
- assertOpen();
- if (this.socket != null) {
- this.socket.setSoTimeout(timeout);
- }
- }
- /**
- * Returns the {@link Socket}'s timeout, via {@link Socket#getSoTimeout}, if the
- * connection is already open. If no connection is open, return the value subsequent
- * connection will use.
- *
- * Note: This is not a connection timeout but a timeout on network traffic!
- *
- * @return the timeout value
- *
- * @deprecated Use {@link HttpConnectionParams#getSoTimeout()},
- * {@link HttpConnection#getParams()}.
- */
- public int getSoTimeout() throws SocketException {
- return this.params.getSoTimeout();
- }
- /**
- * Sets the connection timeout. This is the maximum time that may be spent
- * until a connection is established. The connection will fail after this
- * amount of time.
- * @param timeout The timeout in milliseconds. 0 means timeout is not used.
- *
- * @deprecated Use {@link HttpConnectionParams#setConnectionTimeout(int)},
- * {@link HttpConnection#getParams()}.
- */
- public void setConnectionTimeout(int timeout) {
- this.params.setConnectionTimeout(timeout);
- }
- /**
- * Establishes a connection to the specified host and port
- * (via a proxy if specified).
- * The underlying socket is created from the {@link ProtocolSocketFactory}.
- *
- * @throws IOException if an attempt to establish the connection results in an
- * I/O error.
- */
- public void open() throws IOException {
- LOG.trace("enter HttpConnection.open()");
- final String host = (proxyHostName == null) ? hostName : proxyHostName;
- final int port = (proxyHostName == null) ? portNumber : proxyPortNumber;
- assertNotOpen();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Open connection to " + host + ":" + port);
- }
- try {
- if (this.socket == null) {
- usingSecureSocket = isSecure() && !isProxied();
- // use the protocol's socket factory unless this is a secure
- // proxied connection
- ProtocolSocketFactory socketFactory = null;
- if (isSecure() && isProxied()) {
- Protocol defaultprotocol = Protocol.getProtocol("http");
- socketFactory = defaultprotocol.getSocketFactory();
- } else {
- socketFactory = this.protocolInUse.getSocketFactory();
- }
- this.socket = socketFactory.createSocket(
- host, port,
- localAddress, 0,
- this.params);
- }
- /*
- "Nagling has been broadly implemented across networks,
- including the Internet, and is generally performed by default
- - although it is sometimes considered to be undesirable in
- highly interactive environments, such as some client/server
- situations. In such cases, nagling may be turned off through
- use of the TCP_NODELAY sockets option." */
- socket.setTcpNoDelay(this.params.getTcpNoDelay());
- socket.setSoTimeout(this.params.getSoTimeout());
- int linger = this.params.getLinger();
- if (linger >= 0) {
- socket.setSoLinger(linger > 0, linger);
- }
- int sndBufSize = this.params.getSendBufferSize();
- if (sndBufSize >= 0) {
- socket.setSendBufferSize(sndBufSize);
- }
- int rcvBufSize = this.params.getReceiveBufferSize();
- if (rcvBufSize >= 0) {
- socket.setReceiveBufferSize(rcvBufSize);
- }
- int outbuffersize = socket.getSendBufferSize();
- if ((outbuffersize > 2048) || (outbuffersize <= 0)) {
- outbuffersize = 2048;
- }
- int inbuffersize = socket.getReceiveBufferSize();
- if ((inbuffersize > 2048) || (inbuffersize <= 0)) {
- inbuffersize = 2048;
- }
- inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
- outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
- isOpen = true;
- } catch (IOException e) {
- // Connection wasn't opened properly
- // so close everything out
- closeSocketAndStreams();
- throw e;
- }
- }
- /**
- * Instructs the proxy to establish a secure tunnel to the host. The socket will
- * be switched to the secure socket. Subsequent communication is done via the secure
- * socket. The method can only be called once on a proxied secure connection.
- *
- * @throws IllegalStateException if connection is not secure and proxied or
- * if the socket is already secure.
- * @throws IOException if an attempt to establish the secure tunnel results in an
- * I/O error.
- */
- public void tunnelCreated() throws IllegalStateException, IOException {
- LOG.trace("enter HttpConnection.tunnelCreated()");
- if (!isSecure() || !isProxied()) {
- throw new IllegalStateException(
- "Connection must be secure "
- + "and proxied to use this feature");
- }
- if (usingSecureSocket) {
- throw new IllegalStateException("Already using a secure socket");
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("Secure tunnel to " + this.hostName + ":" + this.portNumber);
- }
- SecureProtocolSocketFactory socketFactory =
- (SecureProtocolSocketFactory) protocolInUse.getSocketFactory();
- socket = socketFactory.createSocket(socket, hostName, portNumber, true);
- int sndBufSize = this.params.getSendBufferSize();
- if (sndBufSize >= 0) {
- socket.setSendBufferSize(sndBufSize);
- }
- int rcvBufSize = this.params.getReceiveBufferSize();
- if (rcvBufSize >= 0) {
- socket.setReceiveBufferSize(rcvBufSize);
- }
- int outbuffersize = socket.getSendBufferSize();
- if (outbuffersize > 2048) {
- outbuffersize = 2048;
- }
- int inbuffersize = socket.getReceiveBufferSize();
- if (inbuffersize > 2048) {
- inbuffersize = 2048;
- }
- inputStream = new BufferedInputStream(socket.getInputStream(), inbuffersize);
- outputStream = new BufferedOutputStream(socket.getOutputStream(), outbuffersize);
- usingSecureSocket = true;
- tunnelEstablished = true;
- }
- /**
- * Indicates if the connection is completely transparent from end to end.
- *
- * @return true if conncetion is not proxied or tunneled through a transparent
- * proxy; false otherwise.
- */
- public boolean isTransparent() {
- return !isProxied() || tunnelEstablished;
- }
- /**
- * Flushes the output request stream. This method should be called to
- * ensure that data written to the request OutputStream is sent to the server.
- *
- * @throws IOException if an I/O problem occurs
- */
- public void flushRequestOutputStream() throws IOException {
- LOG.trace("enter HttpConnection.flushRequestOutputStream()");
- assertOpen();
- outputStream.flush();
- }
- /**
- * Returns an {@link OutputStream} suitable for writing the request.
- *
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- * @return a stream to write the request to
- */
- public OutputStream getRequestOutputStream()
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.getRequestOutputStream()");
- assertOpen();
- OutputStream out = this.outputStream;
- if (Wire.CONTENT_WIRE.enabled()) {
- out = new WireLogOutputStream(out, Wire.CONTENT_WIRE);
- }
- return out;
- }
- /**
- * Return a {@link InputStream} suitable for reading the response.
- * @return InputStream The response input stream.
- * @throws IOException If an IO problem occurs
- * @throws IllegalStateException If the connection isn't open.
- */
- public InputStream getResponseInputStream()
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.getResponseInputStream()");
- assertOpen();
- return inputStream;
- }
- /**
- * Tests if input data avaialble. This method returns immediately
- * and does not perform any read operations on the input socket
- *
- * @return boolean
true
if input data is available,
- *
false
otherwise.
- *
- * @throws IOException If an IO problem occurs
- * @throws IllegalStateException If the connection isn't open.
- */
- public boolean isResponseAvailable()
- throws IOException {
- LOG.trace("enter HttpConnection.isResponseAvailable()");
- if (this.isOpen) {
- return this.inputStream.available() > 0;
- } else {
- return false;
- }
- }
- /**
- * Tests if input data becomes available within the given period time in milliseconds.
- *
- * @param timeout The number milliseconds to wait for input data to become available
- * @return boolean
true
if input data is availble,
- *
false
otherwise.
- *
- * @throws IOException If an IO problem occurs
- * @throws IllegalStateException If the connection isn't open.
- */
- public boolean isResponseAvailable(int timeout)
- throws IOException {
- LOG.trace("enter HttpConnection.isResponseAvailable(int)");
- assertOpen();
- boolean result = false;
- if (this.inputStream.available() > 0) {
- result = true;
- } else {
- try {
- this.socket.setSoTimeout(timeout);
- inputStream.mark(1);
- int byteRead = inputStream.read();
- if (byteRead != -1) {
- inputStream.reset();
- LOG.debug("Input data available");
- result = true;
- } else {
- LOG.debug("Input data not available");
- }
- } catch (InterruptedIOException e) {
- if (!ExceptionUtil.isSocketTimeoutException(e)) {
- throw e;
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("Input data not available after " + timeout + " ms");
- }
- } finally {
- try {
- socket.setSoTimeout(this.params.getSoTimeout());
- } catch (IOException ioe) {
- LOG.debug("An error ocurred while resetting soTimeout, we will assume that"
- + " no response is available.",
- ioe);
- result = false;
- }
- }
- }
- return result;
- }
- /**
- * Writes the specified bytes to the output stream.
- *
- * @param data the data to be written
- * @throws IllegalStateException if not connected
- * @throws IOException if an I/O problem occurs
- * @see #write(byte[],int,int)
- */
- public void write(byte[] data)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.write(byte[])");
- this.write(data, 0, data.length);
- }
- /**
- * Writes
length
bytes in
data
starting at
- *
offset
to the output stream.
- *
- * The general contract for
- * write(b, off, len) is that some of the bytes in the array b are written
- * to the output stream in order; element b[off] is the first byte written
- * and b[off+len-1] is the last byte written by this operation.
- *
- * @param data array containing the data to be written.
- * @param offset the start offset in the data.
- * @param length the number of bytes to write.
- * @throws IllegalStateException if not connected
- * @throws IOException if an I/O problem occurs
- */
- public void write(byte[] data, int offset, int length)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.write(byte[], int, int)");
- if (offset < 0) {
- throw new IllegalArgumentException("Array offset may not be negative");
- }
- if (length < 0) {
- throw new IllegalArgumentException("Array length may not be negative");
- }
- if (offset + length > data.length) {
- throw new IllegalArgumentException("Given offset and length exceed the array length");
- }
- assertOpen();
- this.outputStream.write(data, offset, length);
- }
- /**
- * Writes the specified bytes, followed by
"\r\n".getBytes()
to the
- * output stream.
- *
- * @param data the bytes to be written
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- */
- public void writeLine(byte[] data)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.writeLine(byte[])");
- write(data);
- writeLine();
- }
- /**
- * Writes
"\r\n".getBytes()
to the output stream.
- *
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- */
- public void writeLine()
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.writeLine()");
- write(CRLF);
- }
- /**
- * @deprecated Use {@link #print(String, String)}
- *
- * Writes the specified String (as bytes) to the output stream.
- *
- * @param data the string to be written
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- */
- public void print(String data)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.print(String)");
- write(EncodingUtil.getBytes(data, "ISO-8859-1"));
- }
- /**
- * Writes the specified String (as bytes) to the output stream.
- *
- * @param data the string to be written
- * @param charset the charset to use for writing the data
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- *
- * @since 3.0
- */
- public void print(String data, String charset)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.print(String)");
- write(EncodingUtil.getBytes(data, charset));
- }
- /**
- * @deprecated Use {@link #printLine(String, String)}
- *
- * Writes the specified String (as bytes), followed by
- *
"\r\n".getBytes()
to the output stream.
- *
- * @param data the data to be written
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- */
- public void printLine(String data)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.printLine(String)");
- writeLine(EncodingUtil.getBytes(data, "ISO-8859-1"));
- }
- /**
- * Writes the specified String (as bytes), followed by
- *
"\r\n".getBytes()
to the output stream.
- *
- * @param data the data to be written
- * @param charset the charset to use for writing the data
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- *
- * @since 3.0
- */
- public void printLine(String data, String charset)
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.printLine(String)");
- writeLine(EncodingUtil.getBytes(data, charset));
- }
- /**
- * Writes
"\r\n".getBytes()
to the output stream.
- *
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- */
- public void printLine()
- throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.printLine()");
- writeLine();
- }
- /**
- * Reads up to
"\n"
from the (unchunked) input stream.
- * If the stream ends before the line terminator is found,
- * the last part of the string will still be returned.
- *
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- * @return a line from the response
- *
- * @deprecated use #readLine(String)
- */
- public String readLine() throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.readLine()");
- assertOpen();
- return HttpParser.readLine(inputStream);
- }
- /**
- * Reads up to
"\n"
from the (unchunked) input stream.
- * If the stream ends before the line terminator is found,
- * the last part of the string will still be returned.
- *
- * @param charset the charset to use for reading the data
- *
- * @throws IllegalStateException if the connection is not open
- * @throws IOException if an I/O problem occurs
- * @return a line from the response
- *
- * @since 3.0
- */
- public String readLine(final String charset) throws IOException, IllegalStateException {
- LOG.trace("enter HttpConnection.readLine()");
- assertOpen();
- return HttpParser.readLine(inputStream, charset);
- }
- /**
- * Attempts to shutdown the {@link Socket}'s output, via Socket.shutdownOutput()
- * when running on JVM 1.3 or higher.
- *
- * @deprecated unused
- */
- public void shutdownOutput() {
- LOG.trace("enter HttpConnection.shutdownOutput()");
- try {
- // Socket.shutdownOutput is a JDK 1.3
- // method. We'll use reflection in case
- // we're running in an older VM
- Class[] paramsClasses = new Class[0];
- Method shutdownOutput =
- socket.getClass().getMethod("shutdownOutput", paramsClasses);
- Object[] params = new Object[0];
- shutdownOutput.invoke(socket, params);
- } catch (Exception ex) {
- LOG.debug("Unexpected Exception caught", ex);
- // Ignore, and hope everything goes right
- }
- // close output stream?
- }
- /**
- * Closes the socket and streams.
- */
- public void close() {
- LOG.trace("enter HttpConnection.close()");
- closeSocketAndStreams();
- }
- /**
- * Returns the httpConnectionManager.
- * @return HttpConnectionManager
- */
- public HttpConnectionManager getHttpConnectionManager() {
- return httpConnectionManager;
- }
- /**
- * Sets the httpConnectionManager.
- * @param httpConnectionManager The httpConnectionManager to set
- */
- public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) {
- this.httpConnectionManager = httpConnectionManager;
- }
- /**
- * Releases the connection. If the connection is locked or does not have a connection
- * manager associated with it, this method has no effect. Note that it is completely safe
- * to call this method multiple times.
- */
- public void releaseConnection() {
- LOG.trace("enter HttpConnection.releaseConnection()");
- if (locked) {
- LOG.debug("Connection is locked. Call to releaseConnection() ignored.");
- } else if (httpConnectionManager != null) {
- LOG.debug("Releasing connection back to connection manager.");
- httpConnectionManager.releaseConnection(this);
- } else {
- LOG.warn("HttpConnectionManager is null. Connection cannot be released.");
- }
- }
- /**
- * Tests if the connection is locked. Locked connections cannot be released.
- * An attempt to release a locked connection will have no effect.
- *
- * @return
true
if the connection is locked,
false
otherwise.
- *
- * @since 3.0
- */
- protected boolean isLocked() {
- return locked;
- }
- /**
- * Locks or unlocks the connection. Locked connections cannot be released.
- * An attempt to release a locked connection will have no effect.
- *
- * @param locked
true
to lock the connection,
false
to unlock
- * the connection.
- *
- * @since 3.0
- */
- protected void setLocked(boolean locked) {
- this.locked = locked;
- }
- // ------------------------------------------------------ Protected Methods
- /**
- * Closes everything out.
- */
- protected void closeSocketAndStreams() {
- LOG.trace("enter HttpConnection.closeSockedAndStreams()");
- isOpen = false;
- // no longer care about previous responses...
- lastResponseInputStream = null;
- if (null != outputStream) {
- OutputStream temp = outputStream;
- outputStream = null;
- try {
- temp.close();
- } catch (Exception ex) {
- LOG.debug("Exception caught when closing output", ex);
- // ignored
- }
- }
- if (null != inputStream) {
- InputStream temp = inputStream;
- inputStream = null;
- try {
- temp.close();
- } catch (Exception ex) {
- LOG.debug("Exception caught when closing input", ex);
- // ignored
- }
- }
- if (null != socket) {
- Socket temp = socket;
- socket = null;
- try {
- temp.close();
- } catch (Exception ex) {
- LOG.debug("Exception caught when closing socket", ex);
- // ignored
- }
- }
- tunnelEstablished = false;
- usingSecureSocket = false;
- }
- /**
- * Throws an {@link IllegalStateException} if the connection is already open.
- *
- * @throws IllegalStateException if connected
- */
- protected void assertNotOpen() throws IllegalStateException {
- if (isOpen) {
- throw new IllegalStateException("Connection is open");
- }
- }
- /**
- * Throws an {@link IllegalStateException} if the connection is not open.
- *
- * @throws IllegalStateException if not connected
- */
- protected void assertOpen() throws IllegalStateException {
- if (!isOpen) {
- throw new IllegalStateException("Connection is not open");
- }
- }
- /**
- * Gets the socket's sendBufferSize.
- *
- * @return the size of the buffer for the socket OutputStream, -1 if the value
- * has not been set and the socket has not been opened
- *
- * @throws SocketException if an error occurs while getting the socket value
- *
- * @see Socket#getSendBufferSize()
- */
- public int getSendBufferSize() throws SocketException {
- if (socket == null) {
- return -1;
- } else {
- return socket.getSendBufferSize();
- }
- }
- /**
- * Sets the socket's sendBufferSize.
- *
- * @param sendBufferSize the size to set for the socket OutputStream
- *
- * @throws SocketException if an error occurs while setting the socket value
- *
- * @see Socket#setSendBufferSize(int)
- *
- * @deprecated Use {@link HttpConnectionParams#setSendBufferSize(int)},
- * {@link HttpConnection#getParams()}.
- */
- public void setSendBufferSize(int sendBufferSize) throws SocketException {
- this.params.setSendBufferSize(sendBufferSize);
- }
- // ------------------------------------------------------- Static Variable
- /**
"\r\n"
, as bytes. */
- private static final byte[] CRLF = new byte[] {(byte) 13, (byte) 10};
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(HttpConnection.class);
- // ----------------------------------------------------- Instance Variables
- /** My host. */
- private String hostName = null;
- /** My port. */
- private int portNumber = -1;
- /** My proxy host. */
- private String proxyHostName = null;
- /** My proxy port. */
- private int proxyPortNumber = -1;
- /** My client Socket. */
- private Socket socket = null;
- /** My InputStream. */
- private InputStream inputStream = null;
- /** My OutputStream. */
- private OutputStream outputStream = null;
- /** An {@link InputStream} for the response to an individual request. */
- private InputStream lastResponseInputStream = null;
- /** Whether or not the connection is connected. */
- protected boolean isOpen = false;
- /** the protocol being used */
- private Protocol protocolInUse;
- /** Collection of HTTP parameters associated with this HTTP connection*/
- private HttpConnectionParams params = new HttpConnectionParams();
- /** flag to indicate if this connection can be released, if locked the connection cannot be
- * released */
- private boolean locked = false;
- /** Whether or not the socket is a secure one. */
- private boolean usingSecureSocket = false;
- /** Whether the connection is open via a secure tunnel or not */
- private boolean tunnelEstablished = false;
- /** the connection manager that created this connection or null */
- private HttpConnectionManager httpConnectionManager;
- /** The local interface on which the connection is created, or null for the default */
- private InetAddress localAddress;
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpConnectionManager.java b/clients/java/src/org/apache/commons/httpclient/HttpConnectionManager.java
deleted file mode 100644
index ae8d5af..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpConnectionManager.java
+++ /dev/null
@@ -1,151 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpConnectionManager.java,v 1.24 2004/07/05 22:46:58 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
.
- * @param port the port. Value
-1
can be used to set default protocol port
- * @param protocol the protocol. Value
null
can be used to set default protocol
- */
- public HttpHost(final String hostname, int port, final Protocol protocol) {
- super();
- if (hostname == null) {
- throw new IllegalArgumentException("Host name may not be null");
- }
- if (protocol == null) {
- throw new IllegalArgumentException("Protocol may not be null");
- }
- this.hostname = hostname;
- this.protocol = protocol;
- if (port >= 0) {
- this.port = port;
- } else {
- this.port = this.protocol.getDefaultPort();
- }
- }
- /**
- * Constructor for HttpHost.
- *
- * @param hostname the hostname (IP or DNS name). Can be
null
.
- * @param port the port. Value
-1
can be used to set default protocol port
- */
- public HttpHost(final String hostname, int port) {
- this(hostname, port, Protocol.getProtocol("http"));
- }
- /**
- * Constructor for HttpHost.
- *
- * @param hostname the hostname (IP or DNS name). Can be
null
.
- */
- public HttpHost(final String hostname) {
- this(hostname, -1, Protocol.getProtocol("http"));
- }
- /**
- * URI constructor for HttpHost.
- *
- * @param uri the URI.
- */
- public HttpHost(final URI uri) throws URIException {
- this(uri.getHost(), uri.getPort(), Protocol.getProtocol(uri.getScheme()));
- }
- /**
- * Copy constructor for HttpHost
- *
- * @param httphost the HTTP host to copy details from
- */
- public HttpHost (final HttpHost httphost) {
- super();
- init(httphost);
- }
- private void init(final HttpHost httphost) {
- this.hostname = httphost.hostname;
- this.port = httphost.port;
- this.protocol = httphost.protocol;
- }
- /**
- * @throws CloneNotSupportedException
- * @see java.lang.Object#clone()
- */
- public Object clone() throws CloneNotSupportedException {
- HttpHost copy = (HttpHost) super.clone();
- copy.init(this);
- return copy;
- }
- /**
- * Returns the host name (IP or DNS name).
- *
- * @return the host name (IP or DNS name), or
null
if not set
- */
- public String getHostName() {
- return this.hostname;
- }
- /**
- * Returns the port.
- *
- * @return the host port, or
-1
if not set
- */
- public int getPort() {
- return this.port;
- }
- /**
- * Returns the protocol.
- * @return The protocol.
- */
- public Protocol getProtocol() {
- return this.protocol;
- }
- /**
- * Return the host uri.
- *
- * @return The host uri.
- */
- public String toURI() {
- StringBuffer buffer = new StringBuffer(50);
- buffer.append(this.protocol.getScheme());
- buffer.append("://");
- buffer.append(this.hostname);
- if (this.port != this.protocol.getDefaultPort()) {
- buffer.append(':');
- buffer.append(this.port);
- }
- return buffer.toString();
- }
- /**
- * @see java.lang.Object#toString()
- */
- public String toString() {
- StringBuffer buffer = new StringBuffer(50);
- buffer.append(toURI());
- return buffer.toString();
- }
- /**
- * @see java.lang.Object#equals(java.lang.Object)
- */
- public boolean equals(final Object o) {
- if (o instanceof HttpHost) {
- // shortcut if we're comparing with ourselves
- if (o == this) {
- return true;
- }
- HttpHost that = (HttpHost) o;
- if (!this.hostname.equalsIgnoreCase(that.hostname)) {
- return false;
- }
- if (this.port != that.port) {
- return false;
- }
- if (!this.protocol.equals(that.protocol)) {
- return false;
- }
- // everything matches
- return true;
- } else {
- return false;
- }
- }
- /**
- * @see java.lang.Object#hashCode()
- */
- public int hashCode() {
- int hash = LangUtils.HASH_SEED;
- hash = LangUtils.hashCode(hash, this.hostname);
- hash = LangUtils.hashCode(hash, this.port);
- hash = LangUtils.hashCode(hash, this.protocol);
- return hash;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpMethod.java b/clients/java/src/org/apache/commons/httpclient/HttpMethod.java
deleted file mode 100644
index 6de278a..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpMethod.java
+++ /dev/null
@@ -1,577 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethod.java,v 1.43 2004/10/07 16:14:15 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
if none is set
- */
- HostConfiguration getHostConfiguration();
- /**
- * Sets the path of the HTTP method.
- * It is responsibility of the caller to ensure that the path is
- * properly encoded (URL safe).
- *
- * @param path The path of the HTTP method. The path is expected
- * to be URL encoded.
- */
- void setPath(String path);
- /**
- * Returns the path of the HTTP method.
- *
- * Calling this method
after
the request has been executed will
- * return the
actual
path, following any redirects automatically
- * handled by this HTTP method.
- *
- * @return the path of the HTTP method, in URL encoded form
- */
- String getPath();
- /**
- * Returns the URI for this method. The URI will be absolute if the host
- * configuration has been set and relative otherwise.
- *
- * @return the URI for this method
- *
- * @throws URIException if a URI cannot be constructed
- */
- URI getURI() throws URIException;
- /**
- * Sets the URI for this method.
- *
- * @param uri URI to be set
- *
- * @throws URIException if a URI cannot be set
- *
- * @since 3.0
- */
- void setURI(URI uri) throws URIException;
- /**
- * Defines how strictly the method follows the HTTP protocol specification.
- * (See RFC 2616 and other relevant RFCs.) In the strict mode the method precisely
- * implements the requirements of the specification, whereas in non-strict mode
- * it attempts to mimic the exact behaviour of commonly used HTTP agents,
- * which many HTTP servers expect.
- *
- * @param strictMode
true
for strict mode,
false
otherwise
- *
- * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
- * to exercise a more granular control over HTTP protocol strictness.
- *
- * @see #isStrictMode()
- */
- void setStrictMode(boolean strictMode);
- /**
- * Returns the value of the strict mode flag.
- *
- * @return
true
if strict mode is enabled,
false
otherwise
- *
- * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
- * to exercise a more granular control over HTTP protocol strictness.
- *
- * @see #setStrictMode(boolean)
- */
- boolean isStrictMode();
- /**
- * Sets the specified request header, overwriting any
- * previous value.
- * Note that header-name matching is case insensitive.
- * @param headerName the header's name
- * @param headerValue the header's value
- *
- * @see #setRequestHeader(Header)
- * @see #getRequestHeader(String)
- * @see #removeRequestHeader(String)
- */
- void setRequestHeader(String headerName, String headerValue);
- /**
- * Sets the specified request header, overwriting any
- * previous value.
- * Note that header-name matching is case insensitive.
- * @param header the header to be set
- *
- * @see #setRequestHeader(String,String)
- * @see #getRequestHeader(String)
- * @see #removeRequestHeader(String)
- */
- void setRequestHeader(Header header);
- /**
- * Adds the specified request header,
not
overwriting any previous value.
- * If the same header is added multiple times, perhaps with different values,
- * multiple instances of that header will be sent in the HTTP request.
- * Note that header-name matching is case insensitive.
- * @param headerName the header's name
- * @param headerValue the header's value
- *
- * @see #addRequestHeader(Header)
- * @see #getRequestHeader(String)
- * @see #removeRequestHeader(String)
- */
- void addRequestHeader(String headerName, String headerValue);
- /**
- * Adds the specified request header,
not
overwriting any previous value.
- * If the same header is added multiple times, perhaps with different values,
- * multiple instances of that header will be sent in the HTTP request.
- * Note that header-name matching is case insensitive.
- * @param header the header
- *
- * @see #addRequestHeader(String,String)
- * @see #getRequestHeader(String)
- * @see #removeRequestHeader(String)
- */
- void addRequestHeader(Header header);
- /**
- * Gets the request header with the given name.
- * If there are multiple headers with the same name,
- * there values will be combined with the ',' separator as specified by RFC2616.
- * Note that header-name matching is case insensitive.
- * @param headerName the header name
- * @return the header
- */
- Header getRequestHeader(String headerName);
- /**
- * Removes all request headers with the given name.
- * Note that header-name matching is case insensitive.
- * @param headerName the header name
- */
- void removeRequestHeader(String headerName);
- /**
- * Removes the given request header.
- *
- * @param header the header
- *
- * @since 3.0
- */
- void removeRequestHeader(Header header);
- /**
- * Returns
true
if the HTTP method should automatically follow HTTP redirects
- * (status code 302, etc.),
false
otherwise.
- *
- * @return
true
if the method will automatically follow HTTP redirects,
- *
false
otherwise
- */
- boolean getFollowRedirects();
- /**
- * Sets whether or not the HTTP method should automatically follow HTTP redirects
- * (status code 302, etc.)
- *
- * @param followRedirects
true
if the method will automatically follow redirects,
- *
false
otherwise.
- */
- void setFollowRedirects(boolean followRedirects);
- /**
- * Sets the query string of the HTTP method.
- * It is responsibility of the caller to ensure that the path is
- * properly encoded (URL safe). The string must not include an initial '?' character.
- *
- * @param queryString the query to be used in the request, with no leading '?' character
- *
- * @see #getQueryString()
- * @see #setQueryString(NameValuePair[])
- */
- void setQueryString(String queryString);
- /**
- * Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters.
- * To use a different charset the parameters can be encoded manually using EncodingUtil
- * and set as a single String.
- *
- * @param params An array of
NameValuePair
s to use as the query string.
- * The name/value pairs will be automatically URL encoded and should not
- * have been encoded previously.
- *
- * @see #getQueryString()
- * @see #setQueryString(String)
- * @see org.apache.commons.httpclient.util.EncodingUtil#formUrlEncode(NameValuePair[], String)
- */
- void setQueryString(NameValuePair[] params);
- /**
- * Returns the query string of this HTTP method.
- *
- * @return the query string in URL encoded form, without a leading '?'.
- *
- * @see #setQueryString(NameValuePair[])
- * @see #setQueryString(String)
- */
- String getQueryString();
- /**
- * Returns the current request headers for this HTTP method. The returned headers
- * will be in the same order that they were added with
addRequestHeader
.
- * If there are multiple request headers with the same name (e.g.
Cookie
),
- * they will be returned as multiple entries in the array.
- *
- * @return an array containing all of the request headers
- *
- * @see #addRequestHeader(Header)
- * @see #addRequestHeader(String,String)
- */
- Header[] getRequestHeaders();
- /**
- * Returns the request headers with the given name. Note that header-name matching is
- * case insensitive.
- * @param headerName the name of the headers to be returned.
- * @return an array of zero or more headers
- *
- * @since 3.0
- */
- Header[] getRequestHeaders(String headerName);
- // ---------------------------------------------------------------- Queries
- /**
- * Returns
true
the method is ready to execute,
false
otherwise.
- *
- * @return
true
if the method is ready to execute,
false
otherwise.
- */
- boolean validate();
- /**
- * Returns the status code associated with the latest response.
- *
- * @return The status code from the most recent execution of this method.
- * If the method has not yet been executed, the result is undefined.
- */
- int getStatusCode();
- /**
- * Returns the status text (or "reason phrase") associated with the latest
- * response.
- *
- * @return The status text from the most recent execution of this method.
- * If the method has not yet been executed, the result is undefined.
- */
- String getStatusText();
- /**
- * Returns the response headers from the most recent execution of this request.
- *
- * @return A newly-created array containing all of the response headers,
- * in the order in which they appeared in the response.
- */
- Header[] getResponseHeaders();
- /**
- * Returns the specified response header. Note that header-name matching is
- * case insensitive.
- *
- * @param headerName The name of the header to be returned.
- *
- * @return The specified response header. If the repsonse contained multiple
- * instances of the header, its values will be combined using the ','
- * separator as specified by RFC2616.
- */
- Header getResponseHeader(String headerName);
- /**
- * Returns the response headers with the given name. Note that header-name matching is
- * case insensitive.
- * @param headerName the name of the headers to be returned.
- * @return an array of zero or more headers
- *
- * @since 3.0
- */
- Header[] getResponseHeaders(String headerName);
- /**
- * Returns the response footers from the most recent execution of this request.
- *
- * @return an array containing the response footers in the order that they
- * appeared in the response. If the response had no footers,
- * an empty array will be returned.
- */
- Header[] getResponseFooters();
- /**
- * Return the specified response footer. Note that footer-name matching is
- * case insensitive.
- *
- * @param footerName The name of the footer.
- * @return The response footer.
- */
- Header getResponseFooter(String footerName);
- /**
- * Returns the response body of the HTTP method, if any, as an array of bytes.
- * If the method has not yet been executed or the response has no body,
null
- * is returned. Note that this method does not propagate I/O exceptions.
- * If an error occurs while reading the body,
null
will be returned.
- *
- * @return The response body, or
null
if the
- * body is not available.
- *
- * @throws IOException if an I/O (transport) problem occurs
- */
- byte[] getResponseBody() throws IOException;
- /**
- * Returns the response body of the HTTP method, if any, as a {@link String}.
- * If response body is not available or cannot be read,
null
is returned.
- * The raw bytes in the body are converted to a
String
using the
- * character encoding specified in the response's
Content-Type
header, or
- * ISO-8859-1 if the response did not specify a character set.
- *
- * Note that this method does not propagate I/O exceptions.
- * If an error occurs while reading the body,
null
will be returned.
- *
- * @return The response body converted to a
String
, or
null
- * if the body is not available.
- *
- * @throws IOException if an I/O (transport) problem occurs
- */
- String getResponseBodyAsString() throws IOException;
- /**
- * Returns the response body of the HTTP method, if any, as an InputStream.
- * If the response had no body or the method has not yet been executed,
- *
null
is returned. Additionally,
null
may be returned
- * if {@link #releaseConnection} has been called or
- * if this method was called previously and the resulting stream was closed.
- *
- * @return The response body, or
null
if it is not available
- *
- * @throws IOException if an I/O (transport) problem occurs
- */
- InputStream getResponseBodyAsStream() throws IOException;
- /**
- * Returns
true
if the HTTP method has been already {@link #execute executed},
- * but not {@link #recycle recycled}.
- *
- * @return
true
if the method has been executed,
false
otherwise
- */
- boolean hasBeenUsed();
- // --------------------------------------------------------- Action Methods
- /**
- * Executes this method using the specified
HttpConnection
and
- *
HttpState
.
- *
- * @param state the {@link HttpState state} information to associate with this method
- * @param connection the {@link HttpConnection connection} used to execute
- * this HTTP method
- *
- * @throws IOException If an I/O (transport) error occurs. Some transport exceptions
- * can be recovered from.
- * @throws HttpException If a protocol exception occurs. Usually protocol exceptions
- * cannot be recovered from.
- *
- * @return the integer status code if one was obtained, or
-1
- */
- int execute(HttpState state, HttpConnection connection)
- throws HttpException, IOException;
- /**
- * Aborts the execution of the HTTP method.
- *
- * @see #execute(HttpState, HttpConnection)
- *
- * @since 3.0
- */
- void abort();
- /**
- * Recycles the HTTP method so that it can be used again.
- * Note that all of the instance variables will be reset
- * once this method has been called. This method will also
- * release the connection being used by this HTTP method.
- *
- * @see #releaseConnection()
- *
- * @deprecated no longer supported and will be removed in the future
- * version of HttpClient
- */
- void recycle();
- /**
- * Releases the connection being used by this HTTP method. In particular the
- * connection is used to read the response (if there is one) and will be held
- * until the response has been read. If the connection can be reused by other
- * HTTP methods it is NOT closed at this point.
- *
- * After this method is called, {@link #getResponseBodyAsStream} will return
- *
null
, and {@link #getResponseBody} and {@link #getResponseBodyAsString}
- *
may
return
null
.
- */
- void releaseConnection();
- /**
- * Add a footer to this method's response.
- *
- *
Note:
This method is for
- * internal use only and should not be called by external clients.
- *
- * @param footer the footer to add
- *
- * @since 2.0
- */
- void addResponseFooter(Header footer);
- /**
- * Returns the Status-Line from the most recent response for this method,
- * or
null
if the method has not been executed.
- *
- * @return the status line, or
null
if the method has not been executed
- *
- * @since 2.0
- */
- StatusLine getStatusLine();
- /**
- * Returns
true
if the HTTP method should automatically handle HTTP
- * authentication challenges (status code 401, etc.),
false
otherwise
- *
- * @return
true
if authentication challenges will be processed
- * automatically,
false
otherwise.
- *
- * @since 2.0
- *
- * @see #setDoAuthentication(boolean)
- */
- boolean getDoAuthentication();
- /**
- * Sets whether or not the HTTP method should automatically handle HTTP
- * authentication challenges (status code 401, etc.)
- *
- * @param doAuthentication
true
to process authentication challenges
- * automatically,
false
otherwise.
- *
- * @since 2.0
- *
- * @see #getDoAuthentication()
- */
- void setDoAuthentication(boolean doAuthentication);
- /**
- * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method.
- *
- * @since 3.0
- *
- * @see HttpMethodParams
- */
- public HttpMethodParams getParams();
- /**
- * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method.
- *
- * @since 3.0
- *
- * @see HttpMethodParams
- */
- public void setParams(final HttpMethodParams params);
- /**
- * Returns the target host {@link AuthState authentication state}
- *
- * @return host authentication state
- *
- * @since 3.0
- */
- public AuthState getHostAuthState();
- /**
- * Returns the proxy {@link AuthState authentication state}
- *
- * @return host authentication state
- *
- * @since 3.0
- */
- public AuthState getProxyAuthState();
- /**
- * Returns
true
if the HTTP has been transmitted to the target
- * server in its entirety,
false
otherwise. This flag can be useful
- * for recovery logic. If the request has not been transmitted in its entirety,
- * it is safe to retry the failed method.
- *
- * @return
true
if the request has been sent,
false
otherwise
- */
- boolean isRequestSent();
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpMethodBase.java b/clients/java/src/org/apache/commons/httpclient/HttpMethodBase.java
deleted file mode 100644
index c65bf35..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpMethodBase.java
+++ /dev/null
@@ -1,2554 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v 1.222 2005/01/14 21:16:40 olegk Exp $
- * $Revision: 539441 $
- * $Date: 2007-05-18 14:56:55 +0200 (Fri, 18 May 2007) $
- * ====================================================================
- * 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
- *
- * Return -1 when the content-length is unknown. - *
- * - * @return content length, if Content-Length header is available. - * 0 indicates that the request has no body. - * If Content-Length header is not present, the method - * returns -1 . - */ - public long getResponseContentLength() { - Header[] headers = getResponseHeaderGroup().getHeaders("Content-Length"); - if (headers.length == 0) { - return -1; - } - if (headers.length > 1) { - LOG.warn("Multiple content-length headers detected"); - } - for (int i = headers.length - 1; i >= 0; i--) { - Header header = headers[i]; - try { - return Long.parseLong(header.getValue()); - } catch (NumberFormatException e) { - if (LOG.isWarnEnabled()) { - LOG.warn("Invalid content-length value: " + e.getMessage()); - } - } - // See if we can have better luck with another header, if present - } - return -1; - } - /** - * Returns the response body of the HTTP method, if any, as an array of bytes. - * If response body is not available or cannot be read, returns null . - * Buffers the response and this method can be called several times yielding - * the same result each time. - * - * Note: This will cause the entire response body to be buffered in memory. A - * malicious server may easily exhaust all the VM memory. It is strongly - * recommended, to use getResponseAsStream if the content length of the response - * is unknown or resonably large. - * - * @return The response body. - * - * @throws IOException If an I/O (transport) problem occurs while obtaining the - * response body. - */ - public byte[] getResponseBody() throws IOException { - if (this.responseBody == null) { - InputStream instream = getResponseBodyAsStream(); - if (instream != null) { - long contentLength = getResponseContentLength(); - if (contentLength > Integer.MAX_VALUE) { //guard below cast from overflow - throw new IOException("Content too large to be buffered: "+ contentLength +" bytes"); - } - int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024); - if ((contentLength == -1) || (contentLength > limit)) { - LOG.warn("Going to buffer response body of large or unknown size. " - +"Using getResponseBodyAsStream instead is recommended."); - } - LOG.debug("Buffering response body"); - ByteArrayOutputStream outstream = new ByteArrayOutputStream( - contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE); - byte[] buffer = new byte[4096]; - int len; - while ((len = instream.read(buffer)) > 0) { - outstream.write(buffer, 0, len); - } - outstream.close(); - setResponseStream(null); - this.responseBody = outstream.toByteArray(); - } - } - return this.responseBody; - } - /** - * Returns the response body of the HTTP method, if any, as an array of bytes. - * If response body is not available or cannot be read, returns null . - * Buffers the response and this method can be called several times yielding - * the same result each time. - * - * Note: This will cause the entire response body to be buffered in memory. This method is - * safe if the content length of the response is unknown, because the amount of memory used - * is limited.
- *
- * If the response is large this method involves lots of array copying and many object
- * allocations, which makes it unsuitable for high-performance / low-footprint applications.
- * Those applications should use {@link #getResponseBodyAsStream()}.
- *
- * @param maxlen the maximum content length to accept (number of bytes).
- * @return The response body.
- *
- * @throws IOException If an I/O (transport) problem occurs while obtaining the
- * response body.
- */
- public byte[] getResponseBody(int maxlen) throws IOException {
- if (maxlen < 0) throw new IllegalArgumentException("maxlen must be positive");
- if (this.responseBody == null) {
- InputStream instream = getResponseBodyAsStream();
- if (instream != null) {
- // we might already know that the content is larger
- long contentLength = getResponseContentLength();
- if ((contentLength != -1) && (contentLength > maxlen)) {
- throw new HttpContentTooLargeException(
- "Content-Length is " + contentLength, maxlen);
- }
- LOG.debug("Buffering response body");
- ByteArrayOutputStream rawdata = new ByteArrayOutputStream(
- contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
- byte[] buffer = new byte[2048];
- int pos = 0;
- int len;
- do {
- len = instream.read(buffer, 0, Math.min(buffer.length, maxlen-pos));
- if (len == -1) break;
- rawdata.write(buffer, 0, len);
- pos += len;
- } while (pos < maxlen);
- setResponseStream(null);
- // check if there is even more data
- if (pos == maxlen) {
- if (instream.read() != -1)
- throw new HttpContentTooLargeException(
- "Content-Length not known but larger than "
- + maxlen, maxlen);
- }
- this.responseBody = rawdata.toByteArray();
- }
- }
- return this.responseBody;
- }
- /**
- * Returns the response body of the HTTP method, if any, as an {@link InputStream}.
- * If response body is not available, returns
null
. If the response has been
- * buffered this method returns a new stream object on every call. If the response
- * has not been buffered the returned stream can only be read once.
- *
- * @return The response body or
null
.
- *
- * @throws IOException If an I/O (transport) problem occurs while obtaining the
- * response body.
- */
- public InputStream getResponseBodyAsStream() throws IOException {
- if (responseStream != null) {
- return responseStream;
- }
- if (responseBody != null) {
- InputStream byteResponseStream = new ByteArrayInputStream(responseBody);
- LOG.debug("re-creating response stream from byte array");
- return byteResponseStream;
- }
- return null;
- }
- /**
- * Returns the response body of the HTTP method, if any, as a {@link String}.
- * If response body is not available or cannot be read, returns
null
- * The string conversion on the data is done using the character encoding specified
- * in
Content-Type
header. Buffers the response and this method can be
- * called several times yielding the same result each time.
- *
- * Note: This will cause the entire response body to be buffered in memory. A
- * malicious server may easily exhaust all the VM memory. It is strongly
- * recommended, to use getResponseAsStream if the content length of the response
- * is unknown or resonably large.
- *
- * @return The response body or
null
.
- *
- * @throws IOException If an I/O (transport) problem occurs while obtaining the
- * response body.
- */
- public String getResponseBodyAsString() throws IOException {
- byte[] rawdata = null;
- if (responseAvailable()) {
- rawdata = getResponseBody();
- }
- if (rawdata != null) {
- return EncodingUtil.getString(rawdata, getResponseCharSet());
- } else {
- return null;
- }
- }
- /**
- * Returns the response body of the HTTP method, if any, as a {@link String}.
- * If response body is not available or cannot be read, returns
null
- * The string conversion on the data is done using the character encoding specified
- * in
Content-Type
header. Buffers the response and this method can be
- * called several times yielding the same result each time.
- *
- * If the response is large this method involves lots of array copying and many object
- * allocations, which makes it unsuitable for high-performance / low-footprint applications.
- * Those applications should use {@link #getResponseBodyAsStream()}.
- *
- * @param maxlen the maximum content length to accept (number of bytes). Note that,
- * depending on the encoding, this is not equal to the number of characters.
- * @return The response body or
null
.
- *
- * @throws IOException If an I/O (transport) problem occurs while obtaining the
- * response body.
- */
- public String getResponseBodyAsString(int maxlen) throws IOException {
- if (maxlen < 0) throw new IllegalArgumentException("maxlen must be positive");
- byte[] rawdata = null;
- if (responseAvailable()) {
- rawdata = getResponseBody(maxlen);
- }
- if (rawdata != null) {
- return EncodingUtil.getString(rawdata, getResponseCharSet());
- } else {
- return null;
- }
- }
- /**
- * Returns an array of the response footers that the HTTP method currently has
- * in the order in which they were read.
- *
- * @return an array of footers
- */
- public Header[] getResponseFooters() {
- return getResponseTrailerHeaderGroup().getAllHeaders();
- }
- /**
- * Gets the response footer associated with the given name.
- * Footer name matching is case insensitive.
- *
null
will be returned if either
footerName
is
- *
null
or there is no matching footer for
footerName
- * or there are no footers available. If there are multiple footers
- * with the same name, there values will be combined with the ',' separator
- * as specified by RFC2616.
- *
- * @param footerName the footer name to match
- * @return the matching footer
- */
- public Header getResponseFooter(String footerName) {
- if (footerName == null) {
- return null;
- } else {
- return getResponseTrailerHeaderGroup().getCondensedHeader(footerName);
- }
- }
- /**
- * Sets the response stream.
- * @param responseStream The new response stream.
- */
- protected void setResponseStream(InputStream responseStream) {
- this.responseStream = responseStream;
- }
- /**
- * Returns a stream from which the body of the current response may be read.
- * If the method has not yet been executed, if
responseBodyConsumed
- * has been called, or if the stream returned by a previous call has been closed,
- *
null
will be returned.
- *
- * @return the current response stream
- */
- protected InputStream getResponseStream() {
- return responseStream;
- }
- /**
- * Returns the status text (or "reason phrase") associated with the latest
- * response.
- *
- * @return The status text.
- */
- public String getStatusText() {
- return statusLine.getReasonPhrase();
- }
- /**
- * Defines how strictly HttpClient follows the HTTP protocol specification
- * (RFC 2616 and other relevant RFCs). In the strict mode HttpClient precisely
- * implements the requirements of the specification, whereas in non-strict mode
- * it attempts to mimic the exact behaviour of commonly used HTTP agents,
- * which many HTTP servers expect.
- *
- * @param strictMode
true
for strict mode,
false
otherwise
- *
- * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
- * to exercise a more granular control over HTTP protocol strictness.
- */
- public void setStrictMode(boolean strictMode) {
- if (strictMode) {
- this.params.makeStrict();
- } else {
- this.params.makeLenient();
- }
- }
- /**
- * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
- * to exercise a more granular control over HTTP protocol strictness.
- *
- * @return
false
- */
- public boolean isStrictMode() {
- return false;
- }
- /**
- * Adds the specified request header, NOT overwriting any previous value.
- * Note that header-name matching is case insensitive.
- *
- * @param headerName the header's name
- * @param headerValue the header's value
- */
- public void addRequestHeader(String headerName, String headerValue) {
- addRequestHeader(new Header(headerName, headerValue));
- }
- /**
- * Tests if the connection should be force-closed when no longer needed.
- *
- * @return
true
if the connection must be closed
- */
- protected boolean isConnectionCloseForced() {
- return this.connectionCloseForced;
- }
- /**
- * Sets whether or not the connection should be force-closed when no longer
- * needed. This value should only be set to
true
in abnormal
- * circumstances, such as HTTP protocol violations.
- *
- * @param b
true
if the connection must be closed,
false
- * otherwise.
- */
- protected void setConnectionCloseForced(boolean b) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Force-close connection: " + b);
- }
- this.connectionCloseForced = b;
- }
- /**
- * Tests if the connection should be closed after the method has been executed.
- * The connection will be left open when using HTTP/1.1 or if
Connection:
- * keep-alive
header was sent.
- *
- * @param conn the connection in question
- *
- * @return boolean true if we should close the connection.
- */
- protected boolean shouldCloseConnection(HttpConnection conn) {
- // Connection must be closed due to an abnormal circumstance
- if (isConnectionCloseForced()) {
- LOG.debug("Should force-close connection.");
- return true;
- }
- Header connectionHeader = null;
- // In case being connected via a proxy server
- if (!conn.isTransparent()) {
- // Check for 'proxy-connection' directive
- connectionHeader = responseHeaders.getFirstHeader("proxy-connection");
- }
- // In all cases Check for 'connection' directive
- // some non-complaint proxy servers send it instread of
- // expected 'proxy-connection' directive
- if (connectionHeader == null) {
- connectionHeader = responseHeaders.getFirstHeader("connection");
- }
- // In case the response does not contain any explict connection
- // directives, check whether the request does
- if (connectionHeader == null) {
- connectionHeader = requestHeaders.getFirstHeader("connection");
- }
- if (connectionHeader != null) {
- if (connectionHeader.getValue().equalsIgnoreCase("close")) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Should close connection in response to directive: "
- + connectionHeader.getValue());
- }
- return true;
- } else if (connectionHeader.getValue().equalsIgnoreCase("keep-alive")) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Should NOT close connection in response to directive: "
- + connectionHeader.getValue());
- }
- return false;
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Unknown directive: " + connectionHeader.toExternalForm());
- }
- }
- }
- LOG.debug("Resorting to protocol version default close connection policy");
- // missing or invalid connection header, do the default
- if (this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Should NOT close connection, using " + this.effectiveVersion.toString());
- }
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Should close connection, using " + this.effectiveVersion.toString());
- }
- }
- return this.effectiveVersion.lessEquals(HttpVersion.HTTP_1_0);
- }
- /**
- * Tests if the this method is ready to be executed.
- *
- * @param state the {@link HttpState state} information associated with this method
- * @param conn the {@link HttpConnection connection} to be used
- * @throws HttpException If the method is in invalid state.
- */
- private void checkExecuteConditions(HttpState state, HttpConnection conn)
- throws HttpException {
- if (state == null) {
- throw new IllegalArgumentException("HttpState parameter may not be null");
- }
- if (conn == null) {
- throw new IllegalArgumentException("HttpConnection parameter may not be null");
- }
- if (this.aborted) {
- throw new IllegalStateException("Method has been aborted");
- }
- if (!validate()) {
- throw new ProtocolException("HttpMethodBase object not valid");
- }
- }
- /**
- * Executes this method using the specified
HttpConnection
and
- *
HttpState
.
- *
- * @param state {@link HttpState state} information to associate with this
- * request. Must be non-null.
- * @param conn the {@link HttpConnection connection} to used to execute
- * this HTTP method. Must be non-null.
- *
- * @return the integer status code if one was obtained, or
-1
- *
- * @throws IOException if an I/O (transport) error occurs
- * @throws HttpException if a protocol exception occurs.
- */
- public int execute(HttpState state, HttpConnection conn)
- throws HttpException, IOException {
- LOG.trace("enter HttpMethodBase.execute(HttpState, HttpConnection)");
- // this is our connection now, assign it to a local variable so
- // that it can be released later
- this.responseConnection = conn;
- checkExecuteConditions(state, conn);
- this.statusLine = null;
- this.connectionCloseForced = false;
- conn.setLastResponseInputStream(null);
- // determine the effective protocol version
- if (this.effectiveVersion == null) {
- this.effectiveVersion = this.params.getVersion();
- }
- writeRequest(state, conn);
- this.requestSent = true;
- readResponse(state, conn);
- // the method has successfully executed
- used = true;
- return statusLine.getStatusCode();
- }
- /**
- * Aborts the execution of this method.
- *
- * @since 3.0
- */
- public void abort() {
- if (this.aborted) {
- return;
- }
- this.aborted = true;
- HttpConnection conn = this.responseConnection;
- if (conn != null) {
- conn.close();
- }
- }
- /**
- * Returns
true
if the HTTP method has been already {@link #execute executed},
- * but not {@link #recycle recycled}.
- *
- * @return
true
if the method has been executed,
false
otherwise
- */
- public boolean hasBeenUsed() {
- return used;
- }
- /**
- * Recycles the HTTP method so that it can be used again.
- * Note that all of the instance variables will be reset
- * once this method has been called. This method will also
- * release the connection being used by this HTTP method.
- *
- * @see #releaseConnection()
- *
- * @deprecated no longer supported and will be removed in the future
- * version of HttpClient
- */
- public void recycle() {
- LOG.trace("enter HttpMethodBase.recycle()");
- releaseConnection();
- path = null;
- followRedirects = false;
- doAuthentication = true;
- queryString = null;
- getRequestHeaderGroup().clear();
- getResponseHeaderGroup().clear();
- getResponseTrailerHeaderGroup().clear();
- statusLine = null;
- effectiveVersion = null;
- aborted = false;
- used = false;
- params = new HttpMethodParams();
- responseBody = null;
- recoverableExceptionCount = 0;
- connectionCloseForced = false;
- hostAuthState.invalidate();
- proxyAuthState.invalidate();
- cookiespec = null;
- requestSent = false;
- }
- /**
- * Releases the connection being used by this HTTP method. In particular the
- * connection is used to read the response(if there is one) and will be held
- * until the response has been read. If the connection can be reused by other
- * HTTP methods it is NOT closed at this point.
- *
- * @since 2.0
- */
- public void releaseConnection() {
- try {
- if (this.responseStream != null) {
- try {
- // FYI - this may indirectly invoke responseBodyConsumed.
- this.responseStream.close();
- } catch (IOException ignore) {
- }
- }
- } finally {
- ensureConnectionRelease();
- }
- }
- /**
- * Remove the request header associated with the given name. Note that
- * header-name matching is case insensitive.
- *
- * @param headerName the header name
- */
- public void removeRequestHeader(String headerName) {
- Header[] headers = getRequestHeaderGroup().getHeaders(headerName);
- for (int i = 0; i < headers.length; i++) {
- getRequestHeaderGroup().removeHeader(headers[i]);
- }
- }
- /**
- * Removes the given request header.
- *
- * @param header the header
- */
- public void removeRequestHeader(final Header header) {
- if (header == null) {
- return;
- }
- getRequestHeaderGroup().removeHeader(header);
- }
- // ---------------------------------------------------------------- Queries
- /**
- * Returns
true
the method is ready to execute,
false
otherwise.
- *
- * @return This implementation always returns
true
.
- */
- public boolean validate() {
- return true;
- }
- /**
- * Returns the actual cookie policy
- *
- * @param state HTTP state. TODO: to be removed in the future
- *
- * @return cookie spec
- */
- private CookieSpec getCookieSpec(final HttpState state) {
- if (this.cookiespec == null) {
- int i = state.getCookiePolicy();
- if (i == -1) {
- this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy());
- } else {
- this.cookiespec = CookiePolicy.getSpecByPolicy(i);
- }
- this.cookiespec.setValidDateFormats(
- (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS));
- }
- return this.cookiespec;
- }
- /**
- * Generates
Cookie
request headers for those {@link Cookie cookie}s
- * that match the given host, port and path.
- *
- * @param state the {@link HttpState state} information associated with this method
- * @param conn the {@link HttpConnection connection} used to execute
- * this HTTP method
- *
- * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
- * can be recovered from.
- * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
- * cannot be recovered from.
- */
- protected void addCookieRequestHeader(HttpState state, HttpConnection conn)
- throws IOException, HttpException {
- LOG.trace("enter HttpMethodBase.addCookieRequestHeader(HttpState, "
- + "HttpConnection)");
- Header[] cookieheaders = getRequestHeaderGroup().getHeaders("Cookie");
- for (int i = 0; i < cookieheaders.length; i++) {
- Header cookieheader = cookieheaders[i];
- if (cookieheader.isAutogenerated()) {
- getRequestHeaderGroup().removeHeader(cookieheader);
- }
- }
- CookieSpec matcher = getCookieSpec(state);
- String host = this.params.getVirtualHost();
- if (host == null) {
- host = conn.getHost();
- }
- Cookie[] cookies = matcher.match(host, conn.getPort(),
- getPath(), conn.isSecure(), state.getCookies());
- if ((cookies != null) && (cookies.length > 0)) {
- if (getParams().isParameterTrue(HttpMethodParams.SINGLE_COOKIE_HEADER)) {
- // In strict mode put all cookies on the same header
- String s = matcher.formatCookies(cookies);
- getRequestHeaderGroup().addHeader(new Header("Cookie", s, true));
- } else {
- // In non-strict mode put each cookie on a separate header
- for (int i = 0; i < cookies.length; i++) {
- String s = matcher.formatCookie(cookies[i]);
- getRequestHeaderGroup().addHeader(new Header("Cookie", s, true));
- }
- }
- if (matcher instanceof CookieVersionSupport) {
- CookieVersionSupport versupport = (CookieVersionSupport) matcher;
- int ver = versupport.getVersion();
- boolean needVersionHeader = false;
- for (int i = 0; i < cookies.length; i++) {
- if (ver != cookies[i].getVersion()) {
- needVersionHeader = true;
- }
- }
- if (needVersionHeader) {
- // Advertise cookie version support
- getRequestHeaderGroup().addHeader(versupport.getVersionHeader());
- }
- }
- }
- }
- /**
- * Generates
Host
request header, as long as no
Host
request
- * header already exists.
- *
- * @param state the {@link HttpState state} information associated with this method
- * @param conn the {@link HttpConnection connection} used to execute
- * this HTTP method
- *
- * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
- * can be recovered from.
- * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
- * cannot be recovered from.
- */
- protected void addHostRequestHeader(HttpState state, HttpConnection conn)
- throws IOException, HttpException {
- LOG.trace("enter HttpMethodBase.addHostRequestHeader(HttpState, "
- + "HttpConnection)");
- // Per 19.6.1.1 of RFC 2616, it is legal for HTTP/1.0 based
- // applications to send the Host request-header.
- // TODO: Add the ability to disable the sending of this header for
- // HTTP/1.0 requests.
- String host = this.params.getVirtualHost();
- if (host != null) {
- LOG.debug("Using virtual host name: " + host);
- } else {
- host = conn.getHost();
- }
- int port = conn.getPort();
- // Note: RFC 2616 uses the term "internet host name" for what goes on the
- // host line. It would seem to imply that host should be blank if the
- // host is a number instead of an name. Based on the behavior of web
- // browsers, and the fact that RFC 2616 never defines the phrase "internet
- // host name", and the bad behavior of HttpClient that follows if we
- // send blank, I interpret this as a small misstatement in the RFC, where
- // they meant to say "internet host". So IP numbers get sent as host
- // entries too. -- Eric Johnson 12/13/2002
- if (LOG.isDebugEnabled()) {
- LOG.debug("Adding Host request header");
- }
- //appends the port only if not using the default port for the protocol
- if (conn.getProtocol().getDefaultPort() != port) {
- host += (":" + port);
- }
- setRequestHeader("Host", host);
- }
- /**
- * Generates
Proxy-Connection: Keep-Alive
request header when
- * communicating via a proxy server.
- *
- * @param state the {@link HttpState state} information associated with this method
- * @param conn the {@link HttpConnection connection} used to execute
- * this HTTP method
- *
- * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
- * can be recovered from.
- * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
- * cannot be recovered from.
- */
- protected void addProxyConnectionHeader(HttpState state,
- HttpConnection conn)
- throws IOException, HttpException {
- LOG.trace("enter HttpMethodBase.addProxyConnectionHeader("
- + "HttpState, HttpConnection)");
- if (!conn.isTransparent()) {
- if (getRequestHeader("Proxy-Connection") == null) {
- addRequestHeader("Proxy-Connection", "Keep-Alive");
- }
- }
- }
- /**
- * Generates all the required request {@link Header header}s
- * to be submitted via the given {@link HttpConnection connection}.
- *
- *
- * This implementation adds User-Agent , Host , - * Cookie , Authorization , Proxy-Authorization - * and Proxy-Connection headers, when appropriate. - *
- * - *- * Subclasses may want to override this method to to add additional - * headers, and may choose to invoke this implementation (via - * super ) to add the "standard" headers. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #writeRequestHeaders - */ - protected void addRequestHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter HttpMethodBase.addRequestHeaders(HttpState, " - + "HttpConnection)"); - addUserAgentRequestHeader(state, conn); - addHostRequestHeader(state, conn); - addCookieRequestHeader(state, conn); - addProxyConnectionHeader(state, conn); - } - /** - * Generates default User-Agent request header, as long as no - * User-Agent request header already exists. - * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - */ - protected void addUserAgentRequestHeader(HttpState state, - HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter HttpMethodBase.addUserAgentRequestHeaders(HttpState, " - + "HttpConnection)"); - if (getRequestHeader("User-Agent") == null) { - String agent = (String)getParams().getParameter(HttpMethodParams.USER_AGENT); - if (agent == null) { - agent = "Jakarta Commons-HttpClient"; - } - setRequestHeader("User-Agent", agent); - } - } - /** - * Throws an {@link IllegalStateException} if the HTTP method has been already - * {@link #execute executed}, but not {@link #recycle recycled}. - * - * @throws IllegalStateException if the method has been used and not - * recycled - */ - protected void checkNotUsed() throws IllegalStateException { - if (used) { - throw new IllegalStateException("Already used."); - } - } - /** - * Throws an {@link IllegalStateException} if the HTTP method has not been - * {@link #execute executed} since last {@link #recycle recycle}. - * - * - * @throws IllegalStateException if not used - */ - protected void checkUsed() throws IllegalStateException { - if (!used) { - throw new IllegalStateException("Not Used."); - } - } - // ------------------------------------------------- Static Utility Methods - /** - * Generates HTTP request line according to the specified attributes. - * - * @param connection the {@link HttpConnection connection} used to execute - * this HTTP method - * @param name the method name generate a request for - * @param requestPath the path string for the request - * @param query the query string for the request - * @param version the protocol version to use (e.g. HTTP/1.0) - * - * @return HTTP request line - */ - protected static String generateRequestLine(HttpConnection connection, - String name, String requestPath, String query, String version) { - LOG.trace("enter HttpMethodBase.generateRequestLine(HttpConnection, " - + "String, String, String, String)"); - StringBuffer buf = new StringBuffer(); - // Append method name - buf.append(name); - buf.append(" "); - // Absolute or relative URL? - if (!connection.isTransparent()) { - Protocol protocol = connection.getProtocol(); - buf.append(protocol.getScheme().toLowerCase()); - buf.append("://"); - buf.append(connection.getHost()); - if ((connection.getPort() != -1) - && (connection.getPort() != protocol.getDefaultPort()) - ) { - buf.append(":"); - buf.append(connection.getPort()); - } - } - // Append path, if any - if (requestPath == null) { - buf.append("/"); - } else { - if (!connection.isTransparent() && !requestPath.startsWith("/")) { - buf.append("/"); - } - buf.append(requestPath); - } - // Append query, if any - if (query != null) { - if (query.indexOf("?") != 0) { - buf.append("?"); - } - buf.append(query); - } - // Append protocol - buf.append(" "); - buf.append(version); - buf.append("\r\n"); - return buf.toString(); - } - /** - * This method is invoked immediately after - * {@link #readResponseBody(HttpState,HttpConnection)} and can be overridden by - * sub-classes in order to provide custom body processing. - * - *- * This implementation does nothing. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @see #readResponse - * @see #readResponseBody - */ - protected void processResponseBody(HttpState state, HttpConnection conn) { - } - /** - * This method is invoked immediately after - * {@link #readResponseHeaders(HttpState,HttpConnection)} and can be overridden by - * sub-classes in order to provide custom response headers processing. - *- * This implementation will handle the Set-Cookie and - * Set-Cookie2 headers, if any, adding the relevant cookies to - * the given {@link HttpState}. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @see #readResponse - * @see #readResponseHeaders - */ - protected void processResponseHeaders(HttpState state, - HttpConnection conn) { - LOG.trace("enter HttpMethodBase.processResponseHeaders(HttpState, " - + "HttpConnection)"); - CookieSpec parser = getCookieSpec(state); - // process set-cookie headers - Header[] headers = getResponseHeaderGroup().getHeaders("set-cookie"); - processCookieHeaders(parser, headers, state, conn); - // see if the cookie spec supports cookie versioning. - if (parser instanceof CookieVersionSupport) { - CookieVersionSupport versupport = (CookieVersionSupport) parser; - if (versupport.getVersion() > 0) { - // process set-cookie2 headers. - // Cookie2 will replace equivalent Cookie instances - headers = getResponseHeaderGroup().getHeaders("set-cookie2"); - processCookieHeaders(parser, headers, state, conn); - } - } - } - /** - * This method processes the specified cookie headers. It is invoked from - * within {@link #processResponseHeaders(HttpState,HttpConnection)} - * - * @param headers cookie {@link Header}s to be processed - * @param state the {@link HttpState state} information associated with - * this HTTP method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - */ - protected void processCookieHeaders( - final CookieSpec parser, - final Header[] headers, - final HttpState state, - final HttpConnection conn) { - LOG.trace("enter HttpMethodBase.processCookieHeaders(Header[], HttpState, " - + "HttpConnection)"); - String host = this.params.getVirtualHost(); - if (host == null) { - host = conn.getHost(); - } - for (int i = 0; i < headers.length; i++) { - Header header = headers[i]; - Cookie[] cookies = null; - try { - cookies = parser.parse( - host, - conn.getPort(), - getPath(), - conn.isSecure(), - header); - } catch (MalformedCookieException e) { - if (LOG.isWarnEnabled()) { - LOG.warn("Invalid cookie header: \"" - + header.getValue() - + "\". " + e.getMessage()); - } - } - if (cookies != null) { - for (int j = 0; j < cookies.length; j++) { - Cookie cookie = cookies[j]; - try { - parser.validate( - host, - conn.getPort(), - getPath(), - conn.isSecure(), - cookie); - state.addCookie(cookie); - if (LOG.isDebugEnabled()) { - LOG.debug("Cookie accepted: \"" - + parser.formatCookie(cookie) + "\""); - } - } catch (MalformedCookieException e) { - if (LOG.isWarnEnabled()) { - LOG.warn("Cookie rejected: \"" + parser.formatCookie(cookie) - + "\". " + e.getMessage()); - } - } - } - } - } - } - /** - * This method is invoked immediately after - * {@link #readStatusLine(HttpState,HttpConnection)} and can be overridden by - * sub-classes in order to provide custom response status line processing. - * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @see #readResponse - * @see #readStatusLine - */ - protected void processStatusLine(HttpState state, HttpConnection conn) { - } - /** - * Reads the response from the given {@link HttpConnection connection}. - * - *- * The response is processed as the following sequence of actions: - * - *
- * The current implementation wraps the socket level stream with - * an appropriate stream for the type of response (chunked, content-length, - * or auto-close). If there is no response body, the connection associated - * with the request will be returned to the connection manager. - *
- * - *- * Subclasses may want to override this method to to customize the - * processing. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #readResponse - * @see #processResponseBody - */ - protected void readResponseBody(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace( - "enter HttpMethodBase.readResponseBody(HttpState, HttpConnection)"); - // assume we are not done with the connection if we get a stream - InputStream stream = readResponseBody(conn); - if (stream == null) { - // done using the connection! - responseBodyConsumed(); - } else { - conn.setLastResponseInputStream(stream); - setResponseStream(stream); - } - } - /** - * Returns the response body as an {@link InputStream input stream} - * corresponding to the values of the Content-Length and - * Transfer-Encoding headers. If no response body is available - * returns null . - *- * - * @see #readResponse - * @see #processResponseBody - * - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - */ - private InputStream readResponseBody(HttpConnection conn) - throws HttpException, IOException { - LOG.trace("enter HttpMethodBase.readResponseBody(HttpConnection)"); - responseBody = null; - InputStream is = conn.getResponseInputStream(); - if (Wire.CONTENT_WIRE.enabled()) { - is = new WireLogInputStream(is, Wire.CONTENT_WIRE); - } - boolean canHaveBody = canResponseHaveBody(statusLine.getStatusCode()); - InputStream result = null; - Header transferEncodingHeader = responseHeaders.getFirstHeader("Transfer-Encoding"); - // We use Transfer-Encoding if present and ignore Content-Length. - // RFC2616, 4.4 item number 3 - if (transferEncodingHeader != null) { - String transferEncoding = transferEncodingHeader.getValue(); - if (!"chunked".equalsIgnoreCase(transferEncoding) - && !"identity".equalsIgnoreCase(transferEncoding)) { - if (LOG.isWarnEnabled()) { - LOG.warn("Unsupported transfer encoding: " + transferEncoding); - } - } - HeaderElement[] encodings = transferEncodingHeader.getElements(); - // The chunked encoding must be the last one applied - // RFC2616, 14.41 - int len = encodings.length; - if ((len > 0) && ("chunked".equalsIgnoreCase(encodings[len - 1].getName()))) { - // if response body is empty - if (conn.isResponseAvailable(conn.getParams().getSoTimeout())) { - result = new ChunkedInputStream(is, this); - } else { - if (getParams().isParameterTrue(HttpMethodParams.STRICT_TRANSFER_ENCODING)) { - throw new ProtocolException("Chunk-encoded body declared but not sent"); - } else { - LOG.warn("Chunk-encoded body missing"); - } - } - } else { - LOG.info("Response content is not chunk-encoded"); - // The connection must be terminated by closing - // the socket as per RFC 2616, 3.6 - setConnectionCloseForced(true); - result = is; - } - } else { - long expectedLength = getResponseContentLength(); - if (expectedLength == -1) { - if (canHaveBody && this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) { - Header connectionHeader = responseHeaders.getFirstHeader("Connection"); - String connectionDirective = null; - if (connectionHeader != null) { - connectionDirective = connectionHeader.getValue(); - } - if (!"close".equalsIgnoreCase(connectionDirective)) { - LOG.info("Response content length is not known"); - setConnectionCloseForced(true); - } - } - result = is; - } else { - result = new ContentLengthInputStream(is, expectedLength); - } - } - // See if the response is supposed to have a response body - if (!canHaveBody) { - result = null; - } - // if there is a result - ALWAYS wrap it in an observer which will - // close the underlying stream as soon as it is consumed, and notify - // the watcher that the stream has been consumed. - if (result != null) { - result = new AutoCloseInputStream( - result, - new ResponseConsumedWatcher() { - public void responseConsumed() { - responseBodyConsumed(); - } - } - ); - } - return result; - } - /** - * Reads the response headers from the given {@link HttpConnection connection}. - * - *
- * Subclasses may want to override this method to to customize the - * processing. - *
- * - *- * "It must be possible to combine the multiple header fields into one - * "field-name: field-value" pair, without changing the semantics of the - * message, by appending each subsequent field-value to the first, each - * separated by a comma." - HTTP/1.0 (4.3) - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #readResponse - * @see #processResponseHeaders - */ - protected void readResponseHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter HttpMethodBase.readResponseHeaders(HttpState," - + "HttpConnection)"); - getResponseHeaderGroup().clear(); - Header[] headers = HttpParser.parseHeaders( - conn.getResponseInputStream(), getParams().getHttpElementCharset()); - // Wire logging moved to HttpParser - getResponseHeaderGroup().setHeaders(headers); - } - /** - * Read the status line from the given {@link HttpConnection}, setting my - * {@link #getStatusCode status code} and {@link #getStatusText status - * text}. - * - *- * Subclasses may want to override this method to to customize the - * processing. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see StatusLine - */ - protected void readStatusLine(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter HttpMethodBase.readStatusLine(HttpState, HttpConnection)"); - final int maxGarbageLines = getParams(). - getIntParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE); - //read out the HTTP status string - int count = 0; - String s; - do { - s = conn.readLine(getParams().getHttpElementCharset()); - if (s == null && count == 0) { - // The server just dropped connection on us - throw new NoHttpResponseException("The server " + conn.getHost() + - " failed to respond"); - } - if (Wire.HEADER_WIRE.enabled()) { - Wire.HEADER_WIRE.input(s + "\r\n"); - } - if (s != null && StatusLine.startsWithHTTP(s)) { - // Got one - break; - } else if (s == null || count >= maxGarbageLines) { - // Giving up - throw new ProtocolException("The server " + conn.getHost() + - " failed to respond with a valid HTTP response"); - } - count++; - } while(true); - //create the status line from the status string - statusLine = new StatusLine(s); - //check for a valid HTTP-Version - String versionStr = statusLine.getHttpVersion(); - if (getParams().isParameterFalse(HttpMethodParams.UNAMBIGUOUS_STATUS_LINE) - && versionStr.equals("HTTP")) { - getParams().setVersion(HttpVersion.HTTP_1_0); - if (LOG.isWarnEnabled()) { - LOG.warn("Ambiguous status line (HTTP protocol version missing):" + - statusLine.toString()); - } - } else { - this.effectiveVersion = HttpVersion.parse(versionStr); - } - } - // ------------------------------------------------------ Protected Methods - /** - *- * Sends the request via the given {@link HttpConnection connection}. - *
- * - *- * The request is written as the following sequence of actions: - *
- * - *- * Subclasses may want to override one or more of the above methods to to - * customize the processing. (Or they may choose to override this method - * if dramatically different processing is required.) - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - */ - protected void writeRequest(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace( - "enter HttpMethodBase.writeRequest(HttpState, HttpConnection)"); - writeRequestLine(state, conn); - writeRequestHeaders(state, conn); - conn.writeLine(); // close head - if (Wire.HEADER_WIRE.enabled()) { - Wire.HEADER_WIRE.output("\r\n"); - } - HttpVersion ver = getParams().getVersion(); - Header expectheader = getRequestHeader("Expect"); - String expectvalue = null; - if (expectheader != null) { - expectvalue = expectheader.getValue(); - } - if ((expectvalue != null) - && (expectvalue.compareToIgnoreCase("100-continue") == 0)) { - if (ver.greaterEquals(HttpVersion.HTTP_1_1)) { - // make sure the status line and headers have been sent - conn.flushRequestOutputStream(); - int readTimeout = conn.getParams().getSoTimeout(); - try { - conn.setSocketTimeout(RESPONSE_WAIT_TIME_MS); - readStatusLine(state, conn); - processStatusLine(state, conn); - readResponseHeaders(state, conn); - processResponseHeaders(state, conn); - if (this.statusLine.getStatusCode() == HttpStatus.SC_CONTINUE) { - // Discard status line - this.statusLine = null; - LOG.debug("OK to continue received"); - } else { - return; - } - } catch (InterruptedIOException e) { - if (!ExceptionUtil.isSocketTimeoutException(e)) { - throw e; - } - // Most probably Expect header is not recongnized - // Remove the header to signal the method - // that it's okay to go ahead with sending data - removeRequestHeader("Expect"); - LOG.info("100 (continue) read timeout. Resume sending the request"); - } finally { - conn.setSocketTimeout(readTimeout); - } - } else { - removeRequestHeader("Expect"); - LOG.info("'Expect: 100-continue' handshake is only supported by " - + "HTTP/1.1 or higher"); - } - } - writeRequestBody(state, conn); - // make sure the entire request body has been sent - conn.flushRequestOutputStream(); - } - /** - * Writes the request body to the given {@link HttpConnection connection}. - * - *- * This method should return true if the request body was actually - * sent (or is empty), or false if it could not be sent for some - * reason. - *
- * - *- * This implementation writes nothing and returns true . - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @return true - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - */ - protected boolean writeRequestBody(HttpState state, HttpConnection conn) - throws IOException, HttpException { - return true; - } - /** - * Writes the request headers to the given {@link HttpConnection connection}. - * - *- * This implementation invokes {@link #addRequestHeaders(HttpState,HttpConnection)}, - * and then writes each header to the request stream. - *
- * - *- * Subclasses may want to override this method to to customize the - * processing. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #addRequestHeaders - * @see #getRequestHeaders - */ - protected void writeRequestHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter HttpMethodBase.writeRequestHeaders(HttpState," - + "HttpConnection)"); - addRequestHeaders(state, conn); - String charset = getParams().getHttpElementCharset(); - Header[] headers = getRequestHeaders(); - for (int i = 0; i < headers.length; i++) { - String s = headers[i].toExternalForm(); - if (Wire.HEADER_WIRE.enabled()) { - Wire.HEADER_WIRE.output(s); - } - conn.print(s, charset); - } - } - /** - * Writes the request line to the given {@link HttpConnection connection}. - * - *- * Subclasses may want to override this method to to customize the - * processing. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #generateRequestLine - */ - protected void writeRequestLine(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace( - "enter HttpMethodBase.writeRequestLine(HttpState, HttpConnection)"); - String requestLine = getRequestLine(conn); - if (Wire.HEADER_WIRE.enabled()) { - Wire.HEADER_WIRE.output(requestLine); - } - conn.print(requestLine, getParams().getHttpElementCharset()); - } - /** - * Returns the request line. - * - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @return The request line. - */ - private String getRequestLine(HttpConnection conn) { - return HttpMethodBase.generateRequestLine(conn, getName(), - getPath(), getQueryString(), this.effectiveVersion.toString()); - } - /** - * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method. - * - * @return HTTP parameters. - * - * @since 3.0 - */ - public HttpMethodParams getParams() { - return this.params; - } - /** - * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method. - * - * @since 3.0 - * - * @see HttpMethodParams - */ - public void setParams(final HttpMethodParams params) { - if (params == null) { - throw new IllegalArgumentException("Parameters may not be null"); - } - this.params = params; - } - /** - * Returns the HTTP version used with this method (may be null - * if undefined, that is, the method has not been executed) - * - * @return HTTP version. - * - * @since 3.0 - */ - public HttpVersion getEffectiveVersion() { - return this.effectiveVersion; - } - /** - * Per RFC 2616 section 4.3, some response can never contain a message - * body. - * - * @param status - the HTTP status code - * - * @return true if the message may contain a body, false if it can not - * contain a message body - */ - private static boolean canResponseHaveBody(int status) { - LOG.trace("enter HttpMethodBase.canResponseHaveBody(int)"); - boolean result = true; - if ((status >= 100 && status <= 199) || (status == 204) - || (status == 304)) { // NOT MODIFIED - result = false; - } - return result; - } - /** - * Returns proxy authentication realm, if it has been used during authentication process. - * Otherwise returns null . - * - * @return proxy authentication realm - * - * @deprecated use #getProxyAuthState() - */ - public String getProxyAuthenticationRealm() { - return this.proxyAuthState.getRealm(); - } - /** - * Returns authentication realm, if it has been used during authentication process. - * Otherwise returns null . - * - * @return authentication realm - * - * @deprecated use #getHostAuthState() - */ - public String getAuthenticationRealm() { - return this.hostAuthState.getRealm(); - } - /** - * Returns the character set from the Content-Type header. - * - * @param contentheader The content header. - * @return String The character set. - */ - protected String getContentCharSet(Header contentheader) { - LOG.trace("enter getContentCharSet( Header contentheader )"); - String charset = null; - if (contentheader != null) { - HeaderElement values[] = contentheader.getElements(); - // I expect only one header element to be there - // No more. no less - if (values.length == 1) { - NameValuePair param = values[0].getParameterByName("charset"); - if (param != null) { - // If I get anything "funny" - // UnsupportedEncondingException will result - charset = param.getValue(); - } - } - } - if (charset == null) { - charset = getParams().getContentCharset(); - if (LOG.isDebugEnabled()) { - LOG.debug("Default charset used: " + charset); - } - } - return charset; - } - /** - * Returns the character encoding of the request from the Content-Type header. - * - * @return String The character set. - */ - public String getRequestCharSet() { - return getContentCharSet(getRequestHeader("Content-Type")); - } - /** - * Returns the character encoding of the response from the Content-Type header. - * - * @return String The character set. - */ - public String getResponseCharSet() { - return getContentCharSet(getResponseHeader("Content-Type")); - } - /** - * @deprecated no longer used - * - * Returns the number of "recoverable" exceptions thrown and handled, to - * allow for monitoring the quality of the connection. - * - * @return The number of recoverable exceptions handled by the method. - */ - public int getRecoverableExceptionCount() { - return recoverableExceptionCount; - } - /** - * A response has been consumed. - * - *The default behavior for this class is to check to see if the connection - * should be closed, and close if need be, and to ensure that the connection - * is returned to the connection manager - if and only if we are not still - * inside the execute call.
- * - */ - protected void responseBodyConsumed() { - // make sure this is the initial invocation of the notification, - // ignore subsequent ones. - responseStream = null; - if (responseConnection != null) { - responseConnection.setLastResponseInputStream(null); - // At this point, no response data should be available. - // If there is data available, regard the connection as being - // unreliable and close it. - if (shouldCloseConnection(responseConnection)) { - responseConnection.close(); - } else { - try { - if(responseConnection.isResponseAvailable()) { - boolean logExtraInput = - getParams().isParameterTrue(HttpMethodParams.WARN_EXTRA_INPUT); - if(logExtraInput) { - LOG.warn("Extra response data detected - closing connection"); - } - responseConnection.close(); - } - } - catch (IOException e) { - LOG.warn(e.getMessage()); - responseConnection.close(); - } - } - } - this.connectionCloseForced = false; - ensureConnectionRelease(); - } - /** - * Insure that the connection is released back to the pool. - */ - private void ensureConnectionRelease() { - if (responseConnection != null) { - responseConnection.releaseConnection(); - responseConnection = null; - } - } - /** - * Returns the {@link HostConfiguration host configuration}. - * - * @return the host configuration - * - * @deprecated no longer applicable - */ - public HostConfiguration getHostConfiguration() { - HostConfiguration hostconfig = new HostConfiguration(); - hostconfig.setHost(this.httphost); - return hostconfig; - } - /** - * Sets the {@link HostConfiguration host configuration}. - * - * @param hostconfig The hostConfiguration to set - * - * @deprecated no longer applicable - */ - public void setHostConfiguration(final HostConfiguration hostconfig) { - if (hostconfig != null) { - this.httphost = new HttpHost( - hostconfig.getHost(), - hostconfig.getPort(), - hostconfig.getProtocol()); - } else { - this.httphost = null; - } - } - /** - * Returns the {@link MethodRetryHandler retry handler} for this HTTP method - * - * @return the methodRetryHandler - * - * @deprecated use {@link HttpMethodParams} - */ - public MethodRetryHandler getMethodRetryHandler() { - return methodRetryHandler; - } - /** - * Sets the {@link MethodRetryHandler retry handler} for this HTTP method - * - * @param handler the methodRetryHandler to use when this method executed - * - * @deprecated use {@link HttpMethodParams} - */ - public void setMethodRetryHandler(MethodRetryHandler handler) { - methodRetryHandler = handler; - } - /** - * This method is a dirty hack intended to work around - * current (2.0) design flaw that prevents the user from - * obtaining correct status code, headers and response body from the - * preceding HTTP CONNECT method. - * - * TODO: Remove this crap as soon as possible - */ - void fakeResponse( - StatusLine statusline, - HeaderGroup responseheaders, - InputStream responseStream - ) { - // set used so that the response can be read - this.used = true; - this.statusLine = statusline; - this.responseHeaders = responseheaders; - this.responseBody = null; - this.responseStream = responseStream; - } - /** - * Returns the target host {@link AuthState authentication state} - * - * @return host authentication state - * - * @since 3.0 - */ - public AuthState getHostAuthState() { - return this.hostAuthState; - } - /** - * Returns the proxy {@link AuthState authentication state} - * - * @return host authentication state - * - * @since 3.0 - */ - public AuthState getProxyAuthState() { - return this.proxyAuthState; - } - /** - * Tests whether the execution of this method has been aborted - * - * @return true if the execution of this method has been aborted, - * false otherwise - * - * @since 3.0 - */ - public boolean isAborted() { - return this.aborted; - } - /** - * Returns true if the HTTP has been transmitted to the target - * server in its entirety, false otherwise. This flag can be useful - * for recovery logic. If the request has not been transmitted in its entirety, - * it is safe to retry the failed method. - * - * @return true if the request has been sent, false otherwise - */ - public boolean isRequestSent() { - return this.requestSent; - } diff --git a/clients/java/src/org/apache/commons/httpclient/HttpMethodDirector.java b/clients/java/src/org/apache/commons/httpclient/HttpMethodDirector.java deleted file mode 100644 index 13dd480..0000000 --- a/clients/java/src/org/apache/commons/httpclient/HttpMethodDirector.java +++ /dev/null @@ -1,939 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodDirector.java,v 1.34 2005/01/14 19:40:39 olegk Exp $ - * $Revision: 486658 $ - * $Date: 2006-12-13 15:05:50 +0100 (Wed, 13 Dec 2006) $ - * ==================================================================== - * 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 - *
true
if the connect was successful
- *
- * @throws IOException
- * @throws HttpException
- */
- private boolean executeConnect()
- throws IOException, HttpException {
- this.connectMethod = new ConnectMethod(this.hostConfiguration);
- this.connectMethod.getParams().setDefaults(this.hostConfiguration.getParams());
- int code;
- for (;;) {
- if (!this.conn.isOpen()) {
- this.conn.open();
- }
- if (this.params.isAuthenticationPreemptive()
- || this.state.isAuthenticationPreemptive()) {
- LOG.debug("Preemptively sending default basic credentials");
- this.connectMethod.getProxyAuthState().setPreemptive();
- this.connectMethod.getProxyAuthState().setAuthAttempted(true);
- }
- try {
- authenticateProxy(this.connectMethod);
- } catch (AuthenticationException e) {
- LOG.error(e.getMessage(), e);
- }
- applyConnectionParams(this.connectMethod);
- this.connectMethod.execute(state, this.conn);
- code = this.connectMethod.getStatusCode();
- boolean retry = false;
- AuthState authstate = this.connectMethod.getProxyAuthState();
- authstate.setAuthRequested(code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
- if (authstate.isAuthRequested()) {
- if (processAuthenticationResponse(this.connectMethod)) {
- retry = true;
- }
- }
- if (!retry) {
- break;
- }
- if (this.connectMethod.getResponseBodyAsStream() != null) {
- this.connectMethod.getResponseBodyAsStream().close();
- }
- }
- if ((code >= 200) && (code < 300)) {
- this.conn.tunnelCreated();
- // Drop the connect method, as it is no longer needed
- this.connectMethod = null;
- return true;
- } else {
- this.conn.close();
- return false;
- }
- }
- /**
- * Fake response
- * @param method
- * @return
- */
- private void fakeResponse(final HttpMethod method)
- throws IOException, HttpException {
- // What is to follow is an ugly hack.
- // I REALLY hate having to resort to such
- // an appalling trick
- // The only feasible solution is to split monolithic
- // HttpMethod into HttpRequest/HttpResponse pair.
- // That would allow to execute CONNECT method
- // behind the scene and return CONNECT HttpResponse
- // object in response to the original request that
- // contains the correct status line, headers &
- // response body.
- LOG.debug("CONNECT failed, fake the response for the original method");
- // Pass the status, headers and response stream to the wrapped
- // method.
- // To ensure that the connection is not released more than once
- // this method is still responsible for releasing the connection.
- // This will happen when the response body is consumed, or when
- // the wrapped method closes the response connection in
- // releaseConnection().
- if (method instanceof HttpMethodBase) {
- ((HttpMethodBase) method).fakeResponse(
- this.connectMethod.getStatusLine(),
- this.connectMethod.getResponseHeaderGroup(),
- this.connectMethod.getResponseBodyAsStream()
- );
- method.getProxyAuthState().setAuthScheme(
- this.connectMethod.getProxyAuthState().getAuthScheme());
- this.connectMethod = null;
- } else {
- releaseConnection = true;
- LOG.warn(
- "Unable to fake response on method as it is not derived from HttpMethodBase.");
- }
- }
- /**
- * Process the redirect response.
- *
- * @return
true
if the redirect was successful
- */
- private boolean processRedirectResponse(final HttpMethod method)
- throws RedirectException {
- //get the location header to find out where to redirect to
- Header locationHeader = method.getResponseHeader("location");
- if (locationHeader == null) {
- // got a redirect response, but no location header
- LOG.error("Received redirect response " + method.getStatusCode()
- + " but no location header");
- return false;
- }
- String location = locationHeader.getValue();
- if (LOG.isDebugEnabled()) {
- LOG.debug("Redirect requested to location '" + location + "'");
- }
- //rfc2616 demands the location value be a complete URI
- //Location = "Location" ":" absoluteURI
- URI redirectUri = null;
- URI currentUri = null;
- try {
- currentUri = new URI(
- this.conn.getProtocol().getScheme(),
- null,
- this.conn.getHost(),
- this.conn.getPort(),
- method.getPath()
- );
- String charset = method.getParams().getUriCharset();
- redirectUri = new URI(location, true, charset);
- if (redirectUri.isRelativeURI()) {
- if (this.params.isParameterTrue(HttpClientParams.REJECT_RELATIVE_REDIRECT)) {
- LOG.warn("Relative redirect location '" + location + "' not allowed");
- return false;
- } else {
- //location is incomplete, use current values for defaults
- LOG.debug("Redirect URI is not absolute - parsing as relative");
- redirectUri = new URI(currentUri, redirectUri);
- }
- } else {
- // Reset the default params
- method.getParams().setDefaults(this.params);
- }
- method.setURI(redirectUri);
- hostConfiguration.setHost(redirectUri);
- } catch (URIException ex) {
- throw new InvalidRedirectLocationException(
- "Invalid redirect location: " + location, location, ex);
- }
- if (this.params.isParameterFalse(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS)) {
- if (this.redirectLocations == null) {
- this.redirectLocations = new HashSet();
- }
- this.redirectLocations.add(currentUri);
- try {
- if(redirectUri.hasQuery()) {
- redirectUri.setQuery(null);
- }
- } catch (URIException e) {
- // Should never happen
- return false;
- }
- if (this.redirectLocations.contains(redirectUri)) {
- throw new CircularRedirectException("Circular redirect to '" +
- redirectUri + "'");
- }
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("Redirecting from '" + currentUri.getEscapedURI()
- + "' to '" + redirectUri.getEscapedURI());
- }
- //And finally invalidate the actual authentication scheme
- method.getHostAuthState().invalidate();
- return true;
- }
- /**
- * Processes a response that requires authentication
- *
- * @param method the current {@link HttpMethod HTTP method}
- *
- * @return
true
if the authentication challenge can be responsed to,
- * (that is, at least one of the requested authentication scheme is supported,
- * and matching credentials have been found),
false
otherwise.
- */
- private boolean processAuthenticationResponse(final HttpMethod method) {
- LOG.trace("enter HttpMethodBase.processAuthenticationResponse("
- + "HttpState, HttpConnection)");
- try {
- switch (method.getStatusCode()) {
- case HttpStatus.SC_UNAUTHORIZED:
- return processWWWAuthChallenge(method);
- case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
- return processProxyAuthChallenge(method);
- default:
- return false;
- }
- } catch (Exception e) {
- if (LOG.isErrorEnabled()) {
- LOG.error(e.getMessage(), e);
- }
- return false;
- }
- }
- private boolean processWWWAuthChallenge(final HttpMethod method)
- throws MalformedChallengeException, AuthenticationException
- {
- AuthState authstate = method.getHostAuthState();
- Map challenges = AuthChallengeParser.parseChallenges(
- method.getResponseHeaders(WWW_AUTH_CHALLENGE));
- if (challenges.isEmpty()) {
- LOG.debug("Authentication challenge(s) not found");
- return false;
- }
- AuthScheme authscheme = null;
- try {
- authscheme = this.authProcessor.processChallenge(authstate, challenges);
- } catch (AuthChallengeException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn(e.getMessage());
- }
- }
- if (authscheme == null) {
- return false;
- }
- String host = method.getParams().getVirtualHost();
- if (host == null) {
- host = conn.getHost();
- }
- int port = conn.getPort();
- AuthScope authscope = new AuthScope(
- host, port,
- authscheme.getRealm(),
- authscheme.getSchemeName());
- if (LOG.isDebugEnabled()) {
- LOG.debug("Authentication scope: " + authscope);
- }
- if (authstate.isAuthAttempted() && authscheme.isComplete()) {
- // Already tried and failed
- Credentials credentials = promptForCredentials(
- authscheme, method.getParams(), authscope);
- if (credentials == null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Failure authenticating with " + authscope);
- }
- return false;
- } else {
- return true;
- }
- } else {
- authstate.setAuthAttempted(true);
- Credentials credentials = this.state.getCredentials(authscope);
- if (credentials == null) {
- credentials = promptForCredentials(
- authscheme, method.getParams(), authscope);
- }
- if (credentials == null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("No credentials available for " + authscope);
- }
- return false;
- } else {
- return true;
- }
- }
- }
- private boolean processProxyAuthChallenge(final HttpMethod method)
- throws MalformedChallengeException, AuthenticationException
- {
- AuthState authstate = method.getProxyAuthState();
- Map proxyChallenges = AuthChallengeParser.parseChallenges(
- method.getResponseHeaders(PROXY_AUTH_CHALLENGE));
- if (proxyChallenges.isEmpty()) {
- LOG.debug("Proxy authentication challenge(s) not found");
- return false;
- }
- AuthScheme authscheme = null;
- try {
- authscheme = this.authProcessor.processChallenge(authstate, proxyChallenges);
- } catch (AuthChallengeException e) {
- if (LOG.isWarnEnabled()) {
- LOG.warn(e.getMessage());
- }
- }
- if (authscheme == null) {
- return false;
- }
- AuthScope authscope = new AuthScope(
- conn.getProxyHost(), conn.getProxyPort(),
- authscheme.getRealm(),
- authscheme.getSchemeName());
- if (LOG.isDebugEnabled()) {
- LOG.debug("Proxy authentication scope: " + authscope);
- }
- if (authstate.isAuthAttempted() && authscheme.isComplete()) {
- // Already tried and failed
- Credentials credentials = promptForProxyCredentials(
- authscheme, method.getParams(), authscope);
- if (credentials == null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("Failure authenticating with " + authscope);
- }
- return false;
- } else {
- return true;
- }
- } else {
- authstate.setAuthAttempted(true);
- Credentials credentials = this.state.getProxyCredentials(authscope);
- if (credentials == null) {
- credentials = promptForProxyCredentials(
- authscheme, method.getParams(), authscope);
- }
- if (credentials == null) {
- if (LOG.isInfoEnabled()) {
- LOG.info("No credentials available for " + authscope);
- }
- return false;
- } else {
- return true;
- }
- }
- }
- /**
- * Tests if the {@link HttpMethod method} requires a redirect to another location.
- *
- * @param method HTTP method
- *
- * @return boolean
true
if a retry is needed,
false
otherwise.
- */
- private boolean isRedirectNeeded(final HttpMethod method) {
- switch (method.getStatusCode()) {
- case HttpStatus.SC_MOVED_TEMPORARILY:
- case HttpStatus.SC_MOVED_PERMANENTLY:
- case HttpStatus.SC_SEE_OTHER:
- case HttpStatus.SC_TEMPORARY_REDIRECT:
- LOG.debug("Redirect required");
- if (method.getFollowRedirects()) {
- return true;
- } else {
- return false;
- }
- default:
- return false;
- } //end of switch
- }
- /**
- * Tests if the {@link HttpMethod method} requires authentication.
- *
- * @param method HTTP method
- *
- * @return boolean
true
if a retry is needed,
false
otherwise.
- */
- private boolean isAuthenticationNeeded(final HttpMethod method) {
- method.getHostAuthState().setAuthRequested(
- method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED);
- method.getProxyAuthState().setAuthRequested(
- method.getStatusCode() == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
- if (method.getHostAuthState().isAuthRequested() ||
- method.getProxyAuthState().isAuthRequested()) {
- LOG.debug("Authorization required");
- if (method.getDoAuthentication()) { //process authentication response
- return true;
- } else { //let the client handle the authenticaiton
- LOG.info("Authentication requested but doAuthentication is "
- + "disabled");
- return false;
- }
- } else {
- return false;
- }
- }
- private Credentials promptForCredentials(
- final AuthScheme authScheme,
- final HttpParams params,
- final AuthScope authscope)
- {
- LOG.debug("Credentials required");
- Credentials creds = null;
- CredentialsProvider credProvider =
- (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER);
- if (credProvider != null) {
- try {
- creds = credProvider.getCredentials(
- authScheme, authscope.getHost(), authscope.getPort(), false);
- } catch (CredentialsNotAvailableException e) {
- LOG.warn(e.getMessage());
- }
- if (creds != null) {
- this.state.setCredentials(authscope, creds);
- if (LOG.isDebugEnabled()) {
- LOG.debug(authscope + " new credentials given");
- }
- }
- } else {
- LOG.debug("Credentials provider not available");
- }
- return creds;
- }
- private Credentials promptForProxyCredentials(
- final AuthScheme authScheme,
- final HttpParams params,
- final AuthScope authscope)
- {
- LOG.debug("Proxy credentials required");
- Credentials creds = null;
- CredentialsProvider credProvider =
- (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER);
- if (credProvider != null) {
- try {
- creds = credProvider.getCredentials(
- authScheme, authscope.getHost(), authscope.getPort(), true);
- } catch (CredentialsNotAvailableException e) {
- LOG.warn(e.getMessage());
- }
- if (creds != null) {
- this.state.setProxyCredentials(authscope, creds);
- if (LOG.isDebugEnabled()) {
- LOG.debug(authscope + " new credentials given");
- }
- }
- } else {
- LOG.debug("Proxy credentials provider not available");
- }
- return creds;
- }
- /**
- * @return
- */
- public HostConfiguration getHostConfiguration() {
- return hostConfiguration;
- }
- /**
- * @return
- */
- public HttpState getState() {
- return state;
- }
- /**
- * @return
- */
- public HttpConnectionManager getConnectionManager() {
- return connectionManager;
- }
- /**
- * @return
- */
- public HttpParams getParams() {
- return this.params;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpMethodRetryHandler.java b/clients/java/src/org/apache/commons/httpclient/HttpMethodRetryHandler.java
deleted file mode 100644
index 7ffd350..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpMethodRetryHandler.java
+++ /dev/null
@@ -1,65 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodRetryHandler.java,v 1.2 2004/09/14 20:11:31 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
true
if the method should be retried,
false
- * otherwise
- */
- boolean retryMethod(HttpMethod method, IOException exception, int executionCount);
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpParser.java b/clients/java/src/org/apache/commons/httpclient/HttpParser.java
deleted file mode 100644
index 45857e3..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpParser.java
+++ /dev/null
@@ -1,235 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpParser.java,v 1.13 2005/01/11 13:57:06 oglueck Exp $
- * $Revision: 533405 $
- * $Date: 2007-04-28 20:19:29 +0200 (Sat, 28 Apr 2007) $
- * ====================================================================
- * 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
- *
null
is returned.
- *
- * @param inputStream the stream to read from
- *
- * @throws IOException if an I/O problem occurs
- * @return a byte array from the stream
- */
- public static byte[] readRawLine(InputStream inputStream) throws IOException {
- LOG.trace("enter HttpParser.readRawLine()");
- ByteArrayOutputStream buf = new ByteArrayOutputStream();
- int ch;
- while ((ch = inputStream.read()) >= 0) {
- buf.write(ch);
- if (ch == '\n') { // be tolerant (RFC-2616 Section 19.3)
- break;
- }
- }
- if (buf.size() == 0) {
- return null;
- }
- return buf.toByteArray();
- }
- /**
- * Read up to
"\n"
from an (unchunked) input stream.
- * If the stream ends before the line terminator is found,
- * the last part of the string will still be returned.
- * If no input data available,
null
is returned.
- *
- * @param inputStream the stream to read from
- * @param charset charset of HTTP protocol elements
- *
- * @throws IOException if an I/O problem occurs
- * @return a line from the stream
- *
- * @since 3.0
- */
- public static String readLine(InputStream inputStream, String charset) throws IOException {
- LOG.trace("enter HttpParser.readLine(InputStream, String)");
- byte[] rawdata = readRawLine(inputStream);
- if (rawdata == null) {
- return null;
- }
- // strip CR and LF from the end
- int len = rawdata.length;
- int offset = 0;
- if (len > 0) {
- if (rawdata[len - 1] == '\n') {
- offset++;
- if (len > 1) {
- if (rawdata[len - 2] == '\r') {
- offset++;
- }
- }
- }
- }
- final String result =
- EncodingUtil.getString(rawdata, 0, len - offset, charset);
- if (Wire.HEADER_WIRE.enabled()) {
- String logoutput = result;
- if (offset == 2)
- logoutput = result + "\r\n";
- else if (offset == 1)
- logoutput = result + "\n";
- Wire.HEADER_WIRE.input(logoutput);
- }
- return result;
- }
- /**
- * Read up to
"\n"
from an (unchunked) input stream.
- * If the stream ends before the line terminator is found,
- * the last part of the string will still be returned.
- * If no input data available,
null
is returned
- *
- * @param inputStream the stream to read from
- *
- * @throws IOException if an I/O problem occurs
- * @return a line from the stream
- *
- * @deprecated use #readLine(InputStream, String)
- */
- public static String readLine(InputStream inputStream) throws IOException {
- LOG.trace("enter HttpParser.readLine(InputStream)");
- return readLine(inputStream, "US-ASCII");
- }
- /**
- * Parses headers from the given stream. Headers with the same name are not
- * combined.
- *
- * @param is the stream to read headers from
- * @param charset the charset to use for reading the data
- *
- * @return an array of headers in the order in which they were parsed
- *
- * @throws IOException if an IO error occurs while reading from the stream
- * @throws HttpException if there is an error parsing a header value
- *
- * @since 3.0
- */
- public static Header[] parseHeaders(InputStream is, String charset) throws IOException, HttpException {
- LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)");
- ArrayList headers = new ArrayList();
- String name = null;
- StringBuffer value = null;
- for (; ;) {
- String line = HttpParser.readLine(is, charset);
- if ((line == null) || (line.trim().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 ((line.charAt(0) == ' ') || (line.charAt(0) == '\t')) {
- // we have continuation folded header
- // so append value
- if (value != null) {
- value.append(' ');
- value.append(line.trim());
- }
- } else {
- // make sure we save the previous name,value pair if present
- if (name != null) {
- headers.add(new Header(name, value.toString()));
- }
- // Otherwise we should have normal HTTP header line
- // Parse the header name and value
- int colon = line.indexOf(":");
- if (colon < 0) {
- throw new ProtocolException("Unable to parse header: " + line);
- }
- name = line.substring(0, colon).trim();
- value = new StringBuffer(line.substring(colon + 1).trim());
- }
- }
- // make sure we save the last name,value pair if present
- if (name != null) {
- headers.add(new Header(name, value.toString()));
- }
- return (Header[]) headers.toArray(new Header[headers.size()]);
- }
- /**
- * Parses headers from the given stream. Headers with the same name are not
- * combined.
- *
- * @param is the stream to read headers from
- *
- * @return an array of headers in the order in which they were parsed
- *
- * @throws IOException if an IO error occurs while reading from the stream
- * @throws HttpException if there is an error parsing a header value
- *
- * @deprecated use #parseHeaders(InputStream, String)
- */
- public static Header[] parseHeaders(InputStream is) throws IOException, HttpException {
- LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)");
- return parseHeaders(is, "US-ASCII");
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpRecoverableException.java b/clients/java/src/org/apache/commons/httpclient/HttpRecoverableException.java
deleted file mode 100644
index aa44b33..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpRecoverableException.java
+++ /dev/null
@@ -1,64 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpRecoverableException.java,v 1.15 2004/07/05 22:46:58 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
true
when using HTTPS
- *
- * @return an array of {@link Cookie cookies}.
- *
- * @see #getCookies()
- *
- * @deprecated use CookieSpec#match(String, int, String, boolean, Cookie)
- */
- public synchronized Cookie[] getCookies(
- String domain,
- int port,
- String path,
- boolean secure
- ) {
- LOG.trace("enter HttpState.getCookies(String, int, String, boolean)");
- CookieSpec matcher = CookiePolicy.getDefaultSpec();
- ArrayList list = new ArrayList(cookies.size());
- for (int i = 0, m = cookies.size(); i < m; i++) {
- Cookie cookie = (Cookie) (cookies.get(i));
- if (matcher.match(domain, port, path, secure, cookie)) {
- list.add(cookie);
- }
- }
- return (Cookie[]) (list.toArray(new Cookie[list.size()]));
- }
- /**
- * Removes all of {@link Cookie cookies} in this HTTP state
- * that have expired according to the current system time.
- *
- * @see #purgeExpiredCookies(java.util.Date)
- *
- */
- public synchronized boolean purgeExpiredCookies() {
- LOG.trace("enter HttpState.purgeExpiredCookies()");
- return purgeExpiredCookies(new Date());
- }
- /**
- * Removes all of {@link Cookie cookies} in this HTTP state
- * that have expired by the specified {@link java.util.Date date}.
- *
- * @param date The {@link java.util.Date date} to compare against.
- *
- * @return true if any cookies were purged.
- *
- * @see Cookie#isExpired(java.util.Date)
- *
- * @see #purgeExpiredCookies()
- */
- public synchronized boolean purgeExpiredCookies(Date date) {
- LOG.trace("enter HttpState.purgeExpiredCookies(Date)");
- boolean removed = false;
- Iterator it = cookies.iterator();
- while (it.hasNext()) {
- if (((Cookie) (it.next())).isExpired(date)) {
- it.remove();
- removed = true;
- }
- }
- return removed;
- }
- /**
- * Returns the current {@link CookiePolicy cookie policy} for this
- * HTTP state.
- *
- * @return The {@link CookiePolicy cookie policy}.
- *
- * @deprecated Use
- * {@link org.apache.commons.httpclient.params.HttpMethodParams#getCookiePolicy()},
- * {@link HttpMethod#getParams()}.
- */
- public int getCookiePolicy() {
- return this.cookiePolicy;
- }
- /**
- * Defines whether preemptive authentication should be
- * attempted.
- *
- * @param value
true
if preemptive authentication should be
- * attempted,
false
otherwise.
- *
- * @deprecated Use
- * {@link org.apache.commons.httpclient.params.HttpClientParams#setAuthenticationPreemptive(boolean)},
- * {@link HttpClient#getParams()}.
- */
- public void setAuthenticationPreemptive(boolean value) {
- this.preemptive = value;
- }
- /**
- * Returns
true
if preemptive authentication should be
- * attempted,
false
otherwise.
- *
- * @return boolean flag.
- *
- * @deprecated Use
- * {@link org.apache.commons.httpclient.params.HttpClientParams#isAuthenticationPreemptive()},
- * {@link HttpClient#getParams()}.
- */
- public boolean isAuthenticationPreemptive() {
- return this.preemptive;
- }
- /**
- * Sets the current {@link CookiePolicy cookie policy} for this HTTP
- * state to one of the following supported policies:
- * {@link CookiePolicy#COMPATIBILITY},
- * {@link CookiePolicy#NETSCAPE_DRAFT} or
- * {@link CookiePolicy#RFC2109}.
- *
- * @param policy new {@link CookiePolicy cookie policy}
- *
- * @deprecated
- * Use {@link org.apache.commons.httpclient.params.HttpMethodParams#setCookiePolicy(String)},
- * {@link HttpMethod#getParams()}.
- */
- public void setCookiePolicy(int policy) {
- this.cookiePolicy = policy;
- }
- /**
- * Sets the {@link Credentials credentials} for the given authentication
- * realm on the given host. The
null
realm signifies default
- * credentials for the given host, which should be used when no
- * {@link Credentials credentials} have been explictly supplied for the
- * challenging realm. The
null
host signifies default
- * credentials, which should be used when no {@link Credentials credentials}
- * have been explictly supplied for the challenging host. Any previous
- * credentials for the given realm on the given host will be overwritten.
- *
- * @param realm the authentication realm
- * @param host the host the realm belongs to
- * @param credentials the authentication {@link Credentials credentials}
- * for the given realm.
- *
- * @see #getCredentials(String, String)
- * @see #setProxyCredentials(String, String, Credentials)
- *
- * @deprecated use #setCredentials(AuthScope, Credentials)
- */
- public synchronized void setCredentials(String realm, String host, Credentials credentials) {
- LOG.trace("enter HttpState.setCredentials(String, String, Credentials)");
- credMap.put(new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), credentials);
- }
- /**
- * Sets the {@link Credentials credentials} for the given authentication
- * scope. Any previous credentials for the given scope will be overwritten.
- *
- * @param authscope the {@link AuthScope authentication scope}
- * @param credentials the authentication {@link Credentials credentials}
- * for the given scope.
- *
- * @see #getCredentials(AuthScope)
- * @see #setProxyCredentials(AuthScope, Credentials)
- *
- * @since 3.0
- */
- public synchronized void setCredentials(final AuthScope authscope, final Credentials credentials) {
- if (authscope == null) {
- throw new IllegalArgumentException("Authentication scope may not be null");
- }
- LOG.trace("enter HttpState.setCredentials(AuthScope, Credentials)");
- credMap.put(authscope, credentials);
- }
- /**
- * Find matching {@link Credentials credentials} for the given authentication scope.
- *
- * @param map the credentials hash map
- * @param token the {@link AuthScope authentication scope}
- * @return the credentials
- *
- */
- private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) {
- // see if we get a direct hit
- Credentials creds = (Credentials)map.get(authscope);
- if (creds == null) {
- // Nope.
- // Do a full scan
- int bestMatchFactor = -1;
- AuthScope bestMatch = null;
- Iterator items = map.keySet().iterator();
- while (items.hasNext()) {
- AuthScope current = (AuthScope)items.next();
- int factor = authscope.match(current);
- if (factor > bestMatchFactor) {
- bestMatchFactor = factor;
- bestMatch = current;
- }
- }
- if (bestMatch != null) {
- creds = (Credentials)map.get(bestMatch);
- }
- }
- return creds;
- }
- /**
- * Get the {@link Credentials credentials} for the given authentication scope on the
- * given host.
- *
- * If the
realm
exists on
host
, return the coresponding credentials.
- * If the
host
exists with a
null
realm
, return the corresponding
- * credentials.
- * If the
realm
exists with a
null
host
, return the
- * corresponding credentials. If the
realm
does not exist, return
- * the default Credentials. If there are no default credentials, return
- *
null
.
- *
- * @param realm the authentication realm
- * @param host the host the realm is on
- * @return the credentials
- *
- * @see #setCredentials(String, String, Credentials)
- *
- * @deprecated use #getCredentials(AuthScope)
- */
- public synchronized Credentials getCredentials(String realm, String host) {
- LOG.trace("enter HttpState.getCredentials(String, String");
- return matchCredentials(this.credMap,
- new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME));
- }
- /**
- * Get the {@link Credentials credentials} for the given authentication scope.
- *
- * @param authscope the {@link AuthScope authentication scope}
- * @return the credentials
- *
- * @see #setCredentials(AuthScope, Credentials)
- *
- * @since 3.0
- */
- public synchronized Credentials getCredentials(final AuthScope authscope) {
- if (authscope == null) {
- throw new IllegalArgumentException("Authentication scope may not be null");
- }
- LOG.trace("enter HttpState.getCredentials(AuthScope)");
- return matchCredentials(this.credMap, authscope);
- }
- /**
- * Sets the {@link Credentials credentials} for the given proxy authentication
- * realm on the given proxy host. The
null
proxy realm signifies
- * default credentials for the given proxy host, which should be used when no
- * {@link Credentials credentials} have been explictly supplied for the
- * challenging proxy realm. The
null
proxy host signifies default
- * credentials, which should be used when no {@link Credentials credentials}
- * have been explictly supplied for the challenging proxy host. Any previous
- * credentials for the given proxy realm on the given proxy host will be
- * overwritten.
- *
- * @param realm the authentication realm
- * @param proxyHost the proxy host
- * @param credentials the authentication credentials for the given realm
- *
- * @see #getProxyCredentials(AuthScope)
- * @see #setCredentials(AuthScope, Credentials)
- *
- * @deprecated use #setProxyCredentials(AuthScope, Credentials)
- */
- public synchronized void setProxyCredentials(
- String realm,
- String proxyHost,
- Credentials credentials
- ) {
- LOG.trace("enter HttpState.setProxyCredentials(String, String, Credentials");
- proxyCred.put(new AuthScope(proxyHost, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), credentials);
- }
- /**
- * Sets the {@link Credentials proxy credentials} for the given authentication
- * realm. Any previous credentials for the given realm will be overwritten.
- *
- * @param authscope the {@link AuthScope authentication scope}
- * @param credentials the authentication {@link Credentials credentials}
- * for the given realm.
- *
- * @see #getProxyCredentials(AuthScope)
- * @see #setCredentials(AuthScope, Credentials)
- *
- * @since 3.0
- */
- public synchronized void setProxyCredentials(final AuthScope authscope,
- final Credentials credentials)
- {
- if (authscope == null) {
- throw new IllegalArgumentException("Authentication scope may not be null");
- }
- LOG.trace("enter HttpState.setProxyCredentials(AuthScope, Credentials)");
- proxyCred.put(authscope, credentials);
- }
- /**
- * Get the {@link Credentials credentials} for the proxy host with the given
- * authentication scope.
- *
- * If the
realm
exists on
host
, return the coresponding credentials.
- * If the
host
exists with a
null
realm
, return the corresponding
- * credentials.
- * If the
realm
exists with a
null
host
, return the
- * corresponding credentials. If the
realm
does not exist, return
- * the default Credentials. If there are no default credentials, return
- *
null
.
- *
- * @param realm the authentication realm
- * @param proxyHost the proxy host the realm is on
- * @return the credentials
- * @see #setProxyCredentials(String, String, Credentials)
- *
- * @deprecated use #getProxyCredentials(AuthScope)
- */
- public synchronized Credentials getProxyCredentials(String realm, String proxyHost) {
- LOG.trace("enter HttpState.getCredentials(String, String");
- return matchCredentials(this.proxyCred,
- new AuthScope(proxyHost, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME));
- }
- /**
- * Get the {@link Credentials proxy credentials} for the given authentication scope.
- *
- * @param authscope the {@link AuthScope authentication scope}
- * @return the credentials
- *
- * @see #setProxyCredentials(AuthScope, Credentials)
- *
- * @since 3.0
- */
- public synchronized Credentials getProxyCredentials(final AuthScope authscope) {
- if (authscope == null) {
- throw new IllegalArgumentException("Authentication scope may not be null");
- }
- LOG.trace("enter HttpState.getProxyCredentials(AuthScope)");
- return matchCredentials(this.proxyCred, authscope);
- }
- /**
- * Returns a string representation of this HTTP state.
- *
- * @return The string representation of the HTTP state.
- *
- * @see java.lang.Object#toString()
- */
- public synchronized String toString() {
- StringBuffer sbResult = new StringBuffer();
- sbResult.append("[");
- sbResult.append(getCredentialsStringRepresentation(proxyCred));
- sbResult.append(" | ");
- sbResult.append(getCredentialsStringRepresentation(credMap));
- sbResult.append(" | ");
- sbResult.append(getCookiesStringRepresentation(cookies));
- sbResult.append("]");
- String strResult = sbResult.toString();
- return strResult;
- }
- /**
- * Returns a string representation of the credentials.
- * @param credMap The credentials.
- * @return The string representation.
- */
- private static String getCredentialsStringRepresentation(final Map credMap) {
- StringBuffer sbResult = new StringBuffer();
- Iterator iter = credMap.keySet().iterator();
- while (iter.hasNext()) {
- Object key = iter.next();
- Credentials cred = (Credentials) credMap.get(key);
- if (sbResult.length() > 0) {
- sbResult.append(", ");
- }
- sbResult.append(key);
- sbResult.append("#");
- sbResult.append(cred.toString());
- }
- return sbResult.toString();
- }
- /**
- * Returns a string representation of the cookies.
- * @param cookies The cookies
- * @return The string representation.
- */
- private static String getCookiesStringRepresentation(final List cookies) {
- StringBuffer sbResult = new StringBuffer();
- Iterator iter = cookies.iterator();
- while (iter.hasNext()) {
- Cookie ck = (Cookie) iter.next();
- if (sbResult.length() > 0) {
- sbResult.append("#");
- }
- sbResult.append(ck.toExternalForm());
- }
- return sbResult.toString();
- }
- /**
- * Clears all credentials.
- */
- public void clearCredentials() {
- this.credMap.clear();
- }
- /**
- * Clears all proxy credentials.
- */
- public void clearProxyCredentials() {
- this.proxyCred.clear();
- }
- /**
- * Clears all cookies.
- */
- public synchronized void clearCookies() {
- this.cookies.clear();
- }
- /**
- * Clears the state information (all cookies, credentials and proxy credentials).
- */
- public void clear() {
- clearCookies();
- clearCredentials();
- clearProxyCredentials();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpStatus.java b/clients/java/src/org/apache/commons/httpclient/HttpStatus.java
deleted file mode 100644
index 0026816..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpStatus.java
+++ /dev/null
@@ -1,312 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpStatus.java,v 1.18 2004/05/02 11:21:13 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
escaped
is
null
- * @see #getProtocolCharset
- */
- public HttpURL(char[] escaped, String charset)
- throws URIException, NullPointerException {
- protocolCharset = charset;
- parseUriReference(new String(escaped), true);
- checkValid();
- }
- /**
- * Construct a HTTP URL as an escaped form of a character array.
- *
- * @param escaped the HTTP URL character sequence
- * @throws URIException If {@link #checkValid()} fails
- * @throws NullPointerException if
escaped
is
null
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(char[] escaped) throws URIException, NullPointerException {
- parseUriReference(new String(escaped), true);
- checkValid();
- }
- /**
- * Construct a HTTP URL from a given string with the given charset to do
- * escape encoding.
- *
- * @param original the HTTP URL string
- * @param charset the charset string to do escape encoding
- * @throws URIException If {@link #checkValid()} fails
- * @see #getProtocolCharset
- */
- public HttpURL(String original, String charset) throws URIException {
- protocolCharset = charset;
- parseUriReference(original, false);
- checkValid();
- }
- /**
- * Construct a HTTP URL from a given string.
- *
- * @param original the HTTP URL string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String original) throws URIException {
- parseUriReference(original, false);
- checkValid();
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String host, int port, String path) throws URIException {
- this(null, null, host, port, path, null, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String host, int port, String path, String query)
- throws URIException {
- this(null, null, host, port, path, query, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String user, String password, String host)
- throws URIException {
- this(user, password, host, -1, null, null, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String user, String password, String host, int port)
- throws URIException {
- this(user, password, host, port, null, null, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String user, String password, String host, int port,
- String path) throws URIException {
- this(user, password, host, port, path, null, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query The query string.
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String user, String password, String host, int port,
- String path, String query) throws URIException {
- this(user, password, host, port, path, query, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param host the host string
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String host, String path, String query, String fragment)
- throws URIException {
- this(null, null, host, -1, path, query, fragment);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String userinfo, String host, String path, String query,
- String fragment) throws URIException {
- this(userinfo, host, -1, path, query, fragment);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String userinfo, String host, int port, String path)
- throws URIException {
- this(userinfo, host, port, path, null, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String userinfo, String host, int port, String path,
- String query) throws URIException {
- this(userinfo, host, port, path, query, null);
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String userinfo, String host, int port, String path,
- String query, String fragment) throws URIException {
- // validate and contruct the URI character sequence
- StringBuffer buff = new StringBuffer();
- if (userinfo != null || host != null || port != -1) {
- _scheme = DEFAULT_SCHEME; // in order to verify the own protocol
- buff.append(_default_scheme);
- buff.append("://");
- if (userinfo != null) {
- buff.append(userinfo);
- buff.append('@');
- }
- if (host != null) {
- buff.append(URIUtil.encode(host, URI.allowed_host));
- if (port != -1 || port != DEFAULT_PORT) {
- buff.append(':');
- buff.append(port);
- }
- }
- }
- if (path != null) { // accept empty path
- if (scheme != null && !path.startsWith("/")) {
- throw new URIException(URIException.PARSING,
- "abs_path requested");
- }
- buff.append(URIUtil.encode(path, URI.allowed_abs_path));
- }
- if (query != null) {
- buff.append('?');
- buff.append(URIUtil.encode(query, URI.allowed_query));
- }
- if (fragment != null) {
- buff.append('#');
- buff.append(URIUtil.encode(fragment, URI.allowed_fragment));
- }
- parseUriReference(buff.toString(), true);
- checkValid();
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpURL(String user, String password, String host, int port,
- String path, String query, String fragment) throws URIException {
- this(toUserinfo(user, password), host, port, path, query, fragment);
- }
- protected static String toUserinfo(String user, String password) throws URIException {
- if (user == null) return null;
- StringBuffer usrinfo = new StringBuffer(20); //sufficient for real world
- usrinfo.append(URIUtil.encode(user, URI.allowed_within_userinfo));
- if (password == null) return usrinfo.toString();
- usrinfo.append(':');
- usrinfo.append(URIUtil.encode(password, URI.allowed_within_userinfo));
- return usrinfo.toString();
- }
- /**
- * Construct a HTTP URL with a given relative URL string.
- *
- * @param base the base HttpURL
- * @param relative the relative HTTP URL string
- * @throws URIException If {@link #checkValid()} fails
- */
- public HttpURL(HttpURL base, String relative) throws URIException {
- this(base, new HttpURL(relative));
- }
- /**
- * Construct a HTTP URL with a given relative URL.
- *
- * @param base the base HttpURL
- * @param relative the relative HttpURL
- * @throws URIException If {@link #checkValid()} fails
- */
- public HttpURL(HttpURL base, HttpURL relative) throws URIException {
- super(base, relative);
- checkValid();
- }
- // -------------------------------------------------------------- Constants
- /**
- * Default scheme for HTTP URL.
- */
- public static final char[] DEFAULT_SCHEME = { 'h', 't', 't', 'p' };
- /**
- * Default scheme for HTTP URL.
- * @deprecated Use {@link #DEFAULT_SCHEME} instead. This one doesn't
- * conform to the project naming conventions.
- */
- public static final char[] _default_scheme = DEFAULT_SCHEME;
- /**
- * Default port for HTTP URL.
- */
- public static final int DEFAULT_PORT = 80;
- /**
- * Default port for HTTP URL.
- * @deprecated Use {@link #DEFAULT_PORT} instead. This one doesn't conform
- * to the project naming conventions.
- */
- public static final int _default_port = DEFAULT_PORT;
- /**
- * The serialVersionUID.
- */
- static final long serialVersionUID = -7158031098595039459L;
- // ------------------------------------------------------------- The scheme
- /**
- * Get the scheme. You can get the scheme explicitly.
- *
- * @return the scheme
- */
- public char[] getRawScheme() {
- return (_scheme == null) ? null : HttpURL.DEFAULT_SCHEME;
- }
- /**
- * Get the scheme. You can get the scheme explicitly.
- *
- * @return the scheme null if empty or undefined
- */
- public String getScheme() {
- return (_scheme == null) ? null : new String(HttpURL.DEFAULT_SCHEME);
- }
- // --------------------------------------------------------------- The port
- /**
- * Get the port number.
- * @return the port number
- */
- public int getPort() {
- return (_port == -1) ? HttpURL.DEFAULT_PORT : _port;
- }
- // ----------------------------------------------------------- The userinfo
- /**
- * Set the raw-escaped user and password.
- *
- * @param escapedUser the raw-escaped user
- * @param escapedPassword the raw-escaped password; could be null
- * @throws URIException escaped user not valid or user required; escaped
- * password not valid or username missed
- */
- public void setRawUserinfo(char[] escapedUser, char[] escapedPassword)
- throws URIException {
- if (escapedUser == null || escapedUser.length == 0) {
- throw new URIException(URIException.PARSING, "user required");
- }
- if (!validate(escapedUser, within_userinfo)
- || ((escapedPassword != null)
- && !validate(escapedPassword, within_userinfo))) {
- throw new URIException(URIException.ESCAPING,
- "escaped userinfo not valid");
- }
- String username = new String(escapedUser);
- String password = (escapedPassword == null)
- ? null : new String(escapedPassword);
- String userinfo = username + ((password == null) ? "" : ":" + password);
- String hostname = new String(getRawHost());
- String hostport = (_port == -1) ? hostname : hostname + ":" + _port;
- String authority = userinfo + "@" + hostport;
- _userinfo = userinfo.toCharArray();
- _authority = authority.toCharArray();
- setURI();
- }
- /**
- * Set the raw-escaped user and password.
- *
- * @param escapedUser the escaped user
- * @param escapedPassword the escaped password; could be null
- * @throws URIException escaped user not valid or user required; escaped
- * password not valid or username missed
- * @throws NullPointerException null user
- */
- public void setEscapedUserinfo(String escapedUser, String escapedPassword)
- throws URIException, NullPointerException {
- setRawUserinfo(escapedUser.toCharArray(), (escapedPassword == null)
- ? null : escapedPassword.toCharArray());
- }
- /**
- * Set the user and password.
- *
- * @param user the user
- * @param password the password; could be null
- * @throws URIException encoding error or username missed
- * @throws NullPointerException null user
- */
- public void setUserinfo(String user, String password)
- throws URIException, NullPointerException {
- // set the charset to do escape encoding
- String charset = getProtocolCharset();
- setRawUserinfo(encode(user, within_userinfo, charset),
- (password == null)
- ? null
- : encode(password, within_userinfo, charset));
- }
- /**
- * Set the raw-escaped user.
- *
- * @param escapedUser the raw-escaped user
- * @throws URIException escaped user not valid or user required
- */
- public void setRawUser(char[] escapedUser) throws URIException {
- if (escapedUser == null || escapedUser.length == 0) {
- throw new URIException(URIException.PARSING, "user required");
- }
- if (!validate(escapedUser, within_userinfo)) {
- throw new URIException(URIException.ESCAPING,
- "escaped user not valid");
- }
- String username = new String(escapedUser);
- char[] rawPassword = getRawPassword();
- String password = rawPassword == null ? null : new String(rawPassword);
- String userinfo = username + ((password == null) ? "" : ":" + password);
- String hostname = new String(getRawHost());
- String hostport = (_port == -1) ? hostname : hostname + ":" + _port;
- String authority = userinfo + "@" + hostport;
- _userinfo = userinfo.toCharArray();
- _authority = authority.toCharArray();
- setURI();
- }
- /**
- * Set the escaped user string.
- *
- * @param escapedUser the escaped user string
- * @throws URIException escaped user not valid
- * @throws NullPointerException null user
- */
- public void setEscapedUser(String escapedUser)
- throws URIException, NullPointerException {
- setRawUser(escapedUser.toCharArray());
- }
- /**
- * Set the user string.
- *
- * @param user the user string
- * @throws URIException user encoding error
- * @throws NullPointerException null user
- */
- public void setUser(String user) throws URIException, NullPointerException {
- setRawUser(encode(user, allowed_within_userinfo, getProtocolCharset()));
- }
- /**
- * Get the raw-escaped user.
- *
- * @return the raw-escaped user
- */
- public char[] getRawUser() {
- if (_userinfo == null || _userinfo.length == 0) {
- return null;
- }
- int to = indexFirstOf(_userinfo, ':');
- // String.indexOf(':', 0, _userinfo.length, _userinfo, 0, 1, 0);
- if (to == -1) {
- return _userinfo; // only user.
- }
- char[] result = new char[to];
- System.arraycopy(_userinfo, 0, result, 0, to);
- return result;
- }
- /**
- * Get the escaped user
- *
- * @return the escaped user
- */
- public String getEscapedUser() {
- char[] user = getRawUser();
- return (user == null) ? null : new String(user);
- }
- /**
- * Get the user.
- *
- * @return the user name
- * @throws URIException If {@link #decode} fails
- */
- public String getUser() throws URIException {
- char[] user = getRawUser();
- return (user == null) ? null : decode(user, getProtocolCharset());
- }
- /**
- * Set the raw-escaped password.
- *
- * @param escapedPassword the raw-escaped password; could be null
- * @throws URIException escaped password not valid or username missed
- */
- public void setRawPassword(char[] escapedPassword) throws URIException {
- if (escapedPassword != null
- && !validate(escapedPassword, within_userinfo)) {
- throw new URIException(URIException.ESCAPING,
- "escaped password not valid");
- }
- if (getRawUser() == null || getRawUser().length == 0) {
- throw new URIException(URIException.PARSING, "username required");
- }
- String username = new String(getRawUser());
- String password = escapedPassword == null ? null : new String(escapedPassword);
- // an emtpy string is allowed as a password
- String userinfo = username + ((password == null) ? "" : ":" + password);
- String hostname = new String(getRawHost());
- String hostport = (_port == -1) ? hostname : hostname + ":" + _port;
- String authority = userinfo + "@" + hostport;
- _userinfo = userinfo.toCharArray();
- _authority = authority.toCharArray();
- setURI();
- }
- /**
- * Set the escaped password string.
- *
- * @param escapedPassword the escaped password string; could be null
- * @throws URIException escaped password not valid or username missed
- */
- public void setEscapedPassword(String escapedPassword) throws URIException {
- setRawPassword((escapedPassword == null) ? null
- : escapedPassword.toCharArray());
- }
- /**
- * Set the password string.
- *
- * @param password the password string; could be null
- * @throws URIException encoding error or username missed
- */
- public void setPassword(String password) throws URIException {
- setRawPassword((password == null) ? null : encode(password,
- allowed_within_userinfo, getProtocolCharset()));
- }
- /**
- * Get the raw-escaped password.
- *
- * @return the raw-escaped password
- */
- public char[] getRawPassword() {
- int from = indexFirstOf(_userinfo, ':');
- if (from == -1) {
- return null; // null or only user.
- }
- int len = _userinfo.length - from - 1;
- char[] result = new char[len];
- System.arraycopy(_userinfo, from + 1, result, 0, len);
- return result;
- }
- /**
- * Get the escaped password.
- *
- * @return the escaped password
- */
- public String getEscapedPassword() {
- char[] password = getRawPassword();
- return (password == null) ? null : new String(password);
- }
- /**
- * Get the password.
- *
- * @return the password
- * @throws URIException If {@link #decode(char[],String)} fails.
- */
- public String getPassword() throws URIException {
- char[] password = getRawPassword();
- return (password == null) ? null : decode(password,
- getProtocolCharset());
- }
- // --------------------------------------------------------------- The path
- /**
- * Get the raw-escaped current hierarchy level.
- *
- * @return the raw-escaped current hierarchy level
- * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
- */
- public char[] getRawCurrentHierPath() throws URIException {
- return (_path == null || _path.length == 0) ? rootPath
- : super.getRawCurrentHierPath(_path);
- }
- /**
- * Get the level above the this hierarchy level.
- *
- * @return the raw above hierarchy level
- * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails.
- */
- public char[] getRawAboveHierPath() throws URIException {
- char[] path = getRawCurrentHierPath();
- return (path == null || path.length == 0) ? rootPath : getRawCurrentHierPath(path);
- }
- /**
- * Get the raw escaped path.
- *
- * @return the path '/' if empty or undefined
- */
- public char[] getRawPath() {
- char[] path = super.getRawPath();
- return (path == null || path.length == 0) ? rootPath : path;
- }
- // -------------------------------------------------------------- The query
- /**
- * Set the query as the name and value pair.
- *
- * @param queryName the query string.
- * @param queryValue the query string.
- * @throws URIException incomplete trailing escape pattern
- * Or unsupported character encoding
- * @throws NullPointerException null query
- * @see #encode
- */
- public void setQuery(String queryName, String queryValue)
- throws URIException, NullPointerException {
- StringBuffer buff = new StringBuffer();
- // set the charset to do escape encoding
- String charset = getProtocolCharset();
- buff.append(encode(queryName, allowed_within_query, charset));
- buff.append('=');
- buff.append(encode(queryValue, allowed_within_query, charset));
- _query = buff.toString().toCharArray();
- setURI();
- }
- /**
- * Set the query as the name and value pairs.
- *
- * @param queryName the array of the query string.
- * @param queryValue the array of the query string.
- * @throws URIException incomplete trailing escape pattern,
- * unsupported character encoding or wrong array size
- * @throws NullPointerException null query
- * @see #encode
- */
- public void setQuery(String[] queryName, String[] queryValue)
- throws URIException, NullPointerException {
- int length = queryName.length;
- if (length != queryValue.length) {
- throw new URIException("wrong array size of query");
- }
- StringBuffer buff = new StringBuffer();
- // set the charset to do escape encoding
- String charset = getProtocolCharset();
- for (int i = 0; i < length; i++) {
- buff.append(encode(queryName[i], allowed_within_query, charset));
- buff.append('=');
- buff.append(encode(queryValue[i], allowed_within_query, charset));
- if (i + 1 < length) {
- buff.append('&');
- }
- }
- _query = buff.toString().toCharArray();
- setURI();
- }
- // ---------------------------------------------------------------- Utility
- /**
- * Verify the valid class use for construction.
- *
- * @throws URIException the wrong scheme use
- */
- protected void checkValid() throws URIException {
- // could be explicit protocol or undefined.
- if (!(equals(_scheme, DEFAULT_SCHEME) || _scheme == null)) {
- throw new URIException(URIException.PARSING, "wrong class use");
- }
- }
- /**
- * Once it's parsed successfully, set this URI.
- *
- * @see #getRawURI
- */
- protected void setURI() {
- // set _uri
- StringBuffer buf = new StringBuffer();
- // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
- if (_scheme != null) {
- buf.append(_scheme);
- buf.append(':');
- }
- if (_is_net_path) {
- buf.append("//");
- if (_authority != null) { // has_authority
- if (_userinfo != null) { // by default, remove userinfo part
- if (_host != null) {
- buf.append(_host);
- if (_port != -1) {
- buf.append(':');
- buf.append(_port);
- }
- }
- } else {
- buf.append(_authority);
- }
- }
- }
- if (_opaque != null && _is_opaque_part) {
- buf.append(_opaque);
- } else if (_path != null) {
- // _is_hier_part or _is_relativeURI
- if (_path.length != 0) {
- buf.append(_path);
- }
- }
- if (_query != null) { // has_query
- buf.append('?');
- buf.append(_query);
- }
- // ignore the fragment identifier
- _uri = buf.toString().toCharArray();
- hash = 0;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/HttpVersion.java b/clients/java/src/org/apache/commons/httpclient/HttpVersion.java
deleted file mode 100644
index 4dd95e0..0000000
--- a/clients/java/src/org/apache/commons/httpclient/HttpVersion.java
+++ /dev/null
@@ -1,249 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpVersion.java,v 1.6 2004/12/20 19:52:50 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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 version, as specified in RFC 2616.
- * HTTP uses a "<major>.<minor>" numbering scheme to indicate - * versions of the protocol. The protocol versioning policy is intended to - * allow the sender to indicate the format of a message and its capacity for - * understanding further HTTP communication, rather than the features - * obtained via that communication. No change is made to the version - * number for the addition of message components which do not affect - * communication behavior or which only add to extensible field values. - * The <minor> number is incremented when the changes made to the - * protocol add features which do not change the general message parsing - * algorithm, but which may add to the message semantics and imply - * additional capabilities of the sender. The <major> number is - * incremented when the format of a message within the protocol is - * changed. See RFC 2145 [36] for a fuller explanation. - * The version of an HTTP message is indicated by an HTTP-Version field - * in the first line of the message. - * HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT - * Note that the major and minor numbers MUST be treated as separate - * integers and that each MAY be incremented higher than a single digit. - * Thus, HTTP/2.4 is a lower version than HTTP/2.13, which in turn is - * lower than HTTP/12.3. Leading zeros MUST be ignored by recipients and - * MUST NOT be sent. - * @author Oleg Kalnichevski - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * @since 3.0 -public class HttpVersion implements Comparable { - /** Major version number of the HTTP protocol */ - private int major = 0; - /** Minor version number of the HTTP protocol */ - private int minor = 0; - /** HTTP protocol version 0.9 */ - public static final HttpVersion HTTP_0_9 = new HttpVersion(0, 9); - /** HTTP protocol version 1.0 */ - public static final HttpVersion HTTP_1_0 = new HttpVersion(1, 0); - /** HTTP protocol version 1.1 */ - public static final HttpVersion HTTP_1_1 = new HttpVersion(1, 1); - /** - * Create an HTTP protocol version designator. - * - * @param major the major version number of the HTTP protocol - * @param minor the minor version number of the HTTP protocol - * - * @throws IllegalArgumentException if either major or minor version number is negative - */ - public HttpVersion(int major, int minor) { - if (major < 0) { - throw new IllegalArgumentException("HTTP major version number may not be negative"); - } - this.major = major; - if (minor < 0) { - throw new IllegalArgumentException("HTTP minor version number may not be negative"); - } - this.minor = minor; - } - /** - * Returns the major version number of the HTTP protocol. - * - * @return the major version number. - */ - public int getMajor() { - return major; - } - /** - * Returns the minor version number of the HTTP protocol. - * - * @return the minor version number. - */ - public int getMinor() { - return minor; - } - /** - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return this.major * 100000 + this.minor; - } - /** - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof HttpVersion)) { - return false; - } - return equals((HttpVersion)obj); - } - /** - * Compares this HTTP protocol version with another one. - * - * @param anotherVer the version to be compared with. - * - * @return a negative integer, zero, or a positive integer as this version is less than, - * equal to, or greater than the specified version. - */ - public int compareTo(HttpVersion anotherVer) { - if (anotherVer == null) { - throw new IllegalArgumentException("Version parameter may not be null"); - } - int delta = getMajor() - anotherVer.getMajor(); - if (delta == 0) { - delta = getMinor() - anotherVer.getMinor(); - } - return delta; - } - /** - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - public int compareTo(Object o) { - return compareTo((HttpVersion)o); - } - /** - * Test if the HTTP protocol version is equal to the given number. - * - * @return true if HTTP protocol version is given to the given number, - * false otherwise. - */ - public boolean equals(HttpVersion version) { - return compareTo(version) == 0; - } - /** - * Test if the HTTP protocol version is greater or equal to the given number. - * - * @return true if HTTP protocol version is greater or equal given to the - * given number, false otherwise. - */ - public boolean greaterEquals(HttpVersion version) { - return compareTo(version) >= 0; - } - /** - * Test if the HTTP protocol version is less or equal to the given number. - * - * @return true if HTTP protocol version is less or equal to given to the - * given number, false otherwise. - */ - public boolean lessEquals(HttpVersion version) { - return compareTo(version) <= 0; - } - /** - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append("HTTP/"); - buffer.append(this.major); - buffer.append('.'); - buffer.append(this.minor); - return buffer.toString(); - } - /** - * Parses the textual representation of the given HTTP protocol version. - * - * @return HTTP protocol version. - * - * @throws ProtocolException if the string is not a valid HTTP protocol version. - */ - public static HttpVersion parse(final String s) throws ProtocolException { - if (s == null) { - throw new IllegalArgumentException("String may not be null"); - } - if (!s.startsWith("HTTP/")) { - throw new ProtocolException("Invalid HTTP version string: " + s); - } - int major, minor; - int i1 = "HTTP/".length(); - int i2 = s.indexOf(".", i1); - if (i2 == -1) { - throw new ProtocolException("Invalid HTTP version number: " + s); - } - try { - major = Integer.parseInt(s.substring(i1, i2)); - } catch (NumberFormatException e) { - throw new ProtocolException("Invalid HTTP major version number: " + s); - } - i1 = i2 + 1; - i2 = s.length(); - try { - minor = Integer.parseInt(s.substring(i1, i2)); - } catch (NumberFormatException e) { - throw new ProtocolException("Invalid HTTP minor version number: " + s); - } - return new HttpVersion(major, minor); - } diff --git a/clients/java/src/org/apache/commons/httpclient/HttpsURL.java b/clients/java/src/org/apache/commons/httpclient/HttpsURL.java deleted file mode 100644 index 0dbb1ba..0000000 --- a/clients/java/src/org/apache/commons/httpclient/HttpsURL.java +++ /dev/null @@ -1,473 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpsURL.java,v 1.11 2004/09/30 17:26:41 oglueck Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
escaped
is
null
- * @see #getProtocolCharset
- */
- public HttpsURL(char[] escaped, String charset)
- throws URIException, NullPointerException {
- protocolCharset = charset;
- parseUriReference(new String(escaped), true);
- checkValid();
- }
- /**
- * Construct a HTTPS URL as an escaped form of a character array.
- *
- * @param escaped the HTTPS URL character sequence
- * @throws URIException If {@link #checkValid()} fails
- * @throws NullPointerException if
escaped
is
null
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(char[] escaped) throws URIException, NullPointerException {
- parseUriReference(new String(escaped), true);
- checkValid();
- }
- /**
- * Construct a HTTPS URL from a given string with the given charset to do
- * escape encoding.
- *
- * @param original the HTTPS URL string
- * @param charset the charset to do escape encoding
- * @throws URIException If {@link #checkValid()} fails
- * @see #getProtocolCharset
- */
- public HttpsURL(String original, String charset) throws URIException {
- protocolCharset = charset;
- parseUriReference(original, false);
- checkValid();
- }
- /**
- * Construct a HTTPS URL from a given string.
- *
- * @param original the HTTPS URL string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String original) throws URIException {
- parseUriReference(original, false);
- checkValid();
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String host, int port, String path) throws URIException {
- this(null, host, port, path, null, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String host, int port, String path, String query)
- throws URIException {
- this(null, host, port, path, query, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String user, String password, String host)
- throws URIException {
- this(user, password, host, -1, null, null, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String user, String password, String host, int port)
- throws URIException {
- this(user, password, host, port, null, null, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String user, String password, String host, int port,
- String path) throws URIException {
- this(user, password, host, port, path, null, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query The query string.
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String user, String password, String host, int port,
- String path, String query) throws URIException {
- this(user, password, host, port, path, query, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * @param host the host string
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String host, String path, String query, String fragment)
- throws URIException {
- this(null, host, -1, path, query, fragment);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String userinfo, String host, String path, String query,
- String fragment) throws URIException {
- this(userinfo, host, -1, path, query, fragment);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String userinfo, String host, int port, String path)
- throws URIException {
- this(userinfo, host, port, path, null, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String userinfo, String host, int port, String path,
- String query) throws URIException {
- this(userinfo, host, port, path, query, null);
- }
- /**
- * Construct a HTTPS URL from given components.
- *
- * Note: The
userinfo
format is normally
- *
<username>:<password>
where
- * username and password must both be URL escaped.
- *
- * @param userinfo the userinfo string whose parts are URL escaped
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String userinfo, String host, int port, String path,
- String query, String fragment) throws URIException {
- // validate and contruct the URI character sequence
- StringBuffer buff = new StringBuffer();
- if (userinfo != null || host != null || port != -1) {
- _scheme = DEFAULT_SCHEME; // in order to verify the own protocol
- buff.append(_default_scheme);
- buff.append("://");
- if (userinfo != null) {
- buff.append(userinfo);
- buff.append('@');
- }
- if (host != null) {
- buff.append(URIUtil.encode(host, URI.allowed_host));
- if (port != -1 || port != DEFAULT_PORT) {
- buff.append(':');
- buff.append(port);
- }
- }
- }
- if (path != null) { // accept empty path
- if (scheme != null && !path.startsWith("/")) {
- throw new URIException(URIException.PARSING,
- "abs_path requested");
- }
- buff.append(URIUtil.encode(path, URI.allowed_abs_path));
- }
- if (query != null) {
- buff.append('?');
- buff.append(URIUtil.encode(query, URI.allowed_query));
- }
- if (fragment != null) {
- buff.append('#');
- buff.append(URIUtil.encode(fragment, URI.allowed_fragment));
- }
- parseUriReference(buff.toString(), true);
- checkValid();
- }
- /**
- * Construct a HTTP URL from given components.
- *
- * @param user the user name
- * @param password his or her password
- * @param host the host string
- * @param port the port number
- * @param path the path string
- * @param query the query string
- * @param fragment the fragment string
- * @throws URIException If {@link #checkValid()} fails
- * @see #getDefaultProtocolCharset
- */
- public HttpsURL(String user, String password, String host, int port,
- String path, String query, String fragment) throws URIException {
- this(HttpURL.toUserinfo(user, password), host, port, path, query, fragment);
- }
- /**
- * Construct a HTTPS URL with a given relative HTTPS URL string.
- *
- * @param base the base HttpsURL
- * @param relative the relative HTTPS URL string
- * @throws URIException If {@link #checkValid()} fails
- */
- public HttpsURL(HttpsURL base, String relative) throws URIException {
- this(base, new HttpsURL(relative));
- }
- /**
- * Construct a HTTPS URL with a given relative URL.
- *
- * @param base the base HttpsURL
- * @param relative the relative HttpsURL
- * @throws URIException If {@link #checkValid()} fails
- */
- public HttpsURL(HttpsURL base, HttpsURL relative) throws URIException {
- super(base, relative);
- checkValid();
- }
- // -------------------------------------------------------------- Constants
- /**
- * Default scheme for HTTPS URL.
- */
- public static final char[] DEFAULT_SCHEME = { 'h', 't', 't', 'p', 's' };
- /**
- * Default scheme for HTTPS URL.
- * @deprecated Use {@link #DEFAULT_SCHEME} instead. This one doesn't
- * conform to the project naming conventions.
- */
- public static final char[] _default_scheme = DEFAULT_SCHEME;
- /**
- * Default port for HTTPS URL.
- */
- public static final int DEFAULT_PORT = 443;
- /**
- * Default port for HTTPS URL.
- * @deprecated Use {@link #DEFAULT_PORT} instead. This one doesn't conform
- * to the project naming conventions.
- */
- public static final int _default_port = DEFAULT_PORT;
- /**
- * The serialVersionUID.
- */
- static final long serialVersionUID = 887844277028676648L;
- // ------------------------------------------------------------- The scheme
- /**
- * Get the scheme. You can get the scheme explicitly.
- *
- * @return the scheme
- */
- public char[] getRawScheme() {
- return (_scheme == null) ? null : HttpsURL.DEFAULT_SCHEME;
- }
- /**
- * Get the scheme. You can get the scheme explicitly.
- *
- * @return the scheme null if empty or undefined
- */
- public String getScheme() {
- return (_scheme == null) ? null : new String(HttpsURL.DEFAULT_SCHEME);
- }
- // --------------------------------------------------------------- The port
- /**
- * Get the port number.
- * @return the port number
- */
- public int getPort() {
- return (_port == -1) ? HttpsURL.DEFAULT_PORT : _port;
- }
- // ---------------------------------------------------------------- Utility
- /**
- * Verify the valid class use for construction.
- *
- * @throws URIException the wrong scheme use
- */
- protected void checkValid() throws URIException {
- // could be explicit protocol or undefined.
- if (!(equals(_scheme, DEFAULT_SCHEME) || _scheme == null)) {
- throw new URIException(URIException.PARSING, "wrong class use");
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/InvalidRedirectLocationException.java b/clients/java/src/org/apache/commons/httpclient/InvalidRedirectLocationException.java
deleted file mode 100644
index f5270bd..0000000
--- a/clients/java/src/org/apache/commons/httpclient/InvalidRedirectLocationException.java
+++ /dev/null
@@ -1,74 +0,0 @@
- * $HeadRL$
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
true
if the method should be retried,
false
- * otherwise
- */
- boolean retryMethod(
- HttpMethod method,
- HttpConnection connection,
- HttpRecoverableException recoverableException,
- int executionCount,
- boolean requestSent);
diff --git a/clients/java/src/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java b/clients/java/src/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java
deleted file mode 100644
index 871b9a4..0000000
--- a/clients/java/src/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java
+++ /dev/null
@@ -1,1676 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/MultiThreadedHttpConnectionManager.java,v 1.47 2004/12/21 11:27:55 olegk Exp $
- * $Revision: 564906 $
- * $Date: 2007-08-11 14:27:18 +0200 (Sat, 11 Aug 2007) $
- * ====================================================================
- * 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
- *
The connection manager can no longer be used once shut down. - * - *
Calling this method more than once will have no effect.
- */
- public synchronized void shutdown() {
- synchronized (connectionPool) {
- if (!shutdown) {
- shutdown = true;
- connectionPool.shutdown();
- }
- }
- }
- /**
- * Gets the staleCheckingEnabled value to be set on HttpConnections that are created.
- *
- * @return
true
if stale checking will be enabled on HttpConnections
- *
- * @see HttpConnection#isStaleCheckingEnabled()
- *
- * @deprecated Use {@link HttpConnectionManagerParams#isStaleCheckingEnabled()},
- * {@link HttpConnectionManager#getParams()}.
- */
- public boolean isConnectionStaleCheckingEnabled() {
- return this.params.isStaleCheckingEnabled();
- }
- /**
- * Sets the staleCheckingEnabled value to be set on HttpConnections that are created.
- *
- * @param connectionStaleCheckingEnabled
true
if stale checking will be enabled
- * on HttpConnections
- *
- * @see HttpConnection#setStaleCheckingEnabled(boolean)
- *
- * @deprecated Use {@link HttpConnectionManagerParams#setStaleCheckingEnabled(boolean)},
- * {@link HttpConnectionManager#getParams()}.
- */
- public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) {
- this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled);
- }
- /**
- * Sets the maximum number of connections allowed for a given
- * HostConfiguration. Per RFC 2616 section 8.1.4, this value defaults to 2.
- *
- * @param maxHostConnections the number of connections allowed for each
- * hostConfiguration
- *
- * @deprecated Use {@link HttpConnectionManagerParams#setDefaultMaxConnectionsPerHost(int)},
- * {@link HttpConnectionManager#getParams()}.
- */
- public void setMaxConnectionsPerHost(int maxHostConnections) {
- this.params.setDefaultMaxConnectionsPerHost(maxHostConnections);
- }
- /**
- * Gets the maximum number of connections allowed for a given
- * hostConfiguration.
- *
- * @return The maximum number of connections allowed for a given
- * hostConfiguration.
- *
- * @deprecated Use {@link HttpConnectionManagerParams#getDefaultMaxConnectionsPerHost()},
- * {@link HttpConnectionManager#getParams()}.
- */
- public int getMaxConnectionsPerHost() {
- return this.params.getDefaultMaxConnectionsPerHost();
- }
- /**
- * Sets the maximum number of connections allowed for this connection manager.
- *
- * @param maxTotalConnections the maximum number of connections allowed
- *
- * @deprecated Use {@link HttpConnectionManagerParams#setMaxTotalConnections(int)},
- * {@link HttpConnectionManager#getParams()}.
- */
- public void setMaxTotalConnections(int maxTotalConnections) {
- this.params.setMaxTotalConnections(maxTotalConnections);
- }
- /**
- * Gets the maximum number of connections allowed for this connection manager.
- *
- * @return The maximum number of connections allowed
- *
- * @deprecated Use {@link HttpConnectionManagerParams#getMaxTotalConnections()},
- * {@link HttpConnectionManager#getParams()}.
- */
- public int getMaxTotalConnections() {
- return this.params.getMaxTotalConnections();
- }
- /**
- * @see HttpConnectionManager#getConnection(HostConfiguration)
- */
- public HttpConnection getConnection(HostConfiguration hostConfiguration) {
- while (true) {
- try {
- return getConnectionWithTimeout(hostConfiguration, 0);
- } catch (ConnectionPoolTimeoutException e) {
- // we'll go ahead and log this, but it should never happen. HttpExceptions
- // are only thrown when the timeout occurs and since we have no timeout
- // it should never happen.
- LOG.debug(
- "Unexpected exception while waiting for connection",
- e
- );
- }
- }
- }
- /**
- * Gets a connection or waits if one is not available. A connection is
- * available if one exists that is not being used or if fewer than
- * maxHostConnections have been created in the connectionPool, and fewer
- * than maxTotalConnections have been created in all connectionPools.
- *
- * @param hostConfiguration The host configuration specifying the connection
- * details.
- * @param timeout the number of milliseconds to wait for a connection, 0 to
- * wait indefinitely
- *
- * @return HttpConnection an available connection
- *
- * @throws HttpException if a connection does not become available in
- * 'timeout' milliseconds
- *
- * @since 3.0
- */
- public HttpConnection getConnectionWithTimeout(HostConfiguration hostConfiguration,
- long timeout) throws ConnectionPoolTimeoutException {
- LOG.trace("enter HttpConnectionManager.getConnectionWithTimeout(HostConfiguration, long)");
- if (hostConfiguration == null) {
- throw new IllegalArgumentException("hostConfiguration is null");
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("HttpConnectionManager.getConnection: config = "
- + hostConfiguration + ", timeout = " + timeout);
- }
- final HttpConnection conn = doGetConnection(hostConfiguration, timeout);
- // wrap the connection in an adapter so we can ensure it is used
- // only once
- return new HttpConnectionAdapter(conn);
- }
- /**
- * @see HttpConnectionManager#getConnection(HostConfiguration, long)
- *
- * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long)
- */
- public HttpConnection getConnection(HostConfiguration hostConfiguration,
- long timeout) throws HttpException {
- LOG.trace("enter HttpConnectionManager.getConnection(HostConfiguration, long)");
- try {
- return getConnectionWithTimeout(hostConfiguration, timeout);
- } catch(ConnectionPoolTimeoutException e) {
- throw new HttpException(e.getMessage());
- }
- }
- private HttpConnection doGetConnection(HostConfiguration hostConfiguration,
- long timeout) throws ConnectionPoolTimeoutException {
- HttpConnection connection = null;
- int maxHostConnections = this.params.getMaxConnectionsPerHost(hostConfiguration);
- int maxTotalConnections = this.params.getMaxTotalConnections();
- synchronized (connectionPool) {
- // we clone the hostConfiguration
- // so that it cannot be changed once the connection has been retrieved
- hostConfiguration = new HostConfiguration(hostConfiguration);
- HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, true);
- WaitingThread waitingThread = null;
- boolean useTimeout = (timeout > 0);
- long timeToWait = timeout;
- long startWait = 0;
- long endWait = 0;
- while (connection == null) {
- if (shutdown) {
- throw new IllegalStateException("Connection factory has been shutdown.");
- }
- // happen to have a free connection with the right specs
- //
- if (hostPool.freeConnections.size() > 0) {
- connection = connectionPool.getFreeConnection(hostConfiguration);
- // have room to make more
- //
- } else if ((hostPool.numConnections < maxHostConnections)
- && (connectionPool.numConnections < maxTotalConnections)) {
- connection = connectionPool.createConnection(hostConfiguration);
- // have room to add host connection, and there is at least one free
- // connection that can be liberated to make overall room
- //
- } else if ((hostPool.numConnections < maxHostConnections)
- && (connectionPool.freeConnections.size() > 0)) {
- connectionPool.deleteLeastUsedConnection();
- connection = connectionPool.createConnection(hostConfiguration);
- // otherwise, we have to wait for one of the above conditions to
- // become true
- //
- } else {
- // TODO: keep track of which hostConfigurations have waiting
- // threads, so they avoid being sacrificed before necessary
- try {
- if (useTimeout && timeToWait <= 0) {
- throw new ConnectionPoolTimeoutException("Timeout waiting for connection");
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("Unable to get a connection, waiting..., hostConfig=" + hostConfiguration);
- }
- if (waitingThread == null) {
- waitingThread = new WaitingThread();
- waitingThread.hostConnectionPool = hostPool;
- waitingThread.thread = Thread.currentThread();
- } else {
- waitingThread.interruptedByConnectionPool = false;
- }
- if (useTimeout) {
- startWait = System.currentTimeMillis();
- }
- hostPool.waitingThreads.addLast(waitingThread);
- connectionPool.waitingThreads.addLast(waitingThread);
- connectionPool.wait(timeToWait);
- } catch (InterruptedException e) {
- if (!waitingThread.interruptedByConnectionPool) {
- LOG.debug("Interrupted while waiting for connection", e);
- throw new IllegalThreadStateException(
- "Interrupted while waiting in MultiThreadedHttpConnectionManager");
- }
- // Else, do nothing, we were interrupted by the connection pool
- // and should now have a connection waiting for us, continue
- // in the loop and let's get it.
- } finally {
- if (!waitingThread.interruptedByConnectionPool) {
- // Either we timed out, experienced a "spurious wakeup", or were
- // interrupted by an external thread. Regardless we need to
- // cleanup for ourselves in the wait queue.
- hostPool.waitingThreads.remove(waitingThread);
- connectionPool.waitingThreads.remove(waitingThread);
- }
- if (useTimeout) {
- endWait = System.currentTimeMillis();
- timeToWait -= (endWait - startWait);
- }
- }
- }
- }
- }
- return connection;
- }
- /**
- * Gets the total number of pooled connections for the given host configuration. This
- * is the total number of connections that have been created and are still in use
- * by this connection manager for the host configuration. This value will
- * not exceed the {@link #getMaxConnectionsPerHost() maximum number of connections per
- * host}.
- *
- * @param hostConfiguration The host configuration
- * @return The total number of pooled connections
- */
- public int getConnectionsInPool(HostConfiguration hostConfiguration) {
- synchronized (connectionPool) {
- HostConnectionPool hostPool = connectionPool.getHostPool(hostConfiguration, false);
- return (hostPool != null) ? hostPool.numConnections : 0;
- }
- }
- /**
- * Gets the total number of pooled connections. This is the total number of
- * connections that have been created and are still in use by this connection
- * manager. This value will not exceed the {@link #getMaxTotalConnections()
- * maximum number of connections}.
- *
- * @return the total number of pooled connections
- */
- public int getConnectionsInPool() {
- synchronized (connectionPool) {
- return connectionPool.numConnections;
- }
- }
- /**
- * Gets the number of connections in use for this configuration.
- *
- * @param hostConfiguration the key that connections are tracked on
- * @return the number of connections in use
- *
- * @deprecated Use {@link #getConnectionsInPool(HostConfiguration)}
- */
- public int getConnectionsInUse(HostConfiguration hostConfiguration) {
- return getConnectionsInPool(hostConfiguration);
- }
- /**
- * Gets the total number of connections in use.
- *
- * @return the total number of connections in use
- *
- * @deprecated Use {@link #getConnectionsInPool()}
- */
- public int getConnectionsInUse() {
- return getConnectionsInPool();
- }
- /**
- * Deletes all closed connections. Only connections currently owned by the connection
- * manager are processed.
- *
- * @see HttpConnection#isOpen()
- *
- * @since 3.0
- */
- public void deleteClosedConnections() {
- connectionPool.deleteClosedConnections();
- }
- /**
- * @since 3.0
- */
- public void closeIdleConnections(long idleTimeout) {
- connectionPool.closeIdleConnections(idleTimeout);
- deleteClosedConnections();
- }
- /**
- * Make the given HttpConnection available for use by other requests.
- * If another thread is blocked in getConnection() that could use this
- * connection, it will be woken up.
- *
- * @param conn the HttpConnection to make available.
- */
- public void releaseConnection(HttpConnection conn) {
- LOG.trace("enter HttpConnectionManager.releaseConnection(HttpConnection)");
- if (conn instanceof HttpConnectionAdapter) {
- // connections given out are wrapped in an HttpConnectionAdapter
- conn = ((HttpConnectionAdapter) conn).getWrappedConnection();
- } else {
- // this is okay, when an HttpConnectionAdapter is released
- // is releases the real connection
- }
- // make sure that the response has been read.
- SimpleHttpConnectionManager.finishLastResponse(conn);
- connectionPool.freeConnection(conn);
- }
- /**
- * Gets the host configuration for a connection.
- * @param conn the connection to get the configuration of
- * @return a new HostConfiguration
- */
- private HostConfiguration configurationForConnection(HttpConnection conn) {
- HostConfiguration connectionConfiguration = new HostConfiguration();
- connectionConfiguration.setHost(
- conn.getHost(),
- conn.getPort(),
- conn.getProtocol()
- );
- if (conn.getLocalAddress() != null) {
- connectionConfiguration.setLocalAddress(conn.getLocalAddress());
- }
- if (conn.getProxyHost() != null) {
- connectionConfiguration.setProxy(conn.getProxyHost(), conn.getProxyPort());
- }
- return connectionConfiguration;
- }
- /**
- * Returns {@link HttpConnectionManagerParams parameters} associated
- * with this connection manager.
- *
- * @since 3.0
- *
- * @see HttpConnectionManagerParams
- */
- public HttpConnectionManagerParams getParams() {
- return this.params;
- }
- /**
- * Assigns {@link HttpConnectionManagerParams parameters} for this
- * connection manager.
- *
- * @since 3.0
- *
- * @see HttpConnectionManagerParams
- */
- public void setParams(final HttpConnectionManagerParams params) {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- this.params = params;
- }
- /**
- * Global Connection Pool, including per-host pools
- */
- private class ConnectionPool {
- /** The list of free connections */
- private LinkedList freeConnections = new LinkedList();
- /** The list of WaitingThreads waiting for a connection */
- private LinkedList waitingThreads = new LinkedList();
- /**
- * Map where keys are {@link HostConfiguration}s and values are {@link
- * HostConnectionPool}s
- */
- private final Map mapHosts = new HashMap();
- private IdleConnectionHandler idleConnectionHandler = new IdleConnectionHandler();
- /** The number of created connections */
- private int numConnections = 0;
- /**
- * Cleans up all connection pool resources.
- */
- public synchronized void shutdown() {
- // close all free connections
- Iterator iter = freeConnections.iterator();
- while (iter.hasNext()) {
- HttpConnection conn = (HttpConnection) iter.next();
- iter.remove();
- conn.close();
- }
- // close all connections that have been checked out
- shutdownCheckedOutConnections(this);
- // interrupt all waiting threads
- iter = waitingThreads.iterator();
- while (iter.hasNext()) {
- WaitingThread waiter = (WaitingThread) iter.next();
- iter.remove();
- waiter.interruptedByConnectionPool = true;
- waiter.thread.interrupt();
- }
- // clear out map hosts
- mapHosts.clear();
- // remove all references to connections
- idleConnectionHandler.removeAll();
- }
- /**
- * Creates a new connection and returns it for use of the calling method.
- *
- * @param hostConfiguration the configuration for the connection
- * @return a new connection or
null
if none are available
- */
- public synchronized HttpConnection createConnection(HostConfiguration hostConfiguration) {
- HostConnectionPool hostPool = getHostPool(hostConfiguration, true);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Allocating new connection, hostConfig=" + hostConfiguration);
- }
- HttpConnectionWithReference connection = new HttpConnectionWithReference(
- hostConfiguration);
- connection.getParams().setDefaults(MultiThreadedHttpConnectionManager.this.params);
- connection.setHttpConnectionManager(MultiThreadedHttpConnectionManager.this);
- numConnections++;
- hostPool.numConnections++;
- // store a reference to this connection so that it can be cleaned up
- // in the event it is not correctly released
- storeReferenceToConnection(connection, hostConfiguration, this);
- return connection;
- }
- /**
- * Handles cleaning up for a lost connection with the given config. Decrements any
- * connection counts and notifies waiting threads, if appropriate.
- *
- * @param config the host configuration of the connection that was lost
- */
- public synchronized void handleLostConnection(HostConfiguration config) {
- HostConnectionPool hostPool = getHostPool(config, true);
- hostPool.numConnections--;
- if ((hostPool.numConnections == 0) &&
- hostPool.waitingThreads.isEmpty()) {
- mapHosts.remove(config);
- }
- numConnections--;
- notifyWaitingThread(config);
- }
- /**
- * Get the pool (list) of connections available for the given hostConfig.
- *
- * @param hostConfiguration the configuraton for the connection pool
- * @param create
true
to create a pool if not found,
- *
false
to return
null
- *
- * @return a pool (list) of connections available for the given config,
- * or
null
if neither found nor created
- */
- public synchronized HostConnectionPool getHostPool(HostConfiguration hostConfiguration, boolean create) {
- LOG.trace("enter HttpConnectionManager.ConnectionPool.getHostPool(HostConfiguration)");
- // Look for a list of connections for the given config
- HostConnectionPool listConnections = (HostConnectionPool)
- mapHosts.get(hostConfiguration);
- if ((listConnections == null) && create) {
- // First time for this config
- listConnections = new HostConnectionPool();
- listConnections.hostConfiguration = hostConfiguration;
- mapHosts.put(hostConfiguration, listConnections);
- }
- return listConnections;
- }
- /**
- * If available, get a free connection for this host
- *
- * @param hostConfiguration the configuraton for the connection pool
- * @return an available connection for the given config
- */
- public synchronized HttpConnection getFreeConnection(HostConfiguration hostConfiguration) {
- HttpConnectionWithReference connection = null;
- HostConnectionPool hostPool = getHostPool(hostConfiguration, false);
- if ((hostPool != null) && (hostPool.freeConnections.size() > 0)) {
- connection = (HttpConnectionWithReference) hostPool.freeConnections.removeLast();
- freeConnections.remove(connection);
- // store a reference to this connection so that it can be cleaned up
- // in the event it is not correctly released
- storeReferenceToConnection(connection, hostConfiguration, this);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Getting free connection, hostConfig=" + hostConfiguration);
- }
- // remove the connection from the timeout handler
- idleConnectionHandler.remove(connection);
- } else if (LOG.isDebugEnabled()) {
- LOG.debug("There were no free connections to get, hostConfig="
- + hostConfiguration);
- }
- return connection;
- }
- /**
- * Deletes all closed connections.
- */
- public synchronized void deleteClosedConnections() {
- Iterator iter = freeConnections.iterator();
- while (iter.hasNext()) {
- HttpConnection conn = (HttpConnection) iter.next();
- if (!conn.isOpen()) {
- iter.remove();
- deleteConnection(conn);
- }
- }
- }
- /**
- * Closes idle connections.
- * @param idleTimeout
- */
- public synchronized void closeIdleConnections(long idleTimeout) {
- idleConnectionHandler.closeIdleConnections(idleTimeout);
- }
- /**
- * Deletes the given connection. This will remove all reference to the connection
- * so that it can be GCed.
- *
- *
Note: Does not remove the connection from the freeConnections list. It - * is assumed that the caller has already handled this case.
- * - * @param connection The connection to delete - */ - private synchronized void deleteConnection(HttpConnection connection) { - HostConfiguration connectionConfiguration = configurationForConnection(connection); - if (LOG.isDebugEnabled()) { - LOG.debug("Reclaiming connection, hostConfig=" + connectionConfiguration); - } - connection.close(); - HostConnectionPool hostPool = getHostPool(connectionConfiguration, true); - hostPool.freeConnections.remove(connection); - hostPool.numConnections--; - numConnections--; - if ((hostPool.numConnections == 0) && - hostPool.waitingThreads.isEmpty()) { - mapHosts.remove(connectionConfiguration); - } - // remove the connection from the timeout handler - idleConnectionHandler.remove(connection); - } - /** - * Close and delete an old, unused connection to make room for a new one. - */ - public synchronized void deleteLeastUsedConnection() { - HttpConnection connection = (HttpConnection) freeConnections.removeFirst(); - if (connection != null) { - deleteConnection(connection); - } else if (LOG.isDebugEnabled()) { - LOG.debug("Attempted to reclaim an unused connection but there were none."); - } - } - /** - * Notifies a waiting thread that a connection for the given configuration is - * available. - * @param configuration the host config to use for notifying - * @see #notifyWaitingThread(HostConnectionPool) - */ - public synchronized void notifyWaitingThread(HostConfiguration configuration) { - notifyWaitingThread(getHostPool(configuration, true)); - } - /** - * Notifies a waiting thread that a connection for the given configuration is - * available. This will wake a thread waiting in this host pool or if there is not - * one a thread in the connection pool will be notified. - * - * @param hostPool the host pool to use for notifying - */ - public synchronized void notifyWaitingThread(HostConnectionPool hostPool) { - // find the thread we are going to notify, we want to ensure that each - // waiting thread is only interrupted once so we will remove it from - // all wait queues before interrupting it - WaitingThread waitingThread = null; - if (hostPool.waitingThreads.size() > 0) { - if (LOG.isDebugEnabled()) { - LOG.debug("Notifying thread waiting on host pool, hostConfig=" - + hostPool.hostConfiguration); - } - waitingThread = (WaitingThread) hostPool.waitingThreads.removeFirst(); - waitingThreads.remove(waitingThread); - } else if (waitingThreads.size() > 0) { - if (LOG.isDebugEnabled()) { - LOG.debug("No-one waiting on host pool, notifying next waiting thread."); - } - waitingThread = (WaitingThread) waitingThreads.removeFirst(); - waitingThread.hostConnectionPool.waitingThreads.remove(waitingThread); - } else if (LOG.isDebugEnabled()) { - LOG.debug("Notifying no-one, there are no waiting threads"); - } - if (waitingThread != null) { - waitingThread.interruptedByConnectionPool = true; - waitingThread.thread.interrupt(); - } - } - /** - * Marks the given connection as free. - * @param conn a connection that is no longer being used - */ - public void freeConnection(HttpConnection conn) { - HostConfiguration connectionConfiguration = configurationForConnection(conn); - if (LOG.isDebugEnabled()) { - LOG.debug("Freeing connection, hostConfig=" + connectionConfiguration); - } - synchronized (this) { - if (shutdown) { - // the connection manager has been shutdown, release the connection's - // resources and get out of here - conn.close(); - return; - } - HostConnectionPool hostPool = getHostPool(connectionConfiguration, true); - // Put the connect back in the available list and notify a waiter - hostPool.freeConnections.add(conn); - if (hostPool.numConnections == 0) { - // for some reason this connection pool didn't already exist - LOG.error("Host connection pool not found, hostConfig=" - + connectionConfiguration); - hostPool.numConnections = 1; - } - freeConnections.add(conn); - // we can remove the reference to this connection as we have control over - // it again. this also ensures that the connection manager can be GCed - removeReferenceToConnection((HttpConnectionWithReference) conn); - if (numConnections == 0) { - // for some reason this connection pool didn't already exist - LOG.error("Host connection pool not found, hostConfig=" - + connectionConfiguration); - numConnections = 1; - } - // register the connection with the timeout handler - idleConnectionHandler.add(conn); - notifyWaitingThread(hostPool); - } - } - } - /** - * A simple struct-like class to combine the objects needed to release a connection's - * resources when claimed by the garbage collector. - */ - private static class ConnectionSource { - /** The connection pool that created the connection */ - public ConnectionPool connectionPool; - /** The connection's host configuration */ - public HostConfiguration hostConfiguration; - } - /** - * A simple struct-like class to combine the connection list and the count - * of created connections. - */ - private static class HostConnectionPool { - /** The hostConfig this pool is for */ - public HostConfiguration hostConfiguration; - /** The list of free connections */ - public LinkedList freeConnections = new LinkedList(); - /** The list of WaitingThreads for this host */ - public LinkedList waitingThreads = new LinkedList(); - /** The number of created connections */ - public int numConnections = 0; - } - /** - * A simple struct-like class to combine the waiting thread and the connection - * pool it is waiting on. - */ - private static class WaitingThread { - /** The thread that is waiting for a connection */ - public Thread thread; - /** The connection pool the thread is waiting for */ - public HostConnectionPool hostConnectionPool; - /** Flag to indicate if the thread was interrupted by the ConnectionPool. Set - * to true inside {@link ConnectionPool#notifyWaitingThread(HostConnectionPool)} - * before the thread is interrupted. */ - public boolean interruptedByConnectionPool = false; - } - /** - * A thread for listening for HttpConnections reclaimed by the garbage - * collector. - */ - private static class ReferenceQueueThread extends Thread { - private volatile boolean shutdown = false; - /** - * Create an instance and make this a daemon thread. - */ - public ReferenceQueueThread() { - setDaemon(true); - setName("MultiThreadedHttpConnectionManager cleanup"); - } - public void shutdown() { - this.shutdown = true; - this.interrupt(); - } - /** - * Handles cleaning up for the given connection reference. - * - * @param ref the reference to clean up - */ - private void handleReference(Reference ref) { - ConnectionSource source = null; - synchronized (REFERENCE_TO_CONNECTION_SOURCE) { - source = (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.remove(ref); - } - // only clean up for this reference if it is still associated with - // a ConnectionSource - if (source != null) { - if (LOG.isDebugEnabled()) { - LOG.debug( - "Connection reclaimed by garbage collector, hostConfig=" - + source.hostConfiguration); - } - source.connectionPool.handleLostConnection(source.hostConfiguration); - } - } - /** - * Start execution. - */ - public void run() { - while (!shutdown) { - try { - // remove the next reference and process it - Reference ref = REFERENCE_QUEUE.remove(); - if (ref != null) { - handleReference(ref); - } - } catch (InterruptedException e) { - LOG.debug("ReferenceQueueThread interrupted", e); - } - } - } - } - /** - * A connection that keeps a reference to itself. - */ - private static class HttpConnectionWithReference extends HttpConnection { - public WeakReference reference = new WeakReference(this, REFERENCE_QUEUE); - /** - * @param hostConfiguration - */ - public HttpConnectionWithReference(HostConfiguration hostConfiguration) { - super(hostConfiguration); - } - } - /** - * An HttpConnection wrapper that ensures a connection cannot be used - * once released. - */ - private static class HttpConnectionAdapter extends HttpConnection { - // the wrapped connection - private HttpConnection wrappedConnection; - /** - * Creates a new HttpConnectionAdapter. - * @param connection the connection to be wrapped - */ - public HttpConnectionAdapter(HttpConnection connection) { - super(connection.getHost(), connection.getPort(), connection.getProtocol()); - this.wrappedConnection = connection; - } - /** - * Tests if the wrapped connection is still available. - * @return boolean - */ - protected boolean hasConnection() { - return wrappedConnection != null; - } - /** - * @return HttpConnection - */ - HttpConnection getWrappedConnection() { - return wrappedConnection; - } - public void close() { - if (hasConnection()) { - wrappedConnection.close(); - } else { - // do nothing - } - } - public InetAddress getLocalAddress() { - if (hasConnection()) { - return wrappedConnection.getLocalAddress(); - } else { - return null; - } - } - /** - * @deprecated - */ - public boolean isStaleCheckingEnabled() { - if (hasConnection()) { - return wrappedConnection.isStaleCheckingEnabled(); - } else { - return false; - } - } - public void setLocalAddress(InetAddress localAddress) { - if (hasConnection()) { - wrappedConnection.setLocalAddress(localAddress); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public void setStaleCheckingEnabled(boolean staleCheckEnabled) { - if (hasConnection()) { - wrappedConnection.setStaleCheckingEnabled(staleCheckEnabled); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public String getHost() { - if (hasConnection()) { - return wrappedConnection.getHost(); - } else { - return null; - } - } - public HttpConnectionManager getHttpConnectionManager() { - if (hasConnection()) { - return wrappedConnection.getHttpConnectionManager(); - } else { - return null; - } - } - public InputStream getLastResponseInputStream() { - if (hasConnection()) { - return wrappedConnection.getLastResponseInputStream(); - } else { - return null; - } - } - public int getPort() { - if (hasConnection()) { - return wrappedConnection.getPort(); - } else { - return -1; - } - } - public Protocol getProtocol() { - if (hasConnection()) { - return wrappedConnection.getProtocol(); - } else { - return null; - } - } - public String getProxyHost() { - if (hasConnection()) { - return wrappedConnection.getProxyHost(); - } else { - return null; - } - } - public int getProxyPort() { - if (hasConnection()) { - return wrappedConnection.getProxyPort(); - } else { - return -1; - } - } - public OutputStream getRequestOutputStream() - throws IOException, IllegalStateException { - if (hasConnection()) { - return wrappedConnection.getRequestOutputStream(); - } else { - return null; - } - } - public InputStream getResponseInputStream() - throws IOException, IllegalStateException { - if (hasConnection()) { - return wrappedConnection.getResponseInputStream(); - } else { - return null; - } - } - public boolean isOpen() { - if (hasConnection()) { - return wrappedConnection.isOpen(); - } else { - return false; - } - } - public boolean closeIfStale() throws IOException { - if (hasConnection()) { - return wrappedConnection.closeIfStale(); - } else { - return false; - } - } - public boolean isProxied() { - if (hasConnection()) { - return wrappedConnection.isProxied(); - } else { - return false; - } - } - public boolean isResponseAvailable() throws IOException { - if (hasConnection()) { - return wrappedConnection.isResponseAvailable(); - } else { - return false; - } - } - public boolean isResponseAvailable(int timeout) throws IOException { - if (hasConnection()) { - return wrappedConnection.isResponseAvailable(timeout); - } else { - return false; - } - } - public boolean isSecure() { - if (hasConnection()) { - return wrappedConnection.isSecure(); - } else { - return false; - } - } - public boolean isTransparent() { - if (hasConnection()) { - return wrappedConnection.isTransparent(); - } else { - return false; - } - } - public void open() throws IOException { - if (hasConnection()) { - wrappedConnection.open(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public void print(String data) - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.print(data); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void printLine() - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.printLine(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public void printLine(String data) - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.printLine(data); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public String readLine() throws IOException, IllegalStateException { - if (hasConnection()) { - return wrappedConnection.readLine(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public String readLine(String charset) throws IOException, IllegalStateException { - if (hasConnection()) { - return wrappedConnection.readLine(charset); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void releaseConnection() { - if (!isLocked() && hasConnection()) { - HttpConnection wrappedConnection = this.wrappedConnection; - this.wrappedConnection = null; - wrappedConnection.releaseConnection(); - } else { - // do nothing - } - } - /** - * @deprecated - */ - public void setConnectionTimeout(int timeout) { - if (hasConnection()) { - wrappedConnection.setConnectionTimeout(timeout); - } else { - // do nothing - } - } - public void setHost(String host) throws IllegalStateException { - if (hasConnection()) { - wrappedConnection.setHost(host); - } else { - // do nothing - } - } - public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) { - if (hasConnection()) { - wrappedConnection.setHttpConnectionManager(httpConnectionManager); - } else { - // do nothing - } - } - public void setLastResponseInputStream(InputStream inStream) { - if (hasConnection()) { - wrappedConnection.setLastResponseInputStream(inStream); - } else { - // do nothing - } - } - public void setPort(int port) throws IllegalStateException { - if (hasConnection()) { - wrappedConnection.setPort(port); - } else { - // do nothing - } - } - public void setProtocol(Protocol protocol) { - if (hasConnection()) { - wrappedConnection.setProtocol(protocol); - } else { - // do nothing - } - } - public void setProxyHost(String host) throws IllegalStateException { - if (hasConnection()) { - wrappedConnection.setProxyHost(host); - } else { - // do nothing - } - } - public void setProxyPort(int port) throws IllegalStateException { - if (hasConnection()) { - wrappedConnection.setProxyPort(port); - } else { - // do nothing - } - } - /** - * @deprecated - */ - public void setSoTimeout(int timeout) - throws SocketException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.setSoTimeout(timeout); - } else { - // do nothing - } - } - /** - * @deprecated - */ - public void shutdownOutput() { - if (hasConnection()) { - wrappedConnection.shutdownOutput(); - } else { - // do nothing - } - } - public void tunnelCreated() throws IllegalStateException, IOException { - if (hasConnection()) { - wrappedConnection.tunnelCreated(); - } else { - // do nothing - } - } - public void write(byte[] data, int offset, int length) - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.write(data, offset, length); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void write(byte[] data) - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.write(data); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void writeLine() - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.writeLine(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void writeLine(byte[] data) - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.writeLine(data); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void flushRequestOutputStream() throws IOException { - if (hasConnection()) { - wrappedConnection.flushRequestOutputStream(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public int getSoTimeout() throws SocketException { - if (hasConnection()) { - return wrappedConnection.getSoTimeout(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public String getVirtualHost() { - if (hasConnection()) { - return wrappedConnection.getVirtualHost(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public void setVirtualHost(String host) throws IllegalStateException { - if (hasConnection()) { - wrappedConnection.setVirtualHost(host); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public int getSendBufferSize() throws SocketException { - if (hasConnection()) { - return wrappedConnection.getSendBufferSize(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /** - * @deprecated - */ - public void setSendBufferSize(int sendBufferSize) throws SocketException { - if (hasConnection()) { - wrappedConnection.setSendBufferSize(sendBufferSize); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public HttpConnectionParams getParams() { - if (hasConnection()) { - return wrappedConnection.getParams(); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - public void setParams(final HttpConnectionParams params) { - if (hasConnection()) { - wrappedConnection.setParams(params); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /* (non-Javadoc) - * @see org.apache.commons.httpclient.HttpConnection#print(java.lang.String, java.lang.String) - */ - public void print(String data, String charset) throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.print(data, charset); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /* (non-Javadoc) - * @see org.apache.commons.httpclient.HttpConnection#printLine(java.lang.String, java.lang.String) - */ - public void printLine(String data, String charset) - throws IOException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.printLine(data, charset); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - /* (non-Javadoc) - * @see org.apache.commons.httpclient.HttpConnection#setSocketTimeout(int) - */ - public void setSocketTimeout(int timeout) throws SocketException, IllegalStateException { - if (hasConnection()) { - wrappedConnection.setSocketTimeout(timeout); - } else { - throw new IllegalStateException("Connection has been released"); - } - } - } diff --git a/clients/java/src/org/apache/commons/httpclient/NTCredentials.java b/clients/java/src/org/apache/commons/httpclient/NTCredentials.java deleted file mode 100644 index 05ada3a..0000000 --- a/clients/java/src/org/apache/commons/httpclient/NTCredentials.java +++ /dev/null @@ -1,192 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NTCredentials.java,v 1.10 2004/04/18 23:51:35 jsdever Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
true
if all of the credentials match.
- */
- public boolean equals(Object o) {
- if (o == null) return false;
- if (this == o) return true;
- if (super.equals(o) ) {
- if (o instanceof NTCredentials) {
- NTCredentials that = (NTCredentials) o;
- return LangUtils.equals(this.domain, that.domain)
- && LangUtils.equals(this.host, that.host);
- }
- }
- return false;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/NameValuePair.java b/clients/java/src/org/apache/commons/httpclient/NameValuePair.java
deleted file mode 100644
index 9e4e873..0000000
--- a/clients/java/src/org/apache/commons/httpclient/NameValuePair.java
+++ /dev/null
@@ -1,152 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NameValuePair.java,v 1.17 2004/04/18 23:51:35 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
A simple class encapsulating a name/value pair.
- * @author B.C. Holmes - * @author Sean C. Sullivan - * @author Mike Bowler - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ -public class NameValuePair implements Serializable { - // ----------------------------------------------------------- Constructors - /** - * Default constructor. - * - */ - public NameValuePair() { - this (null, null); - } - /** - * Constructor. - * @param name The name. - * @param value The value. - */ - public NameValuePair(String name, String value) { - this.name = name; - this.value = value; - } - // ----------------------------------------------------- Instance Variables - /** - * Name. - */ - private String name = null; - /** - * Value. - */ - private String value = null; - // ------------------------------------------------------------- Properties - /** - * Set the name. - * - * @param name The new name - * @see #getName() - */ - public void setName(String name) { - this.name = name; - } - /** - * Return the name. - * - * @return String name The name - * @see #setName(String) - */ - public String getName() { - return name; - } - /** - * Set the value. - * - * @param value The new value. - */ - public void setValue(String value) { - this.value = value; - } - /** - * Return the current value. - * - * @return String value The current value. - */ - public String getValue() { - return value; - } - // --------------------------------------------------------- Public Methods - /** - * Get a String representation of this pair. - * @return A string representation. - */ - public String toString() { - return ("name=" + name + ", " + "value=" + value); - } - public boolean equals(final Object object) { - if (object == null) return false; - if (this == object) return true; - if (object instanceof NameValuePair) { - NameValuePair that = (NameValuePair) object; - return LangUtils.equals(this.name, 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; - } diff --git a/clients/java/src/org/apache/commons/httpclient/NoHttpResponseException.java b/clients/java/src/org/apache/commons/httpclient/NoHttpResponseException.java deleted file mode 100644 index 3b18c08..0000000 --- a/clients/java/src/org/apache/commons/httpclient/NoHttpResponseException.java +++ /dev/null @@ -1,78 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/NoHttpResponseException.java,v 1.1 2004/07/05 22:46:58 olegk Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *- * Even though HTTP CONNECT proxying is generally used for HTTPS tunneling, the returned - * socket will not have been wrapped in an SSL socket. - *
- * - *- * Both the proxy and destination hosts must be set via the - * {@link #getHostConfiguration() host configuration} prior to calling this method. - *
- * - * @return the connect response - * - * @throws IOException - * @throws HttpException - * - * @see #getHostConfiguration() - */ - public ConnectResponse connect() throws IOException, HttpException { - HostConfiguration hostconf = getHostConfiguration(); - if (hostconf.getProxyHost() == null) { - throw new IllegalStateException("proxy host must be configured"); - } - if (hostconf.getHost() == null) { - throw new IllegalStateException("destination host must be configured"); - } - if (hostconf.getProtocol().isSecure()) { - throw new IllegalStateException("secure protocol socket factory may not be used"); - } - ConnectMethod method = new ConnectMethod(getHostConfiguration()); - method.getParams().setDefaults(getParams()); - DummyConnectionManager connectionManager = new DummyConnectionManager(); - connectionManager.setConnectionParams(getParams()); - HttpMethodDirector director = new HttpMethodDirector( - connectionManager, - hostconf, - getParams(), - getState() - ); - director.executeMethod(method); - ConnectResponse response = new ConnectResponse(); - response.setConnectMethod(method); - // only set the socket if the connect was successful - if (method.getStatusCode() == HttpStatus.SC_OK) { - response.setSocket(connectionManager.getConnection().getSocket()); - } else { - connectionManager.getConnection().close(); - } - return response; - } - /** - * Contains the method used to execute the connect along with the created socket. - */ - public static class ConnectResponse { - private ConnectMethod connectMethod; - private Socket socket; - private ConnectResponse() {} - /** - * Gets the method that was used to execute the connect. This method is useful for - * analyzing the proxy's response when a connect fails. - * - * @return the connectMethod. - */ - public ConnectMethod getConnectMethod() { - return connectMethod; - } - /** - * @param connectMethod The connectMethod to set. - */ - private void setConnectMethod(ConnectMethod connectMethod) { - this.connectMethod = connectMethod; - } - /** - * Gets the socket connected and authenticated (if appropriate) to the configured - * HTTP proxy, or
null
if a connection could not be made. It is the
- * responsibility of the user to close this socket when it is no longer needed.
- *
- * @return the socket.
- */
- public Socket getSocket() {
- return socket;
- }
- /**
- * @param socket The socket to set.
- */
- private void setSocket(Socket socket) {
- this.socket = socket;
- }
- }
- /**
- * A connection manager that creates a single connection. Meant to be used only once.
- */
- static class DummyConnectionManager implements HttpConnectionManager {
- private HttpConnection httpConnection;
- private HttpParams connectionParams;
- public void closeIdleConnections(long idleTimeout) {
- }
- public HttpConnection getConnection() {
- return httpConnection;
- }
- public void setConnectionParams(HttpParams httpParams) {
- this.connectionParams = httpParams;
- }
- public HttpConnection getConnectionWithTimeout(
- HostConfiguration hostConfiguration, long timeout) {
- httpConnection = new HttpConnection(hostConfiguration);
- httpConnection.setHttpConnectionManager(this);
- httpConnection.getParams().setDefaults(connectionParams);
- return httpConnection;
- }
- /**
- * @deprecated
- */
- public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout)
- throws HttpException {
- return getConnectionWithTimeout(hostConfiguration, timeout);
- }
- public HttpConnection getConnection(HostConfiguration hostConfiguration) {
- return getConnectionWithTimeout(hostConfiguration, -1);
- }
- public void releaseConnection(HttpConnection conn) {
- }
- public HttpConnectionManagerParams getParams() {
- return null;
- }
- public void setParams(HttpConnectionManagerParams params) {
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/ProxyHost.java b/clients/java/src/org/apache/commons/httpclient/ProxyHost.java
deleted file mode 100644
index 8459b5e..0000000
--- a/clients/java/src/org/apache/commons/httpclient/ProxyHost.java
+++ /dev/null
@@ -1,85 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/ProxyHost.java,v 1.2 2005/01/14 21:16:40 olegk Exp $
- * $Revision: 510587 $
- * $Date: 2007-02-22 17:56:08 +0100 (Thu, 22 Feb 2007) $
- * ====================================================================
- * 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
- *
null
.
- * @param port the port. Value
-1
can be used to set default protocol port
- */
- public ProxyHost(final String hostname, int port) {
- super(hostname, port, Protocol.getProtocol("http"));
- }
- /**
- * Constructor for HttpHost.
- *
- * @param hostname the hostname (IP or DNS name). Can be
null
.
- */
- public ProxyHost(final String hostname) {
- this(hostname, -1);
- }
- /**
- * @throws CloneNotSupportedException
- * @see java.lang.Object#clone()
- */
- public Object clone() throws CloneNotSupportedException {
- ProxyHost copy = (ProxyHost) super.clone();
- return copy;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/RedirectException.java b/clients/java/src/org/apache/commons/httpclient/RedirectException.java
deleted file mode 100644
index 4d5e88a..0000000
--- a/clients/java/src/org/apache/commons/httpclient/RedirectException.java
+++ /dev/null
@@ -1,68 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/RedirectException.java,v 1.2 2004/04/18 23:51:35 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
When one of the three types of {@link java.io.InputStream}, one of - * AutoCloseInputStream (package), {@link ContentLengthInputStream}, or - * {@link ChunkedInputStream} finishes with its content, either because - * all content has been consumed, or because it was explicitly closed, - * it notifies its corresponding method via this interface.
- * @see ContentLengthInputStream - * @see ChunkedInputStream - * @author Eric Johnson -interface ResponseConsumedWatcher { - /** - * A response has been consumed. - */ - void responseConsumed(); diff --git a/clients/java/src/org/apache/commons/httpclient/SimpleHttpConnectionManager.java b/clients/java/src/org/apache/commons/httpclient/SimpleHttpConnectionManager.java deleted file mode 100644 index 13a25a2..0000000 --- a/clients/java/src/org/apache/commons/httpclient/SimpleHttpConnectionManager.java +++ /dev/null @@ -1,284 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/SimpleHttpConnectionManager.java,v 1.23 2004/10/16 22:40:08 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
true
if stale checking will be enabled on HttpConections
- *
- * @see HttpConnection#isStaleCheckingEnabled()
- *
- * @deprecated Use {@link HttpConnectionManagerParams#isStaleCheckingEnabled()},
- * {@link HttpConnectionManager#getParams()}.
- */
- public boolean isConnectionStaleCheckingEnabled() {
- return this.params.isStaleCheckingEnabled();
- }
- /**
- * Sets the staleCheckingEnabled value to be set on HttpConnections that are created.
- *
- * @param connectionStaleCheckingEnabled
true
if stale checking will be enabled
- * on HttpConections
- *
- * @see HttpConnection#setStaleCheckingEnabled(boolean)
- *
- * @deprecated Use {@link HttpConnectionManagerParams#setStaleCheckingEnabled(boolean)},
- * {@link HttpConnectionManager#getParams()}.
- */
- public void setConnectionStaleCheckingEnabled(boolean connectionStaleCheckingEnabled) {
- this.params.setStaleCheckingEnabled(connectionStaleCheckingEnabled);
- }
- /**
- * This method always returns the same connection object. If the connection is already
- * open, it will be closed and the new host configuration will be applied.
- *
- * @param hostConfiguration The host configuration specifying the connection
- * details.
- * @param timeout this parameter has no effect. The connection is always returned
- * immediately.
- * @since 3.0
- */
- public HttpConnection getConnectionWithTimeout(
- HostConfiguration hostConfiguration, long timeout) {
- if (httpConnection == null) {
- httpConnection = new HttpConnection(hostConfiguration);
- httpConnection.setHttpConnectionManager(this);
- httpConnection.getParams().setDefaults(this.params);
- } else {
- // make sure the host and proxy are correct for this connection
- // close it and set the values if they are not
- if (!hostConfiguration.hostEquals(httpConnection)
- || !hostConfiguration.proxyEquals(httpConnection)) {
- if (httpConnection.isOpen()) {
- httpConnection.close();
- }
- httpConnection.setHost(hostConfiguration.getHost());
- httpConnection.setPort(hostConfiguration.getPort());
- httpConnection.setProtocol(hostConfiguration.getProtocol());
- httpConnection.setLocalAddress(hostConfiguration.getLocalAddress());
- httpConnection.setProxyHost(hostConfiguration.getProxyHost());
- httpConnection.setProxyPort(hostConfiguration.getProxyPort());
- } else {
- finishLastResponse(httpConnection);
- }
- }
- // remove the connection from the timeout handler
- idleStartTime = Long.MAX_VALUE;
- if (inUse) LOG.warn(MISUSE_MESSAGE);
- inUse = true;
- return httpConnection;
- }
- /**
- * @see HttpConnectionManager#getConnection(HostConfiguration, long)
- *
- * @deprecated Use #getConnectionWithTimeout(HostConfiguration, long)
- */
- public HttpConnection getConnection(
- HostConfiguration hostConfiguration, long timeout) {
- return getConnectionWithTimeout(hostConfiguration, timeout);
- }
- /**
- * @see HttpConnectionManager#releaseConnection(org.apache.commons.httpclient.HttpConnection)
- */
- public void releaseConnection(HttpConnection conn) {
- if (conn != httpConnection) {
- throw new IllegalStateException("Unexpected release of an unknown connection.");
- }
- if (this.alwaysClose) {
- httpConnection.close();
- } else {
- // make sure the connection is reuseable
- finishLastResponse(httpConnection);
- }
- inUse = false;
- // track the time the connection was made idle
- idleStartTime = System.currentTimeMillis();
- }
- /**
- * Returns {@link HttpConnectionManagerParams parameters} associated
- * with this connection manager.
- *
- * @since 2.1
- *
- * @see HttpConnectionManagerParams
- */
- public HttpConnectionManagerParams getParams() {
- return this.params;
- }
- /**
- * Assigns {@link HttpConnectionManagerParams parameters} for this
- * connection manager.
- *
- * @since 2.1
- *
- * @see HttpConnectionManagerParams
- */
- public void setParams(final HttpConnectionManagerParams params) {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- this.params = params;
- }
- /**
- * @since 3.0
- */
- public void closeIdleConnections(long idleTimeout) {
- long maxIdleTime = System.currentTimeMillis() - idleTimeout;
- if (idleStartTime <= maxIdleTime) {
- httpConnection.close();
- }
- }
- /**
- * since 3.1
- */
- public void shutdown() {
- httpConnection.close();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/StatusLine.java b/clients/java/src/org/apache/commons/httpclient/StatusLine.java
deleted file mode 100644
index c983dd8..0000000
--- a/clients/java/src/org/apache/commons/httpclient/StatusLine.java
+++ /dev/null
@@ -1,185 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/StatusLine.java,v 1.14 2004/07/19 20:24:21 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
- *
- * @see #getProtocolCharset
- *
- * @since 3.0
- */
- public URI(String s, boolean escaped, String charset)
- throws URIException, NullPointerException {
- protocolCharset = charset;
- parseUriReference(s, escaped);
- }
- /**
- * Construct a URI from a string with the given charset. The input string can
- * be either in escaped or unescaped form.
- *
- * @param s URI character sequence
- * @param escaped
true
if URI character sequence is in escaped form.
- *
false
otherwise.
- *
- * @throws URIException If the URI cannot be created.
- * @throws NullPointerException if input string is
null
- *
- * @see #getProtocolCharset
- *
- * @since 3.0
- */
- public URI(String s, boolean escaped)
- throws URIException, NullPointerException {
- parseUriReference(s, escaped);
- }
- /**
- * Construct a URI as an escaped form of a character array with the given
- * charset.
- *
- * @param escaped the URI character sequence
- * @param charset the charset string to do escape encoding
- * @throws URIException If the URI cannot be created.
- * @throws NullPointerException if
escaped
is
null
- * @see #getProtocolCharset
- *
- * @deprecated Use #URI(String, boolean, String)
- */
- public URI(char[] escaped, String charset)
- throws URIException, NullPointerException {
- protocolCharset = charset;
- parseUriReference(new String(escaped), true);
- }
- /**
- * Construct a URI as an escaped form of a character array.
- * An URI can be placed within double-quotes or angle brackets like
- * "http://test.com/" and <http://test.com/>
- *
- * @param escaped the URI character sequence
- * @throws URIException If the URI cannot be created.
- * @throws NullPointerException if
escaped
is
null
- * @see #getDefaultProtocolCharset
- *
- * @deprecated Use #URI(String, boolean)
- */
- public URI(char[] escaped)
- throws URIException, NullPointerException {
- parseUriReference(new String(escaped), true);
- }
- /**
- * Construct a URI from the given string with the given charset.
- *
- * @param original the string to be represented to URI character sequence
- * It is one of absoluteURI and relativeURI.
- * @param charset the charset string to do escape encoding
- * @throws URIException If the URI cannot be created.
- * @see #getProtocolCharset
- *
- * @deprecated Use #URI(String, boolean, String)
- */
- public URI(String original, String charset) throws URIException {
- protocolCharset = charset;
- parseUriReference(original, false);
- }
- /**
- * Construct a URI from the given string.
- *
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] - *
- * An URI can be placed within double-quotes or angle brackets like - * "http://test.com/" and <http://test.com/> - * - * @param original the string to be represented to URI character sequence - * It is one of absoluteURI and relativeURI. - * @throws URIException If the URI cannot be created. - * @see #getDefaultProtocolCharset - * - * @deprecated Use #URI(String, boolean) - */ - public URI(String original) throws URIException { - parseUriReference(original, false); - } - /** - * Construct a general URI from the given components. - *
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] - * absoluteURI = scheme ":" ( hier_part | opaque_part ) - * opaque_part = uric_no_slash *uric - *
- * It's for absolute URI = <scheme>:<scheme-specific-part># - * <fragment>. - * - * @param scheme the scheme string - * @param schemeSpecificPart scheme_specific_part - * @param fragment the fragment string - * @throws URIException If the URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String schemeSpecificPart, String fragment) - throws URIException { - // validate and contruct the URI character sequence - if (scheme == null) { - throw new URIException(URIException.PARSING, "scheme required"); - } - char[] s = scheme.toLowerCase().toCharArray(); - if (validate(s, URI.scheme)) { - _scheme = s; // is_absoluteURI - } else { - throw new URIException(URIException.PARSING, "incorrect scheme"); - } - _opaque = encode(schemeSpecificPart, allowed_opaque_part, - getProtocolCharset()); - // Set flag - _is_opaque_part = true; - _fragment = fragment == null ? null : fragment.toCharArray(); - setURI(); - } - /** - * Construct a general URI from the given components. - *
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] - * absoluteURI = scheme ":" ( hier_part | opaque_part ) - * relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] - * hier_part = ( net_path | abs_path ) [ "?" query ] - *
- * It's for absolute URI = <scheme>:<path>?<query>#< - * fragment> and relative URI = <path>?<query>#<fragment - * >. - * - * @param scheme the scheme string - * @param authority the authority string - * @param path the path string - * @param query the query string - * @param fragment the fragment string - * @throws URIException If the new URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String authority, String path, String query, - String fragment) throws URIException { - // validate and contruct the URI character sequence - StringBuffer buff = new StringBuffer(); - if (scheme != null) { - buff.append(scheme); - buff.append(':'); - } - if (authority != null) { - buff.append("//"); - buff.append(authority); - } - if (path != null) { // accept empty path - if ((scheme != null || authority != null) - && !path.startsWith("/")) { - throw new URIException(URIException.PARSING, - "abs_path requested"); - } - buff.append(path); - } - if (query != null) { - buff.append('?'); - buff.append(query); - } - if (fragment != null) { - buff.append('#'); - buff.append(fragment); - } - parseUriReference(buff.toString(), false); - } - /** - * Construct a general URI from the given components. - * - * @param scheme the scheme string - * @param userinfo the userinfo string - * @param host the host string - * @param port the port number - * @throws URIException If the new URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String userinfo, String host, int port) - throws URIException { - this(scheme, userinfo, host, port, null, null, null); - } - /** - * Construct a general URI from the given components. - * - * @param scheme the scheme string - * @param userinfo the userinfo string - * @param host the host string - * @param port the port number - * @param path the path string - * @throws URIException If the new URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String userinfo, String host, int port, - String path) throws URIException { - this(scheme, userinfo, host, port, path, null, null); - } - /** - * Construct a general URI from the given components. - * - * @param scheme the scheme string - * @param userinfo the userinfo string - * @param host the host string - * @param port the port number - * @param path the path string - * @param query the query string - * @throws URIException If the new URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String userinfo, String host, int port, - String path, String query) throws URIException { - this(scheme, userinfo, host, port, path, query, null); - } - /** - * Construct a general URI from the given components. - * - * @param scheme the scheme string - * @param userinfo the userinfo string - * @param host the host string - * @param port the port number - * @param path the path string - * @param query the query string - * @param fragment the fragment string - * @throws URIException If the new URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String userinfo, String host, int port, - String path, String query, String fragment) throws URIException { - this(scheme, (host == null) ? null - : ((userinfo != null) ? userinfo + '@' : "") + host - + ((port != -1) ? ":" + port : ""), path, query, fragment); - } - /** - * Construct a general URI from the given components. - * - * @param scheme the scheme string - * @param host the host string - * @param path the path string - * @param fragment the fragment string - * @throws URIException If the new URI cannot be created. - * @see #getDefaultProtocolCharset - */ - public URI(String scheme, String host, String path, String fragment) - throws URIException { - this(scheme, host, path, null, fragment); - } - /** - * Construct a general URI with the given relative URI string. - * - * @param base the base URI - * @param relative the relative URI string - * @throws URIException If the new URI cannot be created. - * - * @deprecated Use #URI(URI, String, boolean) - */ - public URI(URI base, String relative) throws URIException { - this(base, new URI(relative)); - } - /** - * Construct a general URI with the given relative URI string. - * - * @param base the base URI - * @param relative the relative URI string - * @param escaped true if URI character sequence is in escaped form. - * false otherwise. - * - * @throws URIException If the new URI cannot be created. - * - * @since 3.0 - */ - public URI(URI base, String relative, boolean escaped) throws URIException { - this(base, new URI(relative, escaped)); - } - /** - * Construct a general URI with the given relative URI. - *
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] - * relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] - *
- * Resolving Relative References to Absolute Form. - * - * Examples of Resolving Relative URI References - * - * Within an object with a well-defined base URI of - *
- * http://a/b/c/d;p?q - *
- * the relative URI would be resolved as follows: - * - * Normal Examples - * - *
- * g:h = g:h - * g = http://a/b/c/g - * ./g = http://a/b/c/g - * g/ = http://a/b/c/g/ - * /g = http://a/g - * //g = http://g - * ?y = http://a/b/c/?y - * g?y = http://a/b/c/g?y - * #s = (current document)#s - * g#s = http://a/b/c/g#s - * g?y#s = http://a/b/c/g?y#s - * ;x = http://a/b/c/;x - * g;x = http://a/b/c/g;x - * g;x?y#s = http://a/b/c/g;x?y#s - * . = http://a/b/c/ - * ./ = http://a/b/c/ - * .. = http://a/b/ - * ../ = http://a/b/ - * ../g = http://a/b/g - * ../.. = http://a/ - * ../../ = http://a/ - * ../../g = http://a/g - *
- *
- * Some URI schemes do not allow a hierarchical syntax matching the
- *
- * digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | - * "8" | "9" - *
- */ - protected static final BitSet digit = new BitSet(256); - // Static initializer for digit - static { - for (int i = '0'; i <= '9'; i++) { - digit.set(i); - } - } - /** - * BitSet for alpha. - *
- * alpha = lowalpha | upalpha - *
- */ - protected static final BitSet alpha = new BitSet(256); - // Static initializer for alpha - static { - for (int i = 'a'; i <= 'z'; i++) { - alpha.set(i); - } - for (int i = 'A'; i <= 'Z'; i++) { - alpha.set(i); - } - } - /** - * BitSet for alphanum (join of alpha & digit). - *
- * alphanum = alpha | digit - *
- */ - protected static final BitSet alphanum = new BitSet(256); - // Static initializer for alphanum - static { - alphanum.or(alpha); - alphanum.or(digit); - } - /** - * BitSet for hex. - *
- * hex = digit | "A" | "B" | "C" | "D" | "E" | "F" | - * "a" | "b" | "c" | "d" | "e" | "f" - *
- */ - protected static final BitSet hex = new BitSet(256); - // Static initializer for hex - static { - hex.or(digit); - for (int i = 'a'; i <= 'f'; i++) { - hex.set(i); - } - for (int i = 'A'; i <= 'F'; i++) { - hex.set(i); - } - } - /** - * BitSet for escaped. - *
- * escaped = "%" hex hex - *
- */ - protected static final BitSet escaped = new BitSet(256); - // Static initializer for escaped - static { - escaped.or(percent); - escaped.or(hex); - } - /** - * BitSet for mark. - *
- * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | - * "(" | ")" - *
- */ - protected static final BitSet mark = new BitSet(256); - // Static initializer for mark - static { - mark.set('-'); - mark.set('_'); - mark.set('.'); - mark.set('!'); - mark.set('~'); - mark.set('*'); - mark.set('\''); - mark.set('('); - mark.set(')'); - } - /** - * Data characters that are allowed in a URI but do not have a reserved - * purpose are called unreserved. - *
- * unreserved = alphanum | mark - *
- */ - protected static final BitSet unreserved = new BitSet(256); - // Static initializer for unreserved - static { - unreserved.or(alphanum); - unreserved.or(mark); - } - /** - * BitSet for reserved. - *
- * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | - * "$" | "," - *
- */ - protected static final BitSet reserved = new BitSet(256); - // Static initializer for reserved - static { - reserved.set(';'); - reserved.set('/'); - reserved.set('?'); - reserved.set(':'); - reserved.set('@'); - reserved.set('&'); - reserved.set('='); - reserved.set('+'); - reserved.set('$'); - reserved.set(','); - } - /** - * BitSet for uric. - *
- * uric = reserved | unreserved | escaped - *
- */ - protected static final BitSet uric = new BitSet(256); - // Static initializer for uric - static { - uric.or(reserved); - uric.or(unreserved); - uric.or(escaped); - } - /** - * BitSet for fragment (alias for uric). - *
- * fragment = *uric - *
- */ - protected static final BitSet fragment = uric; - /** - * BitSet for query (alias for uric). - *
- * query = *uric - *
- */ - protected static final BitSet query = uric; - /** - * BitSet for pchar. - *
- * pchar = unreserved | escaped | - * ":" | "@" | "&" | "=" | "+" | "$" | "," - *
- */ - protected static final BitSet pchar = new BitSet(256); - // Static initializer for pchar - static { - pchar.or(unreserved); - pchar.or(escaped); - pchar.set(':'); - pchar.set('@'); - pchar.set('&'); - pchar.set('='); - pchar.set('+'); - pchar.set('$'); - pchar.set(','); - } - /** - * BitSet for param (alias for pchar). - *
- * param = *pchar - *
- */ - protected static final BitSet param = pchar; - /** - * BitSet for segment. - *
- * segment = *pchar *( ";" param ) - *
- */ - protected static final BitSet segment = new BitSet(256); - // Static initializer for segment - static { - segment.or(pchar); - segment.set(';'); - segment.or(param); - } - /** - * BitSet for path segments. - *
- * path_segments = segment *( "/" segment ) - *
- */ - protected static final BitSet path_segments = new BitSet(256); - // Static initializer for path_segments - static { - path_segments.set('/'); - path_segments.or(segment); - } - /** - * URI absolute path. - *
- * abs_path = "/" path_segments - *
- */ - protected static final BitSet abs_path = new BitSet(256); - // Static initializer for abs_path - static { - abs_path.set('/'); - abs_path.or(path_segments); - } - /** - * URI bitset for encoding typical non-slash characters. - *
- * uric_no_slash = unreserved | escaped | ";" | "?" | ":" | "@" | - * "&" | "=" | "+" | "$" | "," - *
- */ - protected static final BitSet uric_no_slash = new BitSet(256); - // Static initializer for uric_no_slash - static { - uric_no_slash.or(unreserved); - uric_no_slash.or(escaped); - uric_no_slash.set(';'); - uric_no_slash.set('?'); - uric_no_slash.set(';'); - uric_no_slash.set('@'); - uric_no_slash.set('&'); - uric_no_slash.set('='); - uric_no_slash.set('+'); - uric_no_slash.set('$'); - uric_no_slash.set(','); - } - /** - * URI bitset that combines uric_no_slash and uric. - *
- * opaque_part = uric_no_slash *uric - *
- */ - protected static final BitSet opaque_part = new BitSet(256); - // Static initializer for opaque_part - static { - // it's generous. because first character must not include a slash - opaque_part.or(uric_no_slash); - opaque_part.or(uric); - } - /** - * URI bitset that combines absolute path and opaque part. - *
- * path = [ abs_path | opaque_part ] - *
- */ - protected static final BitSet path = new BitSet(256); - // Static initializer for path - static { - path.or(abs_path); - path.or(opaque_part); - } - /** - * Port, a logical alias for digit. - */ - protected static final BitSet port = digit; - /** - * Bitset that combines digit and dot fo IPv$address. - *
- * IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit - *
- */ - protected static final BitSet IPv4address = new BitSet(256); - // Static initializer for IPv4address - static { - IPv4address.or(digit); - IPv4address.set('.'); - } - /** - * RFC 2373. - *
- * IPv6address = hexpart [ ":" IPv4address ] - *
- */ - protected static final BitSet IPv6address = new BitSet(256); - // Static initializer for IPv6address reference - static { - IPv6address.or(hex); // hexpart - IPv6address.set(':'); - IPv6address.or(IPv4address); - } - /** - * RFC 2732, 2373. - *
- * IPv6reference = "[" IPv6address "]" - *
- */ - protected static final BitSet IPv6reference = new BitSet(256); - // Static initializer for IPv6reference - static { - IPv6reference.set('['); - IPv6reference.or(IPv6address); - IPv6reference.set(']'); - } - /** - * BitSet for toplabel. - *
- * toplabel = alpha | alpha *( alphanum | "-" ) alphanum - *
- */ - protected static final BitSet toplabel = new BitSet(256); - // Static initializer for toplabel - static { - toplabel.or(alphanum); - toplabel.set('-'); - } - /** - * BitSet for domainlabel. - *
- * domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum - *
- */ - protected static final BitSet domainlabel = toplabel; - /** - * BitSet for hostname. - *
- * hostname = *( domainlabel "." ) toplabel [ "." ] - *
- */ - protected static final BitSet hostname = new BitSet(256); - // Static initializer for hostname - static { - hostname.or(toplabel); - // hostname.or(domainlabel); - hostname.set('.'); - } - /** - * BitSet for host. - *
- * host = hostname | IPv4address | IPv6reference - *
- */ - protected static final BitSet host = new BitSet(256); - // Static initializer for host - static { - host.or(hostname); - // host.or(IPv4address); - host.or(IPv6reference); // IPv4address - } - /** - * BitSet for hostport. - *
- * hostport = host [ ":" port ] - *
- */ - protected static final BitSet hostport = new BitSet(256); - // Static initializer for hostport - static { - hostport.or(host); - hostport.set(':'); - hostport.or(port); - } - /** - * Bitset for userinfo. - *
- * userinfo = *( unreserved | escaped | - * ";" | ":" | "&" | "=" | "+" | "$" | "," ) - *
- */ - protected static final BitSet userinfo = new BitSet(256); - // Static initializer for userinfo - static { - userinfo.or(unreserved); - userinfo.or(escaped); - userinfo.set(';'); - userinfo.set(':'); - userinfo.set('&'); - userinfo.set('='); - userinfo.set('+'); - userinfo.set('$'); - userinfo.set(','); - } - /** - * BitSet for within the userinfo component like user and password. - */ - public static final BitSet within_userinfo = new BitSet(256); - // Static initializer for within_userinfo - static { - within_userinfo.or(userinfo); - within_userinfo.clear(';'); // reserved within authority - within_userinfo.clear(':'); - within_userinfo.clear('@'); - within_userinfo.clear('?'); - within_userinfo.clear('/'); - } - /** - * Bitset for server. - *
- * server = [ [ userinfo "@" ] hostport ] - *
- */ - protected static final BitSet server = new BitSet(256); - // Static initializer for server - static { - server.or(userinfo); - server.set('@'); - server.or(hostport); - } - /** - * BitSet for reg_name. - *
- * reg_name = 1*( unreserved | escaped | "$" | "," | - * ";" | ":" | "@" | "&" | "=" | "+" ) - *
- */ - protected static final BitSet reg_name = new BitSet(256); - // Static initializer for reg_name - static { - reg_name.or(unreserved); - reg_name.or(escaped); - reg_name.set('$'); - reg_name.set(','); - reg_name.set(';'); - reg_name.set(':'); - reg_name.set('@'); - reg_name.set('&'); - reg_name.set('='); - reg_name.set('+'); - } - /** - * BitSet for authority. - *
- * authority = server | reg_name - *
- */ - protected static final BitSet authority = new BitSet(256); - // Static initializer for authority - static { - authority.or(server); - authority.or(reg_name); - } - /** - * BitSet for scheme. - *
- * scheme = alpha *( alpha | digit | "+" | "-" | "." ) - *
- */ - protected static final BitSet scheme = new BitSet(256); - // Static initializer for scheme - static { - scheme.or(alpha); - scheme.or(digit); - scheme.set('+'); - scheme.set('-'); - scheme.set('.'); - } - /** - * BitSet for rel_segment. - *
- * rel_segment = 1*( unreserved | escaped | - * ";" | "@" | "&" | "=" | "+" | "$" | "," ) - *
- */ - protected static final BitSet rel_segment = new BitSet(256); - // Static initializer for rel_segment - static { - rel_segment.or(unreserved); - rel_segment.or(escaped); - rel_segment.set(';'); - rel_segment.set('@'); - rel_segment.set('&'); - rel_segment.set('='); - rel_segment.set('+'); - rel_segment.set('$'); - rel_segment.set(','); - } - /** - * BitSet for rel_path. - *
- * rel_path = rel_segment [ abs_path ] - *
- */ - protected static final BitSet rel_path = new BitSet(256); - // Static initializer for rel_path - static { - rel_path.or(rel_segment); - rel_path.or(abs_path); - } - /** - * BitSet for net_path. - *
- * net_path = "//" authority [ abs_path ] - *
- */ - protected static final BitSet net_path = new BitSet(256); - // Static initializer for net_path - static { - net_path.set('/'); - net_path.or(authority); - net_path.or(abs_path); - } - /** - * BitSet for hier_part. - *
- * hier_part = ( net_path | abs_path ) [ "?" query ] - *
- */ - protected static final BitSet hier_part = new BitSet(256); - // Static initializer for hier_part - static { - hier_part.or(net_path); - hier_part.or(abs_path); - // hier_part.set('?'); aleady included - hier_part.or(query); - } - /** - * BitSet for relativeURI. - *
- * relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] - *
- */ - protected static final BitSet relativeURI = new BitSet(256); - // Static initializer for relativeURI - static { - relativeURI.or(net_path); - relativeURI.or(abs_path); - relativeURI.or(rel_path); - // relativeURI.set('?'); aleady included - relativeURI.or(query); - } - /** - * BitSet for absoluteURI. - *
- * absoluteURI = scheme ":" ( hier_part | opaque_part ) - *
- */ - protected static final BitSet absoluteURI = new BitSet(256); - // Static initializer for absoluteURI - static { - absoluteURI.or(scheme); - absoluteURI.set(':'); - absoluteURI.or(hier_part); - absoluteURI.or(opaque_part); - } - /** - * BitSet for URI-reference. - *
- * URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] - *
- */ - protected static final BitSet URI_reference = new BitSet(256); - // Static initializer for URI_reference - static { - URI_reference.or(absoluteURI); - URI_reference.or(relativeURI); - URI_reference.set('#'); - URI_reference.or(fragment); - } - // ---------------------------- Characters disallowed within the URI syntax - // Excluded US-ASCII Characters are like control, space, delims and unwise - /** - * BitSet for control. - */ - public static final BitSet control = new BitSet(256); - // Static initializer for control - static { - for (int i = 0; i <= 0x1F; i++) { - control.set(i); - } - control.set(0x7F); - } - /** - * BitSet for space. - */ - public static final BitSet space = new BitSet(256); - // Static initializer for space - static { - space.set(0x20); - } - /** - * BitSet for delims. - */ - public static final BitSet delims = new BitSet(256); - // Static initializer for delims - static { - delims.set(''); - delims.set('#'); - delims.set('%'); - delims.set('"'); - } - /** - * BitSet for unwise. - */ - public static final BitSet unwise = new BitSet(256); - // Static initializer for unwise - static { - unwise.set('{'); - unwise.set('}'); - unwise.set('|'); - unwise.set('\\'); - unwise.set('^'); - unwise.set('['); - unwise.set(']'); - unwise.set('`'); - } - /** - * Disallowed rel_path before escaping. - */ - public static final BitSet disallowed_rel_path = new BitSet(256); - // Static initializer for disallowed_rel_path - static { - disallowed_rel_path.or(uric); - disallowed_rel_path.andNot(rel_path); - } - /** - * Disallowed opaque_part before escaping. - */ - public static final BitSet disallowed_opaque_part = new BitSet(256); - // Static initializer for disallowed_opaque_part - static { - disallowed_opaque_part.or(uric); - disallowed_opaque_part.andNot(opaque_part); - } - // ----------------------- Characters allowed within and for each component - /** - * Those characters that are allowed for the authority component. - */ - public static final BitSet allowed_authority = new BitSet(256); - // Static initializer for allowed_authority - static { - allowed_authority.or(authority); - allowed_authority.clear('%'); - } - /** - * Those characters that are allowed for the opaque_part. - */ - public static final BitSet allowed_opaque_part = new BitSet(256); - // Static initializer for allowed_opaque_part - static { - allowed_opaque_part.or(opaque_part); - allowed_opaque_part.clear('%'); - } - /** - * Those characters that are allowed for the reg_name. - */ - public static final BitSet allowed_reg_name = new BitSet(256); - // Static initializer for allowed_reg_name - static { - allowed_reg_name.or(reg_name); - // allowed_reg_name.andNot(percent); - allowed_reg_name.clear('%'); - } - /** - * Those characters that are allowed for the userinfo component. - */ - public static final BitSet allowed_userinfo = new BitSet(256); - // Static initializer for allowed_userinfo - static { - allowed_userinfo.or(userinfo); - // allowed_userinfo.andNot(percent); - allowed_userinfo.clear('%'); - } - /** - * Those characters that are allowed for within the userinfo component. - */ - public static final BitSet allowed_within_userinfo = new BitSet(256); - // Static initializer for allowed_within_userinfo - static { - allowed_within_userinfo.or(within_userinfo); - allowed_within_userinfo.clear('%'); - } - /** - * Those characters that are allowed for the IPv6reference component. - * The characters '[', ']' in IPv6reference should be excluded. - */ - public static final BitSet allowed_IPv6reference = new BitSet(256); - // Static initializer for allowed_IPv6reference - static { - allowed_IPv6reference.or(IPv6reference); - // allowed_IPv6reference.andNot(unwise); - allowed_IPv6reference.clear('['); - allowed_IPv6reference.clear(']'); - } - /** - * Those characters that are allowed for the host component. - * The characters '[', ']' in IPv6reference should be excluded. - */ - public static final BitSet allowed_host = new BitSet(256); - // Static initializer for allowed_host - static { - allowed_host.or(hostname); - allowed_host.or(allowed_IPv6reference); - } - /** - * Those characters that are allowed for the authority component. - */ - public static final BitSet allowed_within_authority = new BitSet(256); - // Static initializer for allowed_within_authority - static { - allowed_within_authority.or(server); - allowed_within_authority.or(reg_name); - allowed_within_authority.clear(';'); - allowed_within_authority.clear(':'); - allowed_within_authority.clear('@'); - allowed_within_authority.clear('?'); - allowed_within_authority.clear('/'); - } - /** - * Those characters that are allowed for the abs_path. - */ - public static final BitSet allowed_abs_path = new BitSet(256); - // Static initializer for allowed_abs_path - static { - allowed_abs_path.or(abs_path); - // allowed_abs_path.set('/'); // aleady included - allowed_abs_path.andNot(percent); - allowed_abs_path.clear('+'); - } - /** - * Those characters that are allowed for the rel_path. - */ - public static final BitSet allowed_rel_path = new BitSet(256); - // Static initializer for allowed_rel_path - static { - allowed_rel_path.or(rel_path); - allowed_rel_path.clear('%'); - allowed_rel_path.clear('+'); - } - /** - * Those characters that are allowed within the path. - */ - public static final BitSet allowed_within_path = new BitSet(256); - // Static initializer for allowed_within_path - static { - allowed_within_path.or(abs_path); - allowed_within_path.clear('/'); - allowed_within_path.clear(';'); - allowed_within_path.clear('='); - allowed_within_path.clear('?'); - } - /** - * Those characters that are allowed for the query component. - */ - public static final BitSet allowed_query = new BitSet(256); - // Static initializer for allowed_query - static { - allowed_query.or(uric); - allowed_query.clear('%'); - } - /** - * Those characters that are allowed within the query component. - */ - public static final BitSet allowed_within_query = new BitSet(256); - // Static initializer for allowed_within_query - static { - allowed_within_query.or(allowed_query); - allowed_within_query.andNot(reserved); // excluded 'reserved' - } - /** - * Those characters that are allowed for the fragment component. - */ - public static final BitSet allowed_fragment = new BitSet(256); - // Static initializer for allowed_fragment - static { - allowed_fragment.or(uric); - allowed_fragment.clear('%'); - } - // ------------------------------------------- Flags for this URI-reference - // TODO: Figure out what all these variables are for and provide javadoc - // URI-reference = [ absoluteURI | relativeURI ] [ "#" fragment ] - // absoluteURI = scheme ":" ( hier_part | opaque_part ) - protected boolean _is_hier_part; - protected boolean _is_opaque_part; - // relativeURI = ( net_path | abs_path | rel_path ) [ "?" query ] - // hier_part = ( net_path | abs_path ) [ "?" query ] - protected boolean _is_net_path; - protected boolean _is_abs_path; - protected boolean _is_rel_path; - // net_path = "//" authority [ abs_path ] - // authority = server | reg_name - protected boolean _is_reg_name; - protected boolean _is_server; // = _has_server - // server = [ [ userinfo "@" ] hostport ] - // host = hostname | IPv4address | IPv6reference - protected boolean _is_hostname; - protected boolean _is_IPv4address; - protected boolean _is_IPv6reference; - // ------------------------------------------ Character and escape encoding - /** - * Encodes URI string. - * - * This is a two mapping, one from original characters to octets, and - * subsequently a second from octets to URI characters: - *
- * original character sequence->octet sequence->URI character sequence - *
- * - * An escaped octet is encoded as a character triplet, consisting of the - * percent character "%" followed by the two hexadecimal digits - * representing the octet code. For example, "%20" is the escaped - * encoding for the US-ASCII space character. - *
- * Conversion from the local filesystem character set to UTF-8 will - * normally involve a two step process. First convert the local character - * set to the UCS; then convert the UCS to UTF-8. - * The first step in the process can be performed by maintaining a mapping - * table that includes the local character set code and the corresponding - * UCS code. - * The next step is to convert the UCS character code to the UTF-8 encoding. - *
- * Mapping between vendor codepages can be done in a very similar manner - * as described above. - *
- * The only time escape encodings can allowedly be made is when a URI is - * being created from its component parts. The escape and validate methods - * are internally performed within this method. - * - * @param original the original character sequence - * @param allowed those characters that are allowed within a component - * @param charset the protocol charset - * @return URI character sequence - * @throws URIException null component or unsupported character encoding - */ - protected static char[] encode(String original, BitSet allowed, - String charset) throws URIException { - if (original == null) { - throw new IllegalArgumentException("Original string may not be null"); - } - if (allowed == null) { - throw new IllegalArgumentException("Allowed bitset may not be null"); - } - byte[] rawdata = URLCodec.encodeUrl(allowed, EncodingUtil.getBytes(original, charset)); - return EncodingUtil.getAsciiString(rawdata).toCharArray(); - } - /** - * Decodes URI encoded string. - * - * This is a two mapping, one from URI characters to octets, and - * subsequently a second from octets to original characters: - *
- * URI character sequence->octet sequence->original character sequence - *
- * - * A URI must be separated into its components before the escaped - * characters within those components can be allowedly decoded. - *
- * Notice that there is a chance that URI characters that are non UTF-8 - * may be parsed as valid UTF-8. A recent non-scientific analysis found - * that EUC encoded Japanese words had a 2.7% false reading; SJIS had a - * 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0% - * false reading. - *
- * The percent "%" character always has the reserved purpose of being - * the escape indicator, it must be escaped as "%25" in order to be used - * as data within a URI. - *
- * The unescape method is internally performed within this method. - * - * @param component the URI character sequence - * @param charset the protocol charset - * @return original character sequence - * @throws URIException incomplete trailing escape pattern or unsupported - * character encoding - */ - protected static String decode(char[] component, String charset) - throws URIException { - if (component == null) { - throw new IllegalArgumentException("Component array of chars may not be null"); - } - return decode(new String(component), charset); - } - /** - * Decodes URI encoded string. - * - * This is a two mapping, one from URI characters to octets, and - * subsequently a second from octets to original characters: - *
- * URI character sequence->octet sequence->original character sequence - *
- * - * A URI must be separated into its components before the escaped - * characters within those components can be allowedly decoded. - *
- * Notice that there is a chance that URI characters that are non UTF-8 - * may be parsed as valid UTF-8. A recent non-scientific analysis found - * that EUC encoded Japanese words had a 2.7% false reading; SJIS had a - * 0.0005% false reading; other encoding such as ASCII or KOI-8 have a 0% - * false reading. - *
- * The percent "%" character always has the reserved purpose of being - * the escape indicator, it must be escaped as "%25" in order to be used - * as data within a URI. - *
- * The unescape method is internally performed within this method. - * - * @param component the URI character sequence - * @param charset the protocol charset - * @return original character sequence - * @throws URIException incomplete trailing escape pattern or unsupported - * character encoding - * - * @since 3.0 - */ - protected static String decode(String component, String charset) - throws URIException { - if (component == null) { - throw new IllegalArgumentException("Component array of chars may not be null"); - } - byte[] rawdata = null; - try { - rawdata = URLCodec.decodeUrl(EncodingUtil.getAsciiBytes(component)); - } catch (DecoderException e) { - throw new URIException(e.getMessage()); - } - return EncodingUtil.getString(rawdata, charset); - } - /** - * Pre-validate the unescaped URI string within a specific component. - * - * @param component the component string within the component - * @param disallowed those characters disallowed within the component - * @return if true, it doesn't have the disallowed characters - * if false, the component is undefined or an incorrect one - */ - protected boolean prevalidate(String component, BitSet disallowed) { - // prevalidate the given component by disallowed characters - if (component == null) { - return false; // undefined - } - char[] target = component.toCharArray(); - for (int i = 0; i < target.length; i++) { - if (disallowed.get(target[i])) { - return false; - } - } - return true; - } - /** - * Validate the URI characters within a specific component. - * The component must be performed after escape encoding. Or it doesn't - * include escaped characters. - * - * @param component the characters sequence within the component - * @param generous those characters that are allowed within a component - * @return if true, it's the correct URI character sequence - */ - protected boolean validate(char[] component, BitSet generous) { - // validate each component by generous characters - return validate(component, 0, -1, generous); - } - /** - * Validate the URI characters within a specific component. - * The component must be performed after escape encoding. Or it doesn't - * include escaped characters. - *
- * It's not that much strict, generous. The strict validation might be
- * performed before being called this method.
- *
- * @param component the characters sequence within the component
- * @param soffset the starting offset of the given component
- * @param eoffset the ending offset of the given component
- * if -1, it means the length of the component
- * @param generous those characters that are allowed within a component
- * @return if true, it's the correct URI character sequence
- */
- protected boolean validate(char[] component, int soffset, int eoffset,
- BitSet generous) {
- // validate each component by generous characters
- if (eoffset == -1) {
- eoffset = component.length - 1;
- }
- for (int i = soffset; i <= eoffset; i++) {
- if (!generous.get(component[i])) {
- return false;
- }
- }
- return true;
- }
- /**
- * In order to avoid any possilbity of conflict with non-ASCII characters,
- * Parse a URI reference as a
String
with the character
- * encoding of the local system or the document.
- *
- * The following line is the regular expression for breaking-down a URI - * reference into its components. - *
- * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - * 12 3 4 5 6 7 8 9 - *
- * For example, matching the above expression to - * http://jakarta.apache.org/ietf/uri/#Related - * results in the following subexpression matches: - *
- * $1 = http: - * scheme = $2 = http - * $3 = //jakarta.apache.org - * authority = $4 = jakarta.apache.org - * path = $5 = /ietf/uri/ - * $6 =- * query = $7 = - * $8 = #Related - * fragment = $9 = Related - *
- *
- * @param original the original character sequence
- * @param escaped
true
if
original
is escaped
- * @throws URIException If an error occurs.
- */
- protected void parseUriReference(String original, boolean escaped)
- throws URIException {
- // validate and contruct the URI character sequence
- if (original == null) {
- throw new URIException("URI-Reference required");
- }
- /* @
- * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
- */
- String tmp = original.trim();
- /*
- * The length of the string sequence of characters.
- * It may not be equal to the length of the byte array.
- */
- int length = tmp.length();
- /*
- * Remove the delimiters like angle brackets around an URI.
- */
- if (length > 0) {
- char[] firstDelimiter = { tmp.charAt(0) };
- if (validate(firstDelimiter, delims)) {
- if (length >= 2) {
- char[] lastDelimiter = { tmp.charAt(length - 1) };
- if (validate(lastDelimiter, delims)) {
- tmp = tmp.substring(1, length - 1);
- length = length - 2;
- }
- }
- }
- }
- /*
- * The starting index
- */
- int from = 0;
- /*
- * The test flag whether the URI is started from the path component.
- */
- boolean isStartedFromPath = false;
- int atColon = tmp.indexOf(':');
- int atSlash = tmp.indexOf('/');
- if ((atColon <= 0 && !tmp.startsWith("//"))
- || (atSlash >= 0 && atSlash < atColon)) {
- isStartedFromPath = true;
- }
- /*
- *
- * @@@@@@@@ - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - *
- */ - int at = indexFirstOf(tmp, isStartedFromPath ? "/?#" : ":/?#", from); - if (at == -1) { - at = 0; - } - /* - * Parse the scheme. - *
- * scheme = $2 = http - * @ - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - *
- */ - if (at > 0 && at < length && tmp.charAt(at) == ':') { - char[] target = tmp.substring(0, at).toLowerCase().toCharArray(); - if (validate(target, scheme)) { - _scheme = target; - } else { - throw new URIException("incorrect scheme"); - } - from = ++at; - } - /* - * Parse the authority component. - *
- * authority = $4 = jakarta.apache.org - * @@ - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - *
- */ - // Reset flags - _is_net_path = _is_abs_path = _is_rel_path = _is_hier_part = false; - if (0 <= at && at < length && tmp.charAt(at) == '/') { - // Set flag - _is_hier_part = true; - if (at + 2 < length && tmp.charAt(at + 1) == '/' - && !isStartedFromPath) { - // the temporary index to start the search from - int next = indexFirstOf(tmp, "/?#", at + 2); - if (next == -1) { - next = (tmp.substring(at + 2).length() == 0) ? at + 2 - : tmp.length(); - } - parseAuthority(tmp.substring(at + 2, next), escaped); - from = at = next; - // Set flag - _is_net_path = true; - } - if (from == at) { - // Set flag - _is_abs_path = true; - } - } - /* - * Parse the path component. - *
- * path = $5 = /ietf/uri/ - * @@@@@@ - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - *
- */ - if (from < length) { - // rel_path = rel_segment [ abs_path ] - int next = indexFirstOf(tmp, "?#", from); - if (next == -1) { - next = tmp.length(); - } - if (!_is_abs_path) { - if (!escaped - && prevalidate(tmp.substring(from, next), disallowed_rel_path) - || escaped - && validate(tmp.substring(from, next).toCharArray(), rel_path)) { - // Set flag - _is_rel_path = true; - } else if (!escaped - && prevalidate(tmp.substring(from, next), disallowed_opaque_part) - || escaped - && validate(tmp.substring(from, next).toCharArray(), opaque_part)) { - // Set flag - _is_opaque_part = true; - } else { - // the path component may be empty - _path = null; - } - } - String s = tmp.substring(from, next); - if (escaped) { - setRawPath(s.toCharArray()); - } else { - setPath(s); - } - at = next; - } - // set the charset to do escape encoding - String charset = getProtocolCharset(); - /* - * Parse the query component. - *
- * query = $7 =- * @@@@@@@@@ - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - *
- */ - if (0 <= at && at + 1 < length && tmp.charAt(at) == '?') { - int next = tmp.indexOf('#', at + 1); - if (next == -1) { - next = tmp.length(); - } - if (escaped) { - _query = tmp.substring(at + 1, next).toCharArray(); - if (!validate(_query, uric)) { - throw new URIException("Invalid query"); - } - } else { - _query = encode(tmp.substring(at + 1, next), allowed_query, charset); - } - at = next; - } - /* - * Parse the fragment component. - *
- * fragment = $9 = Related - * @@@@@@@@ - * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? - *
- */
- if (0 <= at && at + 1 <= length && tmp.charAt(at) == '#') {
- if (at + 1 == length) { // empty fragment
- _fragment = "".toCharArray();
- } else {
- _fragment = (escaped) ? tmp.substring(at + 1).toCharArray()
- : encode(tmp.substring(at + 1), allowed_fragment, charset);
- }
- }
- // set this URI.
- setURI();
- }
- /**
- * Get the earlier index that to be searched for the first occurrance in
- * one of any of the given string.
- *
- * @param s the string to be indexed
- * @param delims the delimiters used to index
- * @return the earlier index if there are delimiters
- */
- protected int indexFirstOf(String s, String delims) {
- return indexFirstOf(s, delims, -1);
- }
- /**
- * Get the earlier index that to be searched for the first occurrance in
- * one of any of the given string.
- *
- * @param s the string to be indexed
- * @param delims the delimiters used to index
- * @param offset the from index
- * @return the earlier index if there are delimiters
- */
- protected int indexFirstOf(String s, String delims, int offset) {
- if (s == null || s.length() == 0) {
- return -1;
- }
- if (delims == null || delims.length() == 0) {
- return -1;
- }
- // check boundaries
- if (offset < 0) {
- offset = 0;
- } else if (offset > s.length()) {
- return -1;
- }
- // s is never null
- int min = s.length();
- char[] delim = delims.toCharArray();
- for (int i = 0; i < delim.length; i++) {
- int at = s.indexOf(delim[i], offset);
- if (at >= 0 && at < min) {
- min = at;
- }
- }
- return (min == s.length()) ? -1 : min;
- }
- /**
- * Get the earlier index that to be searched for the first occurrance in
- * one of any of the given array.
- *
- * @param s the character array to be indexed
- * @param delim the delimiter used to index
- * @return the ealier index if there are a delimiter
- */
- protected int indexFirstOf(char[] s, char delim) {
- return indexFirstOf(s, delim, 0);
- }
- /**
- * Get the earlier index that to be searched for the first occurrance in
- * one of any of the given array.
- *
- * @param s the character array to be indexed
- * @param delim the delimiter used to index
- * @param offset The offset.
- * @return the ealier index if there is a delimiter
- */
- protected int indexFirstOf(char[] s, char delim, int offset) {
- if (s == null || s.length == 0) {
- return -1;
- }
- // check boundaries
- if (offset < 0) {
- offset = 0;
- } else if (offset > s.length) {
- return -1;
- }
- for (int i = offset; i < s.length; i++) {
- if (s[i] == delim) {
- return i;
- }
- }
- return -1;
- }
- /**
- * Parse the authority component.
- *
- * @param original the original character sequence of authority component
- * @param escaped
true
if
original
is escaped
- * @throws URIException If an error occurs.
- */
- protected void parseAuthority(String original, boolean escaped)
- throws URIException {
- // Reset flags
- _is_reg_name = _is_server =
- _is_hostname = _is_IPv4address = _is_IPv6reference = false;
- // set the charset to do escape encoding
- String charset = getProtocolCharset();
- boolean hasPort = true;
- int from = 0;
- int next = original.indexOf('@');
- if (next != -1) { // neither -1 and 0
- // each protocol extented from URI supports the specific userinfo
- _userinfo = (escaped) ? original.substring(0, next).toCharArray()
- : encode(original.substring(0, next), allowed_userinfo,
- charset);
- from = next + 1;
- }
- next = original.indexOf('[', from);
- if (next >= from) {
- next = original.indexOf(']', from);
- if (next == -1) {
- throw new URIException(URIException.PARSING, "IPv6reference");
- } else {
- next++;
- }
- // In IPv6reference, '[', ']' should be excluded
- _host = (escaped) ? original.substring(from, next).toCharArray()
- : encode(original.substring(from, next), allowed_IPv6reference,
- charset);
- // Set flag
- _is_IPv6reference = true;
- } else { // only for !_is_IPv6reference
- next = original.indexOf(':', from);
- if (next == -1) {
- next = original.length();
- hasPort = false;
- }
- // REMINDME: it doesn't need the pre-validation
- _host = original.substring(from, next).toCharArray();
- if (validate(_host, IPv4address)) {
- // Set flag
- _is_IPv4address = true;
- } else if (validate(_host, hostname)) {
- // Set flag
- _is_hostname = true;
- } else {
- // Set flag
- _is_reg_name = true;
- }
- }
- if (_is_reg_name) {
- // Reset flags for a server-based naming authority
- _is_server = _is_hostname = _is_IPv4address =
- _is_IPv6reference = false;
- // set a registry-based naming authority
- if (escaped) {
- _authority = original.toCharArray();
- if (!validate(_authority, reg_name)) {
- throw new URIException("Invalid authority");
- }
- } else {
- _authority = encode(original, allowed_reg_name, charset);
- }
- } else {
- if (original.length() - 1 > next && hasPort
- && original.charAt(next) == ':') { // not empty
- from = next + 1;
- try {
- _port = Integer.parseInt(original.substring(from));
- } catch (NumberFormatException error) {
- throw new URIException(URIException.PARSING,
- "invalid port number");
- }
- }
- // set a server-based naming authority
- StringBuffer buf = new StringBuffer();
- if (_userinfo != null) { // has_userinfo
- buf.append(_userinfo);
- buf.append('@');
- }
- if (_host != null) {
- buf.append(_host);
- if (_port != -1) {
- buf.append(':');
- buf.append(_port);
- }
- }
- _authority = buf.toString().toCharArray();
- // Set flag
- _is_server = true;
- }
- }
- /**
- * Once it's parsed successfully, set this URI.
- *
- * @see #getRawURI
- */
- protected void setURI() {
- // set _uri
- StringBuffer buf = new StringBuffer();
- // ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
- if (_scheme != null) {
- buf.append(_scheme);
- buf.append(':');
- }
- if (_is_net_path) {
- buf.append("//");
- if (_authority != null) { // has_authority
- buf.append(_authority);
- }
- }
- if (_opaque != null && _is_opaque_part) {
- buf.append(_opaque);
- } else if (_path != null) {
- // _is_hier_part or _is_relativeURI
- if (_path.length != 0) {
- buf.append(_path);
- }
- }
- if (_query != null) { // has_query
- buf.append('?');
- buf.append(_query);
- }
- // ignore the fragment identifier
- _uri = buf.toString().toCharArray();
- hash = 0;
- }
- // ----------------------------------------------------------- Test methods
- /**
- * Tell whether or not this URI is absolute.
- *
- * @return true iif this URI is absoluteURI
- */
- public boolean isAbsoluteURI() {
- return (_scheme != null);
- }
- /**
- * Tell whether or not this URI is relative.
- *
- * @return true iif this URI is relativeURI
- */
- public boolean isRelativeURI() {
- return (_scheme == null);
- }
- /**
- * Tell whether or not the absoluteURI of this URI is hier_part.
- *
- * @return true iif the absoluteURI is hier_part
- */
- public boolean isHierPart() {
- return _is_hier_part;
- }
- /**
- * Tell whether or not the absoluteURI of this URI is opaque_part.
- *
- * @return true iif the absoluteURI is opaque_part
- */
- public boolean isOpaquePart() {
- return _is_opaque_part;
- }
- /**
- * Tell whether or not the relativeURI or heir_part of this URI is net_path.
- * It's the same function as the has_authority() method.
- *
- * @return true iif the relativeURI or heir_part is net_path
- * @see #hasAuthority
- */
- public boolean isNetPath() {
- return _is_net_path || (_authority != null);
- }
- /**
- * Tell whether or not the relativeURI or hier_part of this URI is abs_path.
- *
- * @return true iif the relativeURI or hier_part is abs_path
- */
- public boolean isAbsPath() {
- return _is_abs_path;
- }
- /**
- * Tell whether or not the relativeURI of this URI is rel_path.
- *
- * @return true iif the relativeURI is rel_path
- */
- public boolean isRelPath() {
- return _is_rel_path;
- }
- /**
- * Tell whether or not this URI has authority.
- * It's the same function as the is_net_path() method.
- *
- * @return true iif this URI has authority
- * @see #isNetPath
- */
- public boolean hasAuthority() {
- return (_authority != null) || _is_net_path;
- }
- /**
- * Tell whether or not the authority component of this URI is reg_name.
- *
- * @return true iif the authority component is reg_name
- */
- public boolean isRegName() {
- return _is_reg_name;
- }
- /**
- * Tell whether or not the authority component of this URI is server.
- *
- * @return true iif the authority component is server
- */
- public boolean isServer() {
- return _is_server;
- }
- /**
- * Tell whether or not this URI has userinfo.
- *
- * @return true iif this URI has userinfo
- */
- public boolean hasUserinfo() {
- return (_userinfo != null);
- }
- /**
- * Tell whether or not the host part of this URI is hostname.
- *
- * @return true iif the host part is hostname
- */
- public boolean isHostname() {
- return _is_hostname;
- }
- /**
- * Tell whether or not the host part of this URI is IPv4address.
- *
- * @return true iif the host part is IPv4address
- */
- public boolean isIPv4address() {
- return _is_IPv4address;
- }
- /**
- * Tell whether or not the host part of this URI is IPv6reference.
- *
- * @return true iif the host part is IPv6reference
- */
- public boolean isIPv6reference() {
- return _is_IPv6reference;
- }
- /**
- * Tell whether or not this URI has query.
- *
- * @return true iif this URI has query
- */
- public boolean hasQuery() {
- return (_query != null);
- }
- /**
- * Tell whether or not this URI has fragment.
- *
- * @return true iif this URI has fragment
- */
- public boolean hasFragment() {
- return (_fragment != null);
- }
- // ---------------------------------------------------------------- Charset
- /**
- * Set the default charset of the protocol.
- *
- * The character set used to store files SHALL remain a local decision and - * MAY depend on the capability of local operating systems. Prior to the - * exchange of URIs they SHOULD be converted into a ISO/IEC 10646 format - * and UTF-8 encoded. This approach, while allowing international exchange - * of URIs, will still allow backward compatibility with older systems - * because the code set positions for ASCII characters are identical to the - * one byte sequence in UTF-8. - *
- * An individual URI scheme may require a single charset, define a default - * charset, or provide a way to indicate the charset used. - * - *
- * Always all the time, the setter method is always succeeded and throws
- *
DefaultCharsetChanged
exception.
- *
- * So API programmer must follow the following way:
- *
- * import org.apache.util.URI$DefaultCharsetChanged;
- * .
- * .
- * .
- * try {
- * URI.setDefaultProtocolCharset("UTF-8");
- * } catch (DefaultCharsetChanged cc) {
- * // CASE 1: the exception could be ignored, when it is set by user
- * if (cc.getReasonCode() == DefaultCharsetChanged.PROTOCOL_CHARSET) {
- * // CASE 2: let user know the default protocol charset changed
- * } else {
- * // CASE 2: let user know the default document charset changed
- * }
- * }
- *
- *
- * The API programmer is responsible to set the correct charset.
- * And each application should remember its own charset to support.
- *
- * @param charset the default charset for each protocol
- * @throws DefaultCharsetChanged default charset changed
- */
- public static void setDefaultProtocolCharset(String charset)
- throws DefaultCharsetChanged {
- defaultProtocolCharset = charset;
- throw new DefaultCharsetChanged(DefaultCharsetChanged.PROTOCOL_CHARSET,
- "the default protocol charset changed");
- }
- /**
- * Get the default charset of the protocol.
- *
- * An individual URI scheme may require a single charset, define a default - * charset, or provide a way to indicate the charset used. - *
- * To work globally either requires support of a number of character sets - * and to be able to convert between them, or the use of a single preferred - * character set. - * For support of global compatibility it is STRONGLY RECOMMENDED that - * clients and servers use UTF-8 encoding when exchanging URIs. - * - * @return the default charset string - */ - public static String getDefaultProtocolCharset() { - return defaultProtocolCharset; - } - /** - * Get the protocol charset used by this current URI instance. - * It was set by the constructor for this instance. If it was not set by - * contructor, it will return the default protocol charset. - * - * @return the protocol charset string - * @see #getDefaultProtocolCharset - */ - public String getProtocolCharset() { - return (protocolCharset != null) - ? protocolCharset - : defaultProtocolCharset; - } - /** - * Set the default charset of the document. - *
- * Notice that it will be possible to contain mixed characters (e.g. - * ftp://host/KoreanNamespace/ChineseResource). To handle the Bi-directional - * display of these character sets, the protocol charset could be simply - * used again. Because it's not yet implemented that the insertion of BIDI - * control characters at different points during composition is extracted. - *
- *
- * Always all the time, the setter method is always succeeded and throws
- *
DefaultCharsetChanged
exception.
- *
- * So API programmer must follow the following way:
- *
- * import org.apache.util.URI$DefaultCharsetChanged;
- * .
- * .
- * .
- * try {
- * URI.setDefaultDocumentCharset("EUC-KR");
- * } catch (DefaultCharsetChanged cc) {
- * // CASE 1: the exception could be ignored, when it is set by user
- * if (cc.getReasonCode() == DefaultCharsetChanged.DOCUMENT_CHARSET) {
- * // CASE 2: let user know the default document charset changed
- * } else {
- * // CASE 2: let user know the default protocol charset changed
- * }
- * }
- *
- *
- * The API programmer is responsible to set the correct charset.
- * And each application should remember its own charset to support.
- *
- * @param charset the default charset for the document
- * @throws DefaultCharsetChanged default charset changed
- */
- public static void setDefaultDocumentCharset(String charset)
- throws DefaultCharsetChanged {
- defaultDocumentCharset = charset;
- throw new DefaultCharsetChanged(DefaultCharsetChanged.DOCUMENT_CHARSET,
- "the default document charset changed");
- }
- /**
- * Get the recommended default charset of the document.
- *
- * @return the default charset string
- */
- public static String getDefaultDocumentCharset() {
- return defaultDocumentCharset;
- }
- /**
- * Get the default charset of the document by locale.
- *
- * @return the default charset string by locale
- */
- public static String getDefaultDocumentCharsetByLocale() {
- return defaultDocumentCharsetByLocale;
- }
- /**
- * Get the default charset of the document by platform.
- *
- * @return the default charset string by platform
- */
- public static String getDefaultDocumentCharsetByPlatform() {
- return defaultDocumentCharsetByPlatform;
- }
- // ------------------------------------------------------------- The scheme
- /**
- * Get the scheme.
- *
- * @return the scheme
- */
- public char[] getRawScheme() {
- return _scheme;
- }
- /**
- * Get the scheme.
- *
- * @return the scheme
- * null if undefined scheme
- */
- public String getScheme() {
- return (_scheme == null) ? null : new String(_scheme);
- }
- // ---------------------------------------------------------- The authority
- /**
- * Set the authority. It can be one type of server, hostport, hostname,
- * IPv4address, IPv6reference and reg_name.
- *
- * authority = server | reg_name - *
- * - * @param escapedAuthority the raw escaped authority - * @throws URIException If {@link - * #parseAuthority(java.lang.String,boolean)} fails - * @throws NullPointerException null authority - */ - public void setRawAuthority(char[] escapedAuthority) - throws URIException, NullPointerException { - parseAuthority(new String(escapedAuthority), true); - setURI(); - } - /** - * Set the authority. It can be one type of server, hostport, hostname, - * IPv4address, IPv6reference and reg_name. - * Note that there is no setAuthority method by the escape encoding reason. - * - * @param escapedAuthority the escaped authority string - * @throws URIException If {@link - * #parseAuthority(java.lang.String,boolean)} fails - */ - public void setEscapedAuthority(String escapedAuthority) - throws URIException { - parseAuthority(escapedAuthority, true); - setURI(); - } - /** - * Get the raw-escaped authority. - * - * @return the raw-escaped authority - */ - public char[] getRawAuthority() { - return _authority; - } - /** - * Get the escaped authority. - * - * @return the escaped authority - */ - public String getEscapedAuthority() { - return (_authority == null) ? null : new String(_authority); - } - /** - * Get the authority. - * - * @return the authority - * @throws URIException If {@link #decode} fails - */ - public String getAuthority() throws URIException { - return (_authority == null) ? null : decode(_authority, - getProtocolCharset()); - } - // ----------------------------------------------------------- The userinfo - /** - * Get the raw-escaped userinfo. - * - * @return the raw-escaped userinfo - * @see #getAuthority - */ - public char[] getRawUserinfo() { - return _userinfo; - } - /** - * Get the escaped userinfo. - * - * @return the escaped userinfo - * @see #getAuthority - */ - public String getEscapedUserinfo() { - return (_userinfo == null) ? null : new String(_userinfo); - } - /** - * Get the userinfo. - * - * @return the userinfo - * @throws URIException If {@link #decode} fails - * @see #getAuthority - */ - public String getUserinfo() throws URIException { - return (_userinfo == null) ? null : decode(_userinfo, - getProtocolCharset()); - } - // --------------------------------------------------------------- The host - /** - * Get the host. - *
- * host = hostname | IPv4address | IPv6reference - *
- * - * @return the host - * @see #getAuthority - */ - public char[] getRawHost() { - return _host; - } - /** - * Get the host. - *
- * host = hostname | IPv4address | IPv6reference - *
- * - * @return the host - * @throws URIException If {@link #decode} fails - * @see #getAuthority - */ - public String getHost() throws URIException { - if (_host != null) { - return decode(_host, getProtocolCharset()); - } else { - return null; - } - } - // --------------------------------------------------------------- The port - /** - * Get the port. In order to get the specfic default port, the specific - * protocol-supported class extended from the URI class should be used. - * It has the server-based naming authority. - * - * @return the port - * if -1, it has the default port for the scheme or the server-based - * naming authority is not supported in the specific URI. - */ - public int getPort() { - return _port; - } - // --------------------------------------------------------------- The path - /** - * Set the raw-escaped path. - * - * @param escapedPath the path character sequence - * @throws URIException encoding error or not proper for initial instance - * @see #encode - */ - public void setRawPath(char[] escapedPath) throws URIException { - if (escapedPath == null || escapedPath.length == 0) { - _path = _opaque = escapedPath; - setURI(); - return; - } - // remove the fragment identifier - escapedPath = removeFragmentIdentifier(escapedPath); - if (_is_net_path || _is_abs_path) { - if (escapedPath[0] != '/') { - throw new URIException(URIException.PARSING, - "not absolute path"); - } - if (!validate(escapedPath, abs_path)) { - throw new URIException(URIException.ESCAPING, - "escaped absolute path not valid"); - } - _path = escapedPath; - } else if (_is_rel_path) { - int at = indexFirstOf(escapedPath, '/'); - if (at == 0) { - throw new URIException(URIException.PARSING, "incorrect path"); - } - if (at > 0 && !validate(escapedPath, 0, at - 1, rel_segment) - && !validate(escapedPath, at, -1, abs_path) - || at < 0 && !validate(escapedPath, 0, -1, rel_segment)) { - throw new URIException(URIException.ESCAPING, - "escaped relative path not valid"); - } - _path = escapedPath; - } else if (_is_opaque_part) { - if (!uric_no_slash.get(escapedPath[0]) - && !validate(escapedPath, 1, -1, uric)) { - throw new URIException(URIException.ESCAPING, - "escaped opaque part not valid"); - } - _opaque = escapedPath; - } else { - throw new URIException(URIException.PARSING, "incorrect path"); - } - setURI(); - } - /** - * Set the escaped path. - * - * @param escapedPath the escaped path string - * @throws URIException encoding error or not proper for initial instance - * @see #encode - */ - public void setEscapedPath(String escapedPath) throws URIException { - if (escapedPath == null) { - _path = _opaque = null; - setURI(); - return; - } - setRawPath(escapedPath.toCharArray()); - } - /** - * Set the path. - * - * @param path the path string - * @throws URIException set incorrectly or fragment only - * @see #encode - */ - public void setPath(String path) throws URIException { - if (path == null || path.length() == 0) { - _path = _opaque = (path == null) ? null : path.toCharArray(); - setURI(); - return; - } - // set the charset to do escape encoding - String charset = getProtocolCharset(); - if (_is_net_path || _is_abs_path) { - _path = encode(path, allowed_abs_path, charset); - } else if (_is_rel_path) { - StringBuffer buff = new StringBuffer(path.length()); - int at = path.indexOf('/'); - if (at == 0) { // never 0 - throw new URIException(URIException.PARSING, - "incorrect relative path"); - } - if (at > 0) { - buff.append(encode(path.substring(0, at), allowed_rel_path, - charset)); - buff.append(encode(path.substring(at), allowed_abs_path, - charset)); - } else { - buff.append(encode(path, allowed_rel_path, charset)); - } - _path = buff.toString().toCharArray(); - } else if (_is_opaque_part) { - StringBuffer buf = new StringBuffer(); - buf.insert(0, encode(path.substring(0, 1), uric_no_slash, charset)); - buf.insert(1, encode(path.substring(1), uric, charset)); - _opaque = buf.toString().toCharArray(); - } else { - throw new URIException(URIException.PARSING, "incorrect path"); - } - setURI(); - } - /** - * Resolve the base and relative path. - * - * @param basePath a character array of the basePath - * @param relPath a character array of the relPath - * @return the resolved path - * @throws URIException no more higher path level to be resolved - */ - protected char[] resolvePath(char[] basePath, char[] relPath) - throws URIException { - // REMINDME: paths are never null - String base = (basePath == null) ? "" : new String(basePath); - // _path could be empty - if (relPath == null || relPath.length == 0) { - return normalize(basePath); - } else if (relPath[0] == '/') { - return normalize(relPath); - } else { - int at = base.lastIndexOf('/'); - if (at != -1) { - basePath = base.substring(0, at + 1).toCharArray(); - } - StringBuffer buff = new StringBuffer(base.length() - + relPath.length); - buff.append((at != -1) ? base.substring(0, at + 1) : "/"); - buff.append(relPath); - return normalize(buff.toString().toCharArray()); - } - } - /** - * Get the raw-escaped current hierarchy level in the given path. - * If the last namespace is a collection, the slash mark ('/') should be - * ended with at the last character of the path string. - * - * @param path the path - * @return the current hierarchy level - * @throws URIException no hierarchy level - */ - protected char[] getRawCurrentHierPath(char[] path) throws URIException { - if (_is_opaque_part) { - throw new URIException(URIException.PARSING, "no hierarchy level"); - } - if (path == null) { - throw new URIException(URIException.PARSING, "empty path"); - } - String buff = new String(path); - int first = buff.indexOf('/'); - int last = buff.lastIndexOf('/'); - if (last == 0) { - return rootPath; - } else if (first != last && last != -1) { - return buff.substring(0, last).toCharArray(); - } - // FIXME: it could be a document on the server side - return path; - } - /** - * Get the raw-escaped current hierarchy level. - * - * @return the raw-escaped current hierarchy level - * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. - */ - public char[] getRawCurrentHierPath() throws URIException { - return (_path == null) ? null : getRawCurrentHierPath(_path); - } - /** - * Get the escaped current hierarchy level. - * - * @return the escaped current hierarchy level - * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. - */ - public String getEscapedCurrentHierPath() throws URIException { - char[] path = getRawCurrentHierPath(); - return (path == null) ? null : new String(path); - } - /** - * Get the current hierarchy level. - * - * @return the current hierarchy level - * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. - * @see #decode - */ - public String getCurrentHierPath() throws URIException { - char[] path = getRawCurrentHierPath(); - return (path == null) ? null : decode(path, getProtocolCharset()); - } - /** - * Get the level above the this hierarchy level. - * - * @return the raw above hierarchy level - * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. - */ - public char[] getRawAboveHierPath() throws URIException { - char[] path = getRawCurrentHierPath(); - return (path == null) ? null : getRawCurrentHierPath(path); - } - /** - * Get the level above the this hierarchy level. - * - * @return the raw above hierarchy level - * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. - */ - public String getEscapedAboveHierPath() throws URIException { - char[] path = getRawAboveHierPath(); - return (path == null) ? null : new String(path); - } - /** - * Get the level above the this hierarchy level. - * - * @return the above hierarchy level - * @throws URIException If {@link #getRawCurrentHierPath(char[])} fails. - * @see #decode - */ - public String getAboveHierPath() throws URIException { - char[] path = getRawAboveHierPath(); - return (path == null) ? null : decode(path, getProtocolCharset()); - } - /** - * Get the raw-escaped path. - *
- * path = [ abs_path | opaque_part ] - *
- * - * @return the raw-escaped path - */ - public char[] getRawPath() { - return _is_opaque_part ? _opaque : _path; - } - /** - * Get the escaped path. - *
- * path = [ abs_path | opaque_part ] - * abs_path = "/" path_segments - * opaque_part = uric_no_slash *uric - *
- * - * @return the escaped path string - */ - public String getEscapedPath() { - char[] path = getRawPath(); - return (path == null) ? null : new String(path); - } - /** - * Get the path. - *
- * path = [ abs_path | opaque_part ] - *
- * @return the path string - * @throws URIException If {@link #decode} fails. - * @see #decode - */ - public String getPath() throws URIException { - char[] path = getRawPath(); - return (path == null) ? null : decode(path, getProtocolCharset()); - } - /** - * Get the raw-escaped basename of the path. - * - * @return the raw-escaped basename - */ - public char[] getRawName() { - if (_path == null) { - return null; - } - int at = 0; - for (int i = _path.length - 1; i >= 0; i--) { - if (_path[i] == '/') { - at = i + 1; - break; - } - } - int len = _path.length - at; - char[] basename = new char[len]; - System.arraycopy(_path, at, basename, 0, len); - return basename; - } - /** - * Get the escaped basename of the path. - * - * @return the escaped basename string - */ - public String getEscapedName() { - char[] basename = getRawName(); - return (basename == null) ? null : new String(basename); - } - /** - * Get the basename of the path. - * - * @return the basename string - * @throws URIException incomplete trailing escape pattern or unsupported - * character encoding - * @see #decode - */ - public String getName() throws URIException { - char[] basename = getRawName(); - return (basename == null) ? null : decode(getRawName(), - getProtocolCharset()); - } - // ----------------------------------------------------- The path and query - /** - * Get the raw-escaped path and query. - * - * @return the raw-escaped path and query - */ - public char[] getRawPathQuery() { - if (_path == null && _query == null) { - return null; - } - StringBuffer buff = new StringBuffer(); - if (_path != null) { - buff.append(_path); - } - if (_query != null) { - buff.append('?'); - buff.append(_query); - } - return buff.toString().toCharArray(); - } - /** - * Get the escaped query. - * - * @return the escaped path and query string - */ - public String getEscapedPathQuery() { - char[] rawPathQuery = getRawPathQuery(); - return (rawPathQuery == null) ? null : new String(rawPathQuery); - } - /** - * Get the path and query. - * - * @return the path and query string. - * @throws URIException incomplete trailing escape pattern or unsupported - * character encoding - * @see #decode - */ - public String getPathQuery() throws URIException { - char[] rawPathQuery = getRawPathQuery(); - return (rawPathQuery == null) ? null : decode(rawPathQuery, - getProtocolCharset()); - } - // -------------------------------------------------------------- The query - /** - * Set the raw-escaped query. - * - * @param escapedQuery the raw-escaped query - * @throws URIException escaped query not valid - */ - public void setRawQuery(char[] escapedQuery) throws URIException { - if (escapedQuery == null || escapedQuery.length == 0) { - _query = escapedQuery; - setURI(); - return; - } - // remove the fragment identifier - escapedQuery = removeFragmentIdentifier(escapedQuery); - if (!validate(escapedQuery, query)) { - throw new URIException(URIException.ESCAPING, - "escaped query not valid"); - } - _query = escapedQuery; - setURI(); - } - /** - * Set the escaped query string. - * - * @param escapedQuery the escaped query string - * @throws URIException escaped query not valid - */ - public void setEscapedQuery(String escapedQuery) throws URIException { - if (escapedQuery == null) { - _query = null; - setURI(); - return; - } - setRawQuery(escapedQuery.toCharArray()); - } - /** - * Set the query. - *
- * When a query string is not misunderstood the reserved special characters - * ("&", "=", "+", ",", and "$") within a query component, it is - * recommended to use in encoding the whole query with this method. - *
- * The additional APIs for the special purpose using by the reserved
- * special characters used in each protocol are implemented in each protocol
- * classes inherited from
URI
. So refer to the same-named APIs
- * implemented in each specific protocol instance.
- *
- * @param query the query string.
- * @throws URIException incomplete trailing escape pattern or unsupported
- * character encoding
- * @see #encode
- */
- public void setQuery(String query) throws URIException {
- if (query == null || query.length() == 0) {
- _query = (query == null) ? null : query.toCharArray();
- setURI();
- return;
- }
- setRawQuery(encode(query, allowed_query, getProtocolCharset()));
- }
- /**
- * Get the raw-escaped query.
- *
- * @return the raw-escaped query
- */
- public char[] getRawQuery() {
- return _query;
- }
- /**
- * Get the escaped query.
- *
- * @return the escaped query string
- */
- public String getEscapedQuery() {
- return (_query == null) ? null : new String(_query);
- }
- /**
- * Get the query.
- *
- * @return the query string.
- * @throws URIException incomplete trailing escape pattern or unsupported
- * character encoding
- * @see #decode
- */
- public String getQuery() throws URIException {
- return (_query == null) ? null : decode(_query, getProtocolCharset());
- }
- // ----------------------------------------------------------- The fragment
- /**
- * Set the raw-escaped fragment.
- *
- * @param escapedFragment the raw-escaped fragment
- * @throws URIException escaped fragment not valid
- */
- public void setRawFragment(char[] escapedFragment) throws URIException {
- if (escapedFragment == null || escapedFragment.length == 0) {
- _fragment = escapedFragment;
- hash = 0;
- return;
- }
- if (!validate(escapedFragment, fragment)) {
- throw new URIException(URIException.ESCAPING,
- "escaped fragment not valid");
- }
- _fragment = escapedFragment;
- hash = 0;
- }
- /**
- * Set the escaped fragment string.
- *
- * @param escapedFragment the escaped fragment string
- * @throws URIException escaped fragment not valid
- */
- public void setEscapedFragment(String escapedFragment) throws URIException {
- if (escapedFragment == null) {
- _fragment = null;
- hash = 0;
- return;
- }
- setRawFragment(escapedFragment.toCharArray());
- }
- /**
- * Set the fragment.
- *
- * @param fragment the fragment string.
- * @throws URIException If an error occurs.
- */
- public void setFragment(String fragment) throws URIException {
- if (fragment == null || fragment.length() == 0) {
- _fragment = (fragment == null) ? null : fragment.toCharArray();
- hash = 0;
- return;
- }
- _fragment = encode(fragment, allowed_fragment, getProtocolCharset());
- hash = 0;
- }
- /**
- * Get the raw-escaped fragment.
- *
- * The optional fragment identifier is not part of a URI, but is often used - * in conjunction with a URI. - *
- * The format and interpretation of fragment identifiers is dependent on - * the media type [RFC2046] of the retrieval result. - *
- * A fragment identifier is only meaningful when a URI reference is - * intended for retrieval and the result of that retrieval is a document - * for which the identified fragment is consistently defined. - * - * @return the raw-escaped fragment - */ - public char[] getRawFragment() { - return _fragment; - } - /** - * Get the escaped fragment. - * - * @return the escaped fragment string - */ - public String getEscapedFragment() { - return (_fragment == null) ? null : new String(_fragment); - } - /** - * Get the fragment. - * - * @return the fragment string - * @throws URIException incomplete trailing escape pattern or unsupported - * character encoding - * @see #decode - */ - public String getFragment() throws URIException { - return (_fragment == null) ? null : decode(_fragment, - getProtocolCharset()); - } - // ------------------------------------------------------------- Utilities - /** - * Remove the fragment identifier of the given component. - * - * @param component the component that a fragment may be included - * @return the component that the fragment identifier is removed - */ - protected char[] removeFragmentIdentifier(char[] component) { - if (component == null) { - return null; - } - int lastIndex = new String(component).indexOf('#'); - if (lastIndex != -1) { - component = new String(component).substring(0, - lastIndex).toCharArray(); - } - return component; - } - /** - * Normalize the given hier path part. - * - *
Algorithm taken from URI reference parser at
- * http://www.apache.org/~fielding/uri/rev-2002/issues.html.
- *
- * @param path the path to normalize
- * @return the normalized path
- * @throws URIException no more higher path level to be normalized
- */
- protected char[] normalize(char[] path) throws URIException {
- if (path == null) {
- return null;
- }
- String normalized = new String(path);
- // If the buffer begins with "./" or "../", the "." or ".." is removed.
- if (normalized.startsWith("./")) {
- normalized = normalized.substring(1);
- } else if (normalized.startsWith("../")) {
- normalized = normalized.substring(2);
- } else if (normalized.startsWith("..")) {
- normalized = normalized.substring(2);
- }
- // All occurrences of "/./" in the buffer are replaced with "/"
- int index = -1;
- while ((index = normalized.indexOf("/./")) != -1) {
- normalized = normalized.substring(0, index) + normalized.substring(index + 2);
- }
- // If the buffer ends with "/.", the "." is removed.
- if (normalized.endsWith("/.")) {
- normalized = normalized.substring(0, normalized.length() - 1);
- }
- int startIndex = 0;
- // All occurrences of "/
String
.
- *
- * To copy the identical
URI
object including the userinfo
- * component, it should be used.
- *
- * @return a clone of this instance
- */
- public synchronized Object clone() throws CloneNotSupportedException {
- URI instance = (URI) super.clone();
- instance._uri = _uri;
- instance._scheme = _scheme;
- instance._opaque = _opaque;
- instance._authority = _authority;
- instance._userinfo = _userinfo;
- instance._host = _host;
- instance._port = _port;
- instance._path = _path;
- instance._query = _query;
- instance._fragment = _fragment;
- // the charset to do escape encoding for this instance
- instance.protocolCharset = protocolCharset;
- // flags
- instance._is_hier_part = _is_hier_part;
- instance._is_opaque_part = _is_opaque_part;
- instance._is_net_path = _is_net_path;
- instance._is_abs_path = _is_abs_path;
- instance._is_rel_path = _is_rel_path;
- instance._is_reg_name = _is_reg_name;
- instance._is_server = _is_server;
- instance._is_hostname = _is_hostname;
- instance._is_IPv4address = _is_IPv4address;
- instance._is_IPv6reference = _is_IPv6reference;
- return instance;
- }
- // ------------------------------------------------------------ Get the URI
- /**
- * It can be gotten the URI character sequence. It's raw-escaped.
- * For the purpose of the protocol to be transported, it will be useful.
- *
- * It is clearly unwise to use a URL that contains a password which is - * intended to be secret. In particular, the use of a password within - * the 'userinfo' component of a URL is strongly disrecommended except - * in those rare cases where the 'password' parameter is intended to be - * public. - *
- * When you want to get each part of the userinfo, you need to use the - * specific methods in the specific URL. It depends on the specific URL. - * - * @return the URI character sequence - */ - public char[] getRawURI() { - return _uri; - } - /** - * It can be gotten the URI character sequence. It's escaped. - * For the purpose of the protocol to be transported, it will be useful. - * - * @return the escaped URI string - */ - public String getEscapedURI() { - return (_uri == null) ? null : new String(_uri); - } - /** - * It can be gotten the URI character sequence. - * - * @return the original URI string - * @throws URIException incomplete trailing escape pattern or unsupported - * character encoding - * @see #decode - */ - public String getURI() throws URIException { - return (_uri == null) ? null : decode(_uri, getProtocolCharset()); - } - /** - * Get the URI reference character sequence. - * - * @return the URI reference character sequence - */ - public char[] getRawURIReference() { - if (_fragment == null) { - return _uri; - } - if (_uri == null) { - return _fragment; - } - // if _uri != null && _fragment != null - String uriReference = new String(_uri) + "#" + new String(_fragment); - return uriReference.toCharArray(); - } - /** - * Get the escaped URI reference string. - * - * @return the escaped URI reference string - */ - public String getEscapedURIReference() { - char[] uriReference = getRawURIReference(); - return (uriReference == null) ? null : new String(uriReference); - } - /** - * Get the original URI reference string. - * - * @return the original URI reference string - * @throws URIException If {@link #decode} fails. - */ - public String getURIReference() throws URIException { - char[] uriReference = getRawURIReference(); - return (uriReference == null) ? null : decode(uriReference, - getProtocolCharset()); - } - /** - * Get the escaped URI string. - *
- * On the document, the URI-reference form is only used without the userinfo - * component like http://jakarta.apache.org/ by the security reason. - * But the URI-reference form with the userinfo component could be parsed. - *
- * In other words, this URI and any its subclasses must not expose the
- * URI-reference expression with the userinfo component like
- * http://user:password@hostport/restricted_zone.
- * It means that the API client programmer should extract each user and
- * password to access manually. Probably it will be supported in the each
- * subclass, however, not a whole URI-reference expression.
- *
- * @return the escaped URI string
- * @see #clone()
- */
- public String toString() {
- return getEscapedURI();
- }
- // ------------------------------------------------------------ Inner class
- /**
- * The charset-changed normal operation to represent to be required to
- * alert to user the fact the default charset is changed.
- */
- public static class DefaultCharsetChanged extends RuntimeException {
- // ------------------------------------------------------- constructors
- /**
- * The constructor with a reason string and its code arguments.
- *
- * @param reasonCode the reason code
- * @param reason the reason
- */
- public DefaultCharsetChanged(int reasonCode, String reason) {
- super(reason);
- this.reason = reason;
- this.reasonCode = reasonCode;
- }
- // ---------------------------------------------------------- constants
- /** No specified reason code. */
- public static final int UNKNOWN = 0;
- /** Protocol charset changed. */
- public static final int PROTOCOL_CHARSET = 1;
- /** Document charset changed. */
- public static final int DOCUMENT_CHARSET = 2;
- // ------------------------------------------------- instance variables
- /** The reason code. */
- private int reasonCode;
- /** The reason message. */
- private String reason;
- // ------------------------------------------------------------ methods
- /**
- * Get the reason code.
- *
- * @return the reason code
- */
- public int getReasonCode() {
- return reasonCode;
- }
- /**
- * Get the reason message.
- *
- * @return the reason message
- */
- public String getReason() {
- return reason;
- }
- }
- /**
- * A mapping to determine the (somewhat arbitrarily) preferred charset for a
- * given locale. Supports all locales recognized in JDK 1.1.
- *
- * The distribution of this class is Servlets.com. It was originally
- * written by Jason Hunter [jhunter at acm.org] and used by with permission.
- */
- public static class LocaleToCharsetMap {
- /** A mapping of language code to charset */
- private static final Hashtable LOCALE_TO_CHARSET_MAP;
- static {
- LOCALE_TO_CHARSET_MAP = new Hashtable();
- LOCALE_TO_CHARSET_MAP.put("ar", "ISO-8859-6");
- LOCALE_TO_CHARSET_MAP.put("be", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("bg", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("ca", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("cs", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("da", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("de", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("el", "ISO-8859-7");
- LOCALE_TO_CHARSET_MAP.put("en", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("es", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("et", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("fi", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("fr", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("hr", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("hu", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("is", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("it", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("iw", "ISO-8859-8");
- LOCALE_TO_CHARSET_MAP.put("ja", "Shift_JIS");
- LOCALE_TO_CHARSET_MAP.put("ko", "EUC-KR");
- LOCALE_TO_CHARSET_MAP.put("lt", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("lv", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("mk", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("nl", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("no", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("pl", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("pt", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("ro", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("ru", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("sh", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("sk", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("sl", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("sq", "ISO-8859-2");
- LOCALE_TO_CHARSET_MAP.put("sr", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("sv", "ISO-8859-1");
- LOCALE_TO_CHARSET_MAP.put("tr", "ISO-8859-9");
- LOCALE_TO_CHARSET_MAP.put("uk", "ISO-8859-5");
- LOCALE_TO_CHARSET_MAP.put("zh", "GB2312");
- LOCALE_TO_CHARSET_MAP.put("zh_TW", "Big5");
- }
- /**
- * Get the preferred charset for the given locale.
- *
- * @param locale the locale
- * @return the preferred charset or null if the locale is not
- * recognized.
- */
- public static String getCharset(Locale locale) {
- // try for an full name match (may include country)
- String charset =
- (String) LOCALE_TO_CHARSET_MAP.get(locale.toString());
- if (charset != null) {
- return charset;
- }
- // if a full name didn't match, try just the language
- charset = (String) LOCALE_TO_CHARSET_MAP.get(locale.getLanguage());
- return charset; // may be null
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/URIException.java b/clients/java/src/org/apache/commons/httpclient/URIException.java
deleted file mode 100644
index 1aa537b..0000000
--- a/clients/java/src/org/apache/commons/httpclient/URIException.java
+++ /dev/null
@@ -1,178 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/URIException.java,v 1.12 2004/09/30 18:53:20 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
Username and password {@link Credentials}.
- * @author Remy Maucherat - * @author Sean C. Sullivan - * @author Mike Bowler - * @author Oleg Kalnichevski - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ -public class UsernamePasswordCredentials implements Credentials { - // ----------------------------------------------------------- Constructors - /** - * Default constructor. - * - * @deprecated Do not use. Null user name no longer allowed - */ - public UsernamePasswordCredentials() { - super(); - } - /** - * The constructor with the username and password combined string argument. - * - * @param usernamePassword the username:password formed string - * @see #toString - */ - public UsernamePasswordCredentials(String usernamePassword) { - super(); - if (usernamePassword == null) { - throw new IllegalArgumentException("Username:password string may not be null"); - } - int atColon = usernamePassword.indexOf(':'); - if (atColon >= 0) { - this.userName = usernamePassword.substring(0, atColon); - this.password = usernamePassword.substring(atColon + 1); - } else { - this.userName = usernamePassword; - } - } - /** - * The constructor with the username and password arguments. - * - * @param userName the user name - * @param password the password - */ - public UsernamePasswordCredentials(String userName, String password) { - super(); - if (userName == null) { - throw new IllegalArgumentException("Username may not be null"); - } - this.userName = userName; - this.password = password; - } - // ----------------------------------------------------- Instance Variables - /** - * User name. - */ - private String userName; - /** - * Password. - */ - private String password; - // ------------------------------------------------------------- Properties - /** - * User name property setter. User name may not be null. - * - * @param userName - * @see #getUserName() - * - * @deprecated Do not use. The UsernamePasswordCredentials objects should be immutable - */ - public void setUserName(String userName) { - if (userName == null) { - throw new IllegalArgumentException("Username may not be null"); - } - this.userName = userName; - } - /** - * User name property getter. - * - * @return the userName - * @see #setUserName(String) - */ - public String getUserName() { - return userName; - } - /** - * Password property setter. - * - * @param password - * @see #getPassword() - * - * @deprecated Do not use. The UsernamePasswordCredentials objects should be immutable - */ - public void setPassword(String password) { - this.password = password; - } - /** - * Password property getter. - * - * @return the password - * @see #setPassword(String) - */ - public String getPassword() { - return password; - } - /** - * Get this object string. - * - * @return the username:password formed string - */ - public String toString() { - StringBuffer result = new StringBuffer(); - result.append(this.userName); - result.append(":"); - result.append((this.password == null) ? "null" : this.password); - return result.toString(); - } - /** - * Does a hash of both user name and password. - * - * @return The hash code including user name and password. - */ - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.userName); - hash = LangUtils.hashCode(hash, this.password); - return hash; - } - /** - * These credentials are assumed equal if the username and password are the - * same. - * - * @param o The other object to compare with. - * - * @return
true
if the object is equivalent.
- */
- public boolean equals(Object o) {
- if (o == null) return false;
- if (this == o) return true;
- // note - to allow for sub-classing, this checks that class is the same
- // rather than do "instanceof".
- if (this.getClass().equals(o.getClass())) {
- UsernamePasswordCredentials that = (UsernamePasswordCredentials) o;
- if (LangUtils.equals(this.userName, that.userName)
- && LangUtils.equals(this.password, that.password) ) {
- return true;
- }
- }
- return false;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/Wire.java b/clients/java/src/org/apache/commons/httpclient/Wire.java
deleted file mode 100644
index 6fe7139..0000000
--- a/clients/java/src/org/apache/commons/httpclient/Wire.java
+++ /dev/null
@@ -1,166 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/Wire.java,v 1.9 2004/06/24 21:39:52 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
The following specifications are provided: - *
- * If several schemes are returned in the WWW-Authenticate - * or Proxy-Authenticate header, this parameter defines which - * {@link AuthScheme authentication schemes} takes precedence over others. - * The first item in the collection represents the most preferred - * {@link AuthScheme authentication scheme}, the last item represents the ID - * of the least preferred one. - *
- * - * @see org.apache.commons.httpclient.params.DefaultHttpParams - */ - public static final String AUTH_SCHEME_PRIORITY = "http.auth.scheme-priority"; - /** - * The NTLM scheme is a proprietary Microsoft Windows Authentication - * protocol (considered to be the most secure among currently supported - * authentication schemes). - */ - public static final String NTLM = "NTLM"; - /** - * Digest authentication scheme as defined in RFC2617. - */ - public static final String DIGEST = "Digest"; - /** - * Basic authentication scheme as defined in RFC2617 (considered inherently - * insecure, but most widely supported) - */ - public static final String BASIC = "Basic"; - static { - AuthPolicy.registerAuthScheme(NTLM, NTLMScheme.class); - AuthPolicy.registerAuthScheme(DIGEST, DigestScheme.class); - AuthPolicy.registerAuthScheme(BASIC, BasicScheme.class); - } - /** Log object. */ - protected static final Log LOG = LogFactory.getLog(AuthPolicy.class); - /** - * Registers a class implementing an {@link AuthScheme authentication scheme} with - * the given identifier. If a class with the given ID already exists it will be overridden. - * This ID is the same one used to retrieve the {@link AuthScheme authentication scheme} - * from {@link #getAuthScheme(String)}. - * - *- * Please note that custom authentication preferences, if used, need to be updated accordingly - * for the new {@link AuthScheme authentication scheme} to take effect. - *
- * - * @param id the identifier for this scheme - * @param clazz the class to register - * - * @see #getAuthScheme(String) - * @see #AUTH_SCHEME_PRIORITY - */ - public static synchronized void registerAuthScheme(final String id, Class clazz) { - if (id == null) { - throw new IllegalArgumentException("Id may not be null"); - } - if (clazz == null) { - throw new IllegalArgumentException("Authentication scheme class may not be null"); - } - SCHEMES.put(id.toLowerCase(), clazz); - SCHEME_LIST.add(id.toLowerCase()); - } - /** - * Unregisters the class implementing an {@link AuthScheme authentication scheme} with - * the given ID. - * - * @param id the ID of the class to unregister - */ - public static synchronized void unregisterAuthScheme(final String id) { - if (id == null) { - throw new IllegalArgumentException("Id may not be null"); - } - SCHEMES.remove(id.toLowerCase()); - SCHEME_LIST.remove(id.toLowerCase()); - } - /** - * Gets the {@link AuthScheme authentication scheme} with the given ID. - * - * @param id the {@link AuthScheme authentication scheme} ID - * - * @return {@link AuthScheme authentication scheme} - * - * @throws IllegalStateException if a scheme with the ID cannot be found - */ - public static synchronized AuthScheme getAuthScheme(final String id) - throws IllegalStateException { - if (id == null) { - throw new IllegalArgumentException("Id may not be null"); - } - Class clazz = (Class)SCHEMES.get(id.toLowerCase()); - if (clazz != null) { - try { - return (AuthScheme)clazz.newInstance(); - } catch (Exception e) { - LOG.error("Error initializing authentication scheme: " + id, e); - throw new IllegalStateException(id + - " authentication scheme implemented by " + - clazz.getName() + " could not be initialized"); - } - } else { - throw new IllegalStateException("Unsupported authentication scheme " + id); - } - } - /** - * Returns a list containing all registered {@link AuthScheme authentication - * schemes} in their default order. - * - * @return {@link AuthScheme authentication scheme} - */ - public static synchronized List getDefaultAuthPrefs() { - return (List)SCHEME_LIST.clone(); - } diff --git a/clients/java/src/org/apache/commons/httpclient/auth/AuthScheme.java b/clients/java/src/org/apache/commons/httpclient/auth/AuthScheme.java deleted file mode 100644 index 945d67b..0000000 --- a/clients/java/src/org/apache/commons/httpclient/auth/AuthScheme.java +++ /dev/null @@ -1,191 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthScheme.java,v 1.12 2004/05/13 04:02:00 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
null
.
- *
- * @return the authentication realm
- */
- String getRealm();
- /**
- * Returns a String identifying the authentication challenge. This is
- * used, in combination with the host and port to determine if
- * authorization has already been attempted or not. Schemes which
- * require multiple requests to complete the authentication should
- * return a different value for each stage in the request.
- *
- *
Additionally, the ID should take into account any changes to the - * authentication challenge and return a different value when appropriate. - * For example when the realm changes in basic authentication it should be - * considered a different authentication attempt and a different value should - * be returned.
- * - * @return String a String identifying the authentication challenge. The - * returned value may be null. - * - * @deprecated no longer used - */ - String getID(); - /** - * Tests if the authentication scheme is provides authorization on a per - * connection basis instead of usual per request basis - * - * @return true if the scheme is connection based, false - * if the scheme is request based. - * - * @since 3.0 - */ - boolean isConnectionBased(); - /** - * Authentication process may involve a series of challenge-response exchanges. - * This method tests if the authorization process has been completed, either - * successfully or unsuccessfully, that is, all the required authorization - * challenges have been processed in their entirety. - * - * @return true if the authentication process has been completed, - * false otherwise. - * - * @since 3.0 - */ - boolean isComplete(); - /** - * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} - * - * Produces an authorization string for the given set of {@link Credentials}, - * method name and URI using the given authentication scheme in response to - * the actual authorization challenge. - * - * @param credentials The set of credentials to be used for athentication - * @param method The name of the method that requires authorization. - * This parameter may be ignored, if it is irrelevant - * or not applicable to the given authentication scheme - * @param uri The URI for which authorization is needed. - * This parameter may be ignored, if it is irrelevant or not - * applicable to the given authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return the authorization string - * - * @see org.apache.commons.httpclient.HttpMethod#getName() - * @see org.apache.commons.httpclient.HttpMethod#getPath() - */ - String authenticate(Credentials credentials, String method, String uri) - throws AuthenticationException; - /** - * Produces an authorization string for the given set of {@link Credentials}. - * - * @param credentials The set of credentials to be used for athentication - * @param method The method being authenticated - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return the authorization string - * - * @since 3.0 - */ - String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException; diff --git a/clients/java/src/org/apache/commons/httpclient/auth/AuthSchemeBase.java b/clients/java/src/org/apache/commons/httpclient/auth/AuthSchemeBase.java deleted file mode 100644 index 0ecef6a..0000000 --- a/clients/java/src/org/apache/commons/httpclient/auth/AuthSchemeBase.java +++ /dev/null @@ -1,93 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/AuthSchemeBase.java,v 1.7 2004/04/18 23:51:36 jsdever Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
basic
- */
- public String getSchemeName() {
- return "basic";
- }
- /**
- * Processes the Basic challenge.
- *
- * @param challenge the challenge string
- *
- * @throws MalformedChallengeException is thrown if the authentication challenge
- * is malformed
- *
- * @since 3.0
- */
- public void processChallenge(String challenge)
- throws MalformedChallengeException
- {
- super.processChallenge(challenge);
- this.complete = true;
- }
- /**
- * Tests if the Basic authentication process has been completed.
- *
- * @return
true
if Basic authorization has been processed,
- *
false
otherwise.
- *
- * @since 3.0
- */
- public boolean isComplete() {
- return this.complete;
- }
- /**
- * Produces basic authorization string for the given set of
- * {@link Credentials}.
- *
- * @param credentials The set of credentials to be used for athentication
- * @param method Method name is ignored by the basic authentication scheme
- * @param uri URI is ignored by the basic authentication scheme
- * @throws InvalidCredentialsException if authentication credentials
- * are not valid or not applicable for this authentication scheme
- * @throws AuthenticationException if authorization string cannot
- * be generated due to an authentication failure
- *
- * @return a basic authorization string
- *
- * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
- */
- public String authenticate(Credentials credentials, String method, String uri)
- throws AuthenticationException {
- LOG.trace("enter BasicScheme.authenticate(Credentials, String, String)");
- UsernamePasswordCredentials usernamepassword = null;
- try {
- usernamepassword = (UsernamePasswordCredentials) credentials;
- } catch (ClassCastException e) {
- throw new InvalidCredentialsException(
- "Credentials cannot be used for basic authentication: "
- + credentials.getClass().getName());
- }
- return BasicScheme.authenticate(usernamepassword);
- }
- /**
- * Returns
false
. Basic authentication scheme is request based.
- *
- * @return
false
.
- *
- * @since 3.0
- */
- public boolean isConnectionBased() {
- return false;
- }
- /**
- * Produces basic authorization string for the given set of {@link Credentials}.
- *
- * @param credentials The set of credentials to be used for athentication
- * @param method The method being authenticated
- * @throws InvalidCredentialsException if authentication credentials
- * are not valid or not applicable for this authentication scheme
- * @throws AuthenticationException if authorization string cannot
- * be generated due to an authentication failure
- *
- * @return a basic authorization string
- *
- * @since 3.0
- */
- public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
- LOG.trace("enter BasicScheme.authenticate(Credentials, HttpMethod)");
- if (method == null) {
- throw new IllegalArgumentException("Method may not be null");
- }
- UsernamePasswordCredentials usernamepassword = null;
- try {
- usernamepassword = (UsernamePasswordCredentials) credentials;
- } catch (ClassCastException e) {
- throw new InvalidCredentialsException(
- "Credentials cannot be used for basic authentication: "
- + credentials.getClass().getName());
- }
- return BasicScheme.authenticate(
- usernamepassword,
- method.getParams().getCredentialCharset());
- }
- /**
- * @deprecated Use {@link #authenticate(UsernamePasswordCredentials, String)}
- *
- * Returns a basic
Authorization
header value for the given
- * {@link UsernamePasswordCredentials}.
- *
- * @param credentials The credentials to encode.
- *
- * @return a basic authorization string
- */
- public static String authenticate(UsernamePasswordCredentials credentials) {
- return authenticate(credentials, "ISO-8859-1");
- }
- /**
- * Returns a basic
Authorization
header value for the given
- * {@link UsernamePasswordCredentials} and charset.
- *
- * @param credentials The credentials to encode.
- * @param charset The charset to use for encoding the credentials
- *
- * @return a basic authorization string
- *
- * @since 3.0
- */
- public static String authenticate(UsernamePasswordCredentials credentials, String charset) {
- LOG.trace("enter BasicScheme.authenticate(UsernamePasswordCredentials, String)");
- if (credentials == null) {
- throw new IllegalArgumentException("Credentials may not be null");
- }
- if (charset == null || charset.length() == 0) {
- throw new IllegalArgumentException("charset may not be null or empty");
- }
- StringBuffer buffer = new StringBuffer();
- buffer.append(credentials.getUserName());
- buffer.append(":");
- buffer.append(credentials.getPassword());
- return "Basic " + EncodingUtil.getAsciiString(
- Base64.encodeBase64(EncodingUtil.getBytes(buffer.toString(), charset)));
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.java b/clients/java/src/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.java
deleted file mode 100644
index df3cef0..0000000
--- a/clients/java/src/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.java
+++ /dev/null
@@ -1,68 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/CredentialsNotAvailableException.java,v 1.4 2004/05/13 04:02:00 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
- * This parameter expects a value of type {@link CredentialsProvider}. - *
- */ - public static final String PROVIDER = "http.authentication.credential-provider"; - /** - * Requests additional {@link Credentials authentication credentials}. - * - * @param scheme the {@link AuthScheme authentication scheme} - * @param host the authentication host - * @param port the port of the authentication host - * @param proxy true if authenticating with a proxy, - * false otherwise - */ - public Credentials getCredentials( - final AuthScheme scheme, - final String host, - int port, - boolean proxy) throws CredentialsNotAvailableException; diff --git a/clients/java/src/org/apache/commons/httpclient/auth/DigestScheme.java b/clients/java/src/org/apache/commons/httpclient/auth/DigestScheme.java deleted file mode 100644 index fa5fe0a..0000000 --- a/clients/java/src/org/apache/commons/httpclient/auth/DigestScheme.java +++ /dev/null @@ -1,570 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/DigestScheme.java,v 1.22 2004/12/30 11:01:27 oglueck Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
digest
- */
- public String getSchemeName() {
- return "digest";
- }
- /**
- * Returns
false
. Digest authentication scheme is request based.
- *
- * @return
false
.
- *
- * @since 3.0
- */
- public boolean isConnectionBased() {
- return false;
- }
- /**
- * Produces a digest authorization string for the given set of
- * {@link Credentials}, method name and URI.
- *
- * @param credentials A set of credentials to be used for athentication
- * @param method the name of the method that requires authorization.
- * @param uri The URI for which authorization is needed.
- *
- * @throws InvalidCredentialsException if authentication credentials
- * are not valid or not applicable for this authentication scheme
- * @throws AuthenticationException if authorization string cannot
- * be generated due to an authentication failure
- *
- * @return a digest authorization string
- *
- * @see org.apache.commons.httpclient.HttpMethod#getName()
- * @see org.apache.commons.httpclient.HttpMethod#getPath()
- *
- * @deprecated Use {@link #authenticate(Credentials, HttpMethod)}
- */
- public String authenticate(Credentials credentials, String method, String uri)
- throws AuthenticationException {
- LOG.trace("enter DigestScheme.authenticate(Credentials, String, String)");
- UsernamePasswordCredentials usernamepassword = null;
- try {
- usernamepassword = (UsernamePasswordCredentials) credentials;
- } catch (ClassCastException e) {
- throw new InvalidCredentialsException(
- "Credentials cannot be used for digest authentication: "
- + credentials.getClass().getName());
- }
- getParameters().put("methodname", method);
- getParameters().put("uri", uri);
- String digest = createDigest(
- usernamepassword.getUserName(),
- usernamepassword.getPassword());
- return "Digest " + createDigestHeader(usernamepassword.getUserName(), digest);
- }
- /**
- * Produces a digest authorization string for the given set of
- * {@link Credentials}, method name and URI.
- *
- * @param credentials A set of credentials to be used for athentication
- * @param method The method being authenticated
- *
- * @throws InvalidCredentialsException if authentication credentials
- * are not valid or not applicable for this authentication scheme
- * @throws AuthenticationException if authorization string cannot
- * be generated due to an authentication failure
- *
- * @return a digest authorization string
- *
- * @since 3.0
- */
- public String authenticate(Credentials credentials, HttpMethod method)
- throws AuthenticationException {
- LOG.trace("enter DigestScheme.authenticate(Credentials, HttpMethod)");
- UsernamePasswordCredentials usernamepassword = null;
- try {
- usernamepassword = (UsernamePasswordCredentials) credentials;
- } catch (ClassCastException e) {
- throw new InvalidCredentialsException(
- "Credentials cannot be used for digest authentication: "
- + credentials.getClass().getName());
- }
- getParameters().put("methodname", method.getName());
- StringBuffer buffer = new StringBuffer(method.getPath());
- String query = method.getQueryString();
- if (query != null) {
- if (query.indexOf("?") != 0) {
- buffer.append("?");
- }
- buffer.append(method.getQueryString());
- }
- getParameters().put("uri", buffer.toString());
- String charset = getParameter("charset");
- if (charset == null) {
- getParameters().put("charset", method.getParams().getCredentialCharset());
- }
- String digest = createDigest(
- usernamepassword.getUserName(),
- usernamepassword.getPassword());
- return "Digest " + createDigestHeader(usernamepassword.getUserName(),
- digest);
- }
- /**
- * Creates an MD5 response digest.
- *
- * @param uname Username
- * @param pwd Password
- * @param charset The credential charset
- *
- * @return The created digest as string. This will be the response tag's
- * value in the Authentication HTTP header.
- * @throws AuthenticationException when MD5 is an unsupported algorithm
- */
- private String createDigest(final String uname, final String pwd) throws AuthenticationException {
- LOG.trace("enter DigestScheme.createDigest(String, String, Map)");
- final String digAlg = "MD5";
- // Collecting required tokens
- String uri = getParameter("uri");
- String realm = getParameter("realm");
- String nonce = getParameter("nonce");
- String qop = getParameter("qop");
- String method = getParameter("methodname");
- String algorithm = getParameter("algorithm");
- // If an algorithm is not specified, default to MD5.
- if (algorithm == null) {
- algorithm = "MD5";
- }
- // If an charset is not specified, default to ISO-8859-1.
- String charset = getParameter("charset");
- if (charset == null) {
- charset = "ISO-8859-1";
- }
- if (qopVariant == QOP_AUTH_INT) {
- LOG.warn("qop=auth-int is not supported");
- throw new AuthenticationException(
- "Unsupported qop in HTTP Digest authentication");
- }
- MessageDigest md5Helper;
- try {
- md5Helper = MessageDigest.getInstance(digAlg);
- } catch (Exception e) {
- throw new AuthenticationException(
- "Unsupported algorithm in HTTP Digest authentication: "
- + digAlg);
- }
- // 3.2.2.2: Calculating digest
- StringBuffer tmp = new StringBuffer(uname.length() + realm.length() + pwd.length() + 2);
- tmp.append(uname);
- tmp.append(':');
- tmp.append(realm);
- tmp.append(':');
- tmp.append(pwd);
- // unq(username-value) ":" unq(realm-value) ":" passwd
- String a1 = tmp.toString();
- //a1 is suitable for MD5 algorithm
- if(algorithm.equals("MD5-sess")) {
- // H( unq(username-value) ":" unq(realm-value) ":" passwd )
- // ":" unq(nonce-value)
- // ":" unq(cnonce-value)
- String tmp2=encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
- StringBuffer tmp3 = new StringBuffer(tmp2.length() + nonce.length() + cnonce.length() + 2);
- tmp3.append(tmp2);
- tmp3.append(':');
- tmp3.append(nonce);
- tmp3.append(':');
- tmp3.append(cnonce);
- a1 = tmp3.toString();
- } else if(!algorithm.equals("MD5")) {
- LOG.warn("Unhandled algorithm " + algorithm + " requested");
- }
- String md5a1 = encode(md5Helper.digest(EncodingUtil.getBytes(a1, charset)));
- String a2 = null;
- if (qopVariant == QOP_AUTH_INT) {
- LOG.error("Unhandled qop auth-int");
- //we do not have access to the entity-body or its hash
- //TODO: add Method ":" digest-uri-value ":" H(entity-body)
- } else {
- a2 = method + ":" + uri;
- }
- String md5a2 = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(a2)));
- // 3.2.2.1
- String serverDigestValue;
- if (qopVariant == QOP_MISSING) {
- LOG.debug("Using null qop method");
- StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length() + md5a2.length());
- tmp2.append(md5a1);
- tmp2.append(':');
- tmp2.append(nonce);
- tmp2.append(':');
- tmp2.append(md5a2);
- serverDigestValue = tmp2.toString();
- } else {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Using qop method " + qop);
- }
- String qopOption = getQopVariantString();
- StringBuffer tmp2 = new StringBuffer(md5a1.length() + nonce.length()
- + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
- tmp2.append(md5a1);
- tmp2.append(':');
- tmp2.append(nonce);
- tmp2.append(':');
- tmp2.append(NC);
- tmp2.append(':');
- tmp2.append(cnonce);
- tmp2.append(':');
- tmp2.append(qopOption);
- tmp2.append(':');
- tmp2.append(md5a2);
- serverDigestValue = tmp2.toString();
- }
- String serverDigest =
- encode(md5Helper.digest(EncodingUtil.getAsciiBytes(serverDigestValue)));
- return serverDigest;
- }
- /**
- * Creates digest-response header as defined in RFC2617.
- *
- * @param uname Username
- * @param digest The response tag's value as String.
- *
- * @return The digest-response as String.
- */
- private String createDigestHeader(final String uname, final String digest)
- throws AuthenticationException {
- LOG.trace("enter DigestScheme.createDigestHeader(String, Map, "
- + "String)");
- String uri = getParameter("uri");
- String realm = getParameter("realm");
- String nonce = getParameter("nonce");
- String opaque = getParameter("opaque");
- String response = digest;
- String algorithm = getParameter("algorithm");
- List params = new ArrayList(20);
- params.add(new NameValuePair("username", uname));
- params.add(new NameValuePair("realm", realm));
- params.add(new NameValuePair("nonce", nonce));
- params.add(new NameValuePair("uri", uri));
- params.add(new NameValuePair("response", response));
- if (qopVariant != QOP_MISSING) {
- params.add(new NameValuePair("qop", getQopVariantString()));
- params.add(new NameValuePair("nc", NC));
- params.add(new NameValuePair("cnonce", this.cnonce));
- }
- if (algorithm != null) {
- params.add(new NameValuePair("algorithm", algorithm));
- }
- if (opaque != null) {
- params.add(new NameValuePair("opaque", opaque));
- }
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < params.size(); i++) {
- NameValuePair param = (NameValuePair) params.get(i);
- if (i > 0) {
- buffer.append(", ");
- }
- boolean noQuotes = "nc".equals(param.getName()) ||
- "qop".equals(param.getName());
- this.formatter.setAlwaysUseQuotes(!noQuotes);
- this.formatter.format(buffer, param);
- }
- return buffer.toString();
- }
- private String getQopVariantString() {
- String qopOption;
- if (qopVariant == QOP_AUTH_INT) {
- qopOption = "auth-int";
- } else {
- qopOption = "auth";
- }
- return qopOption;
- }
- /**
- * Encodes the 128 bit (16 bytes) MD5 digest into a 32 characters long
- *
String
according to RFC 2617.
- *
- * @param binaryData array containing the digest
- * @return encoded MD5, or
null
if encoding failed
- */
- private static String encode(byte[] binaryData) {
- LOG.trace("enter DigestScheme.encode(byte[])");
- if (binaryData.length != 16) {
- return null;
- }
- char[] buffer = new char[32];
- for (int i = 0; i < 16; i++) {
- int low = (int) (binaryData[i] & 0x0f);
- int high = (int) ((binaryData[i] & 0xf0) >> 4);
- buffer[i * 2] = HEXADECIMAL[high];
- buffer[(i * 2) + 1] = HEXADECIMAL[low];
- }
- return new String(buffer);
- }
- /**
- * Creates a random cnonce value based on the current time.
- *
- * @return The cnonce value as String.
- * @throws HttpClientError if MD5 algorithm is not supported.
- */
- public static String createCnonce() {
- LOG.trace("enter DigestScheme.createCnonce()");
- String cnonce;
- final String digAlg = "MD5";
- MessageDigest md5Helper;
- try {
- md5Helper = MessageDigest.getInstance(digAlg);
- } catch (NoSuchAlgorithmException e) {
- throw new HttpClientError(
- "Unsupported algorithm in HTTP Digest authentication: "
- + digAlg);
- }
- cnonce = Long.toString(System.currentTimeMillis());
- cnonce = encode(md5Helper.digest(EncodingUtil.getAsciiBytes(cnonce)));
- return cnonce;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/auth/HttpAuthRealm.java b/clients/java/src/org/apache/commons/httpclient/auth/HttpAuthRealm.java
deleted file mode 100644
index d9f4271..0000000
--- a/clients/java/src/org/apache/commons/httpclient/auth/HttpAuthRealm.java
+++ /dev/null
@@ -1,57 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/HttpAuthRealm.java,v 1.9 2004/06/12 22:47:23 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
NTLM
,
- *
Digest
,
Basic
schemes are recognized.
- * The
NTLM
scheme is considered the strongest and is
- * preferred to all others. The
Digest
scheme is preferred to
- * the
Basic
one which provides no encryption for credentials.
- * The
Basic
scheme is used only if it is the only one
- * supported.
- *
- * @param challenges The array of authentication challenges
- *
- * @return The strongest authentication scheme supported
- *
- * @throws MalformedChallengeException is thrown if an authentication
- * challenge is malformed
- * @throws UnsupportedOperationException when none of challenge types
- * available is supported.
- *
- * @deprecated Use {@link AuthChallengeParser#parseChallenges(Header[])} and
- * {@link AuthPolicy#getAuthScheme(String)}
- */
- public static AuthScheme selectAuthScheme(final Header[] challenges)
- throws MalformedChallengeException {
- LOG.trace("enter HttpAuthenticator.selectAuthScheme(Header[])");
- if (challenges == null) {
- throw new IllegalArgumentException("Array of challenges may not be null");
- }
- if (challenges.length == 0) {
- throw new IllegalArgumentException("Array of challenges may not be empty");
- }
- String challenge = null;
- Map challengemap = new HashMap(challenges.length);
- for (int i = 0; i < challenges.length; i++) {
- challenge = challenges[i].getValue();
- String s = AuthChallengeParser.extractScheme(challenge);
- challengemap.put(s, challenge);
- }
- challenge = (String) challengemap.get("ntlm");
- if (challenge != null) {
- return new NTLMScheme(challenge);
- }
- challenge = (String) challengemap.get("digest");
- if (challenge != null) {
- return new DigestScheme(challenge);
- }
- challenge = (String) challengemap.get("basic");
- if (challenge != null) {
- return new BasicScheme(challenge);
- }
- throw new UnsupportedOperationException(
- "Authentication scheme(s) not supported: " + challengemap.toString());
- }
- private static boolean doAuthenticateDefault(
- HttpMethod method,
- HttpConnection conn,
- HttpState state,
- boolean proxy)
- throws AuthenticationException {
- if (method == null) {
- throw new IllegalArgumentException("HTTP method may not be null");
- }
- if (state == null) {
- throw new IllegalArgumentException("HTTP state may not be null");
- }
- String host = null;
- if (conn != null) {
- host = proxy ? conn.getProxyHost() : conn.getHost();
- }
- Credentials credentials = proxy
- ? state.getProxyCredentials(null, host) : state.getCredentials(null, host);
- if (credentials == null) {
- return false;
- }
- if (!(credentials instanceof UsernamePasswordCredentials)) {
- throw new InvalidCredentialsException(
- "Credentials cannot be used for basic authentication: "
- + credentials.toString());
- }
- String auth = BasicScheme.authenticate(
- (UsernamePasswordCredentials) credentials,
- method.getParams().getCredentialCharset());
- if (auth != null) {
- String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
- Header header = new Header(s, auth, true);
- method.addRequestHeader(header);
- return true;
- } else {
- return false;
- }
- }
- /**
- * Attempt to provide default authentication credentials
- * to the given method in the given context using basic
- * authentication scheme.
- *
- * @param method the HttpMethod which requires authentication
- * @param conn the connection to a specific host. This parameter
- * may be
null
if default credentials (not specific
- * to any particular host) are to be used
- * @param state the HttpState object providing Credentials
- *
- * @return true if the
Authenticate
response header
- * was added
- *
- * @throws InvalidCredentialsException if authentication credentials
- * are not valid or not applicable for basic scheme
- * @throws AuthenticationException when a parsing or other error occurs
- *
- * @see HttpState#setCredentials(String,String,Credentials)
- *
- * @deprecated use AuthScheme
- */
- public static boolean authenticateDefault(
- HttpMethod method,
- HttpConnection conn,
- HttpState state)
- throws AuthenticationException {
- LOG.trace(
- "enter HttpAuthenticator.authenticateDefault(HttpMethod, HttpConnection, HttpState)");
- return doAuthenticateDefault(method, conn, state, false);
- }
- /**
- * Attempt to provide default proxy authentication credentials
- * to the given method in the given context using basic
- * authentication scheme.
- *
- * @param method the HttpMethod which requires authentication
- * @param conn the connection to a specific host. This parameter
- * may be
null
if default credentials (not specific
- * to any particular host) are to be used
- * @param state the HttpState object providing Credentials
- *
- * @return true if the
Proxy-Authenticate
response header
- * was added
- *
- * @throws InvalidCredentialsException if authentication credentials
- * are not valid or not applicable for basic scheme
- * @throws AuthenticationException when a parsing or other error occurs
- * @see HttpState#setCredentials(String,String,Credentials)
- *
- * @deprecated use AuthScheme
- */
- public static boolean authenticateProxyDefault(
- HttpMethod method,
- HttpConnection conn,
- HttpState state)
- throws AuthenticationException {
- LOG.trace("enter HttpAuthenticator.authenticateProxyDefault(HttpMethod, HttpState)");
- return doAuthenticateDefault(method, conn, state, true);
- }
- private static boolean doAuthenticate(
- AuthScheme authscheme,
- HttpMethod method,
- HttpConnection conn,
- HttpState state,
- boolean proxy)
- throws AuthenticationException {
- if (authscheme == null) {
- throw new IllegalArgumentException("Authentication scheme may not be null");
- }
- if (method == null) {
- throw new IllegalArgumentException("HTTP method may not be null");
- }
- if (state == null) {
- throw new IllegalArgumentException("HTTP state may not be null");
- }
- String host = null;
- if (conn != null) {
- if (proxy) {
- host = conn.getProxyHost();
- } else {
- host = method.getParams().getVirtualHost();
- if (host == null) {
- host = conn.getHost();
- }
- }
- }
- String realm = authscheme.getRealm();
- if (LOG.isDebugEnabled()) {
- StringBuffer buffer = new StringBuffer();
- buffer.append("Using credentials for ");
- if (realm == null) {
- buffer.append("default");
- } else {
- buffer.append('\'');
- buffer.append(realm);
- buffer.append('\'');
- }
- buffer.append(" authentication realm at ");
- buffer.append(host);
- LOG.debug(buffer.toString());
- }
- Credentials credentials = proxy
- ? state.getProxyCredentials(realm, host)
- : state.getCredentials(realm, host);
- if (credentials == null) {
- StringBuffer buffer = new StringBuffer();
- buffer.append("No credentials available for the ");
- if (realm == null) {
- buffer.append("default");
- } else {
- buffer.append('\'');
- buffer.append(realm);
- buffer.append('\'');
- }
- buffer.append(" authentication realm at ");
- buffer.append(host);
- throw new CredentialsNotAvailableException(buffer.toString());
- }
- String auth = authscheme.authenticate(credentials, method);
- if (auth != null) {
- String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP;
- Header header = new Header(s, auth, true);
- method.addRequestHeader(header);
- return true;
- } else {
- return false;
- }
- }
- /**
- * Attempt to provide requisite authentication credentials to the
- * given method in the given context using the given
- * authentication scheme.
- *
- * @param authscheme The authentication scheme to be used
- * @param method The HttpMethod which requires authentication
- * @param conn the connection to a specific host. This parameter
- * may be
null
if default credentials (not specific
- * to any particular host) are to be used
- * @param state The HttpState object providing Credentials
- *
- * @return true if the
Authenticate
response header was added
- *
- * @throws CredentialsNotAvailableException if authentication credentials
- * required to respond to the authentication challenge are not available
- * @throws AuthenticationException when a parsing or other error occurs
- * @see HttpState#setCredentials(String,String,Credentials)
- *
- * @deprecated use AuthScheme
- */
- public static boolean authenticate(
- AuthScheme authscheme,
- HttpMethod method,
- HttpConnection conn,
- HttpState state)
- throws AuthenticationException {
- LOG.trace(
- "enter HttpAuthenticator.authenticate(AuthScheme, HttpMethod, HttpConnection, "
- + "HttpState)");
- return doAuthenticate(authscheme, method, conn, state, false);
- }
- /**
- * Attempt to provide requisite proxy authentication credentials
- * to the given method in the given context using
- * the given authentication scheme.
- *
- * @param authscheme The authentication scheme to be used
- * @param method the HttpMethod which requires authentication
- * @param conn the connection to a specific host. This parameter
- * may be
null
if default credentials (not specific
- * to any particular host) are to be used
- * @param state the HttpState object providing Credentials
- *
- * @return true if the
Proxy-Authenticate
response header
- * was added
- *
- * @throws CredentialsNotAvailableException if authentication credentials
- * required to respond to the authentication challenge are not available
- * @throws AuthenticationException when a parsing or other error occurs
- * @see HttpState#setCredentials(String,String,Credentials)
- *
- * @deprecated use AuthScheme
- */
- public static boolean authenticateProxy(
- AuthScheme authscheme,
- HttpMethod method,
- HttpConnection conn,
- HttpState state
- ) throws AuthenticationException {
- LOG.trace("enter HttpAuthenticator.authenticateProxy(AuthScheme, HttpMethod, HttpState)");
- return doAuthenticate(authscheme, method, conn, state, true);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/auth/InvalidCredentialsException.java b/clients/java/src/org/apache/commons/httpclient/auth/InvalidCredentialsException.java
deleted file mode 100644
index 1377aac..0000000
--- a/clients/java/src/org/apache/commons/httpclient/auth/InvalidCredentialsException.java
+++ /dev/null
@@ -1,68 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/InvalidCredentialsException.java,v 1.4 2004/05/13 04:02:00 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
- *
Please note that an implementation of JCE must be correctly installed and configured when - * using NTLM support.
- *This class should not be used externally to HttpClient as it's API is specifically - * designed to work with HttpClient's use case, in particular it's connection management.
- * @author Adrian Sutton - * @author Jeff Dever - * @author Mike Bowler - * @version $Revision: 480424 $ $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * @since 3.0 -final class NTLM { - /** Character encoding */ - public static final String DEFAULT_CHARSET = "ASCII"; - /** The current response */ - private byte[] currentResponse; - /** The current position */ - private int currentPosition = 0; - /** The character set to use for encoding the credentials */ - private String credentialCharset = DEFAULT_CHARSET; - /** - * Returns the response for the given message. - * - * @param message the message that was received from the server. - * @param username the username to authenticate with. - * @param password the password to authenticate with. - * @param host The host. - * @param domain the NT domain to authenticate in. - * @return The response. - * @throws HttpException If the messages cannot be retrieved. - */ - public final String getResponseFor(String message, - String username, String password, String host, String domain) - throws AuthenticationException { - final String response; - if (message == null || message.trim().equals("")) { - response = getType1Message(host, domain); - } else { - response = getType3Message(username, password, host, domain, - parseType2Message(message)); - } - return response; - } - /** - * Return the cipher for the specified key. - * @param key The key. - * @return Cipher The cipher. - * @throws AuthenticationException If the cipher cannot be retrieved. - */ - private Cipher getCipher(byte[] key) throws AuthenticationException { - try { - final Cipher ecipher = Cipher.getInstance("DES/ECB/NoPadding"); - key = setupKey(key); - ecipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "DES")); - return ecipher; - } catch (NoSuchAlgorithmException e) { - throw new AuthenticationException("DES encryption is not available.", e); - } catch (InvalidKeyException e) { - throw new AuthenticationException("Invalid key for DES encryption.", e); - } catch (NoSuchPaddingException e) { - throw new AuthenticationException( - "NoPadding option for DES is not available.", e); - } - } - /** - * Adds parity bits to the key. - * @param key56 The key - * @return The modified key. - */ - private byte[] setupKey(byte[] key56) { - byte[] key = new byte[8]; - key[0] = (byte) ((key56[0] >> 1) & 0xff); - key[1] = (byte) ((((key56[0] & 0x01) << 6) - | (((key56[1] & 0xff) >> 2) & 0xff)) & 0xff); - key[2] = (byte) ((((key56[1] & 0x03) << 5) - | (((key56[2] & 0xff) >> 3) & 0xff)) & 0xff); - key[3] = (byte) ((((key56[2] & 0x07) << 4) - | (((key56[3] & 0xff) >> 4) & 0xff)) & 0xff); - key[4] = (byte) ((((key56[3] & 0x0f) << 3) - | (((key56[4] & 0xff) >> 5) & 0xff)) & 0xff); - key[5] = (byte) ((((key56[4] & 0x1f) << 2) - | (((key56[5] & 0xff) >> 6) & 0xff)) & 0xff); - key[6] = (byte) ((((key56[5] & 0x3f) << 1) - | (((key56[6] & 0xff) >> 7) & 0xff)) & 0xff); - key[7] = (byte) (key56[6] & 0x7f); - for (int i = 0; i < key.length; i++) { - key[i] = (byte) (key[i] << 1); - } - return key; - } - /** - * Encrypt the data. - * @param key The key. - * @param bytes The data - * @return byte[] The encrypted data - * @throws HttpException If {@link Cipher.doFinal(byte[])} fails - */ - private byte[] encrypt(byte[] key, byte[] bytes) - throws AuthenticationException { - Cipher ecipher = getCipher(key); - try { - byte[] enc = ecipher.doFinal(bytes); - return enc; - } catch (IllegalBlockSizeException e) { - throw new AuthenticationException("Invalid block size for DES encryption.", e); - } catch (BadPaddingException e) { - throw new AuthenticationException("Data not padded correctly for DES encryption.", e); - } - } - /** - * Prepares the object to create a response of the given length. - * @param length the length of the response to prepare. - */ - private void prepareResponse(int length) { - currentResponse = new byte[length]; - currentPosition = 0; - } - /** - * Adds the given byte to the response. - * @param b the byte to add. - */ - private void addByte(byte b) { - currentResponse[currentPosition] = b; - currentPosition++; - } - /** - * Adds the given bytes to the response. - * @param bytes the bytes to add. - */ - private void addBytes(byte[] bytes) { - for (int i = 0; i < bytes.length; i++) { - currentResponse[currentPosition] = bytes[i]; - currentPosition++; - } - } - /** - * Returns the response that has been generated after shrinking the array if - * required and base64 encodes the response. - * @return The response as above. - */ - private String getResponse() { - byte[] resp; - if (currentResponse.length > currentPosition) { - byte[] tmp = new byte[currentPosition]; - for (int i = 0; i < currentPosition; i++) { - tmp[i] = currentResponse[i]; - } - resp = tmp; - } else { - resp = currentResponse; - } - return EncodingUtil.getAsciiString(Base64.encodeBase64(resp)); - } - /** - * Creates the first message (type 1 message) in the NTLM authentication sequence. - * This message includes the user name, domain and host for the authentication session. - * - * @param host the computer name of the host requesting authentication. - * @param domain The domain to authenticate with. - * @return String the message to add to the HTTP request header. - */ - public String getType1Message(String host, String domain) { - host = host.toUpperCase(); - domain = domain.toUpperCase(); - byte[] hostBytes = EncodingUtil.getBytes(host, DEFAULT_CHARSET); - byte[] domainBytes = EncodingUtil.getBytes(domain, DEFAULT_CHARSET); - int finalLength = 32 + hostBytes.length + domainBytes.length; - prepareResponse(finalLength); - // The initial id string. - byte[] protocol = EncodingUtil.getBytes("NTLMSSP", DEFAULT_CHARSET); - addBytes(protocol); - addByte((byte) 0); - // Type - addByte((byte) 1); - addByte((byte) 0); - addByte((byte) 0); - addByte((byte) 0); - // Flags - addByte((byte) 6); - addByte((byte) 82); - addByte((byte) 0); - addByte((byte) 0); - // Domain length (first time). - int iDomLen = domainBytes.length; - byte[] domLen = convertShort(iDomLen); - addByte(domLen[0]); - addByte(domLen[1]); - // Domain length (second time). - addByte(domLen[0]); - addByte(domLen[1]); - // Domain offset. - byte[] domOff = convertShort(hostBytes.length + 32); - addByte(domOff[0]); - addByte(domOff[1]); - addByte((byte) 0); - addByte((byte) 0); - // Host length (first time). - byte[] hostLen = convertShort(hostBytes.length); - addByte(hostLen[0]); - addByte(hostLen[1]); - // Host length (second time). - addByte(hostLen[0]); - addByte(hostLen[1]); - // Host offset (always 32). - byte[] hostOff = convertShort(32); - addByte(hostOff[0]); - addByte(hostOff[1]); - addByte((byte) 0); - addByte((byte) 0); - // Host String. - addBytes(hostBytes); - // Domain String. - addBytes(domainBytes); - return getResponse(); - } - /** - * Extracts the server nonce out of the given message type 2. - * - * @param message the String containing the base64 encoded message. - * @return an array of 8 bytes that the server sent to be used when - * hashing the password. - */ - public byte[] parseType2Message(String message) { - // Decode the message first. - byte[] msg = Base64.decodeBase64(EncodingUtil.getBytes(message, DEFAULT_CHARSET)); - byte[] nonce = new byte[8]; - // The nonce is the 8 bytes starting from the byte in position 24. - for (int i = 0; i < 8; i++) { - nonce[i] = msg[i + 24]; - } - return nonce; - } - /** - * Creates the type 3 message using the given server nonce. The type 3 message includes all the - * information for authentication, host, domain, username and the result of encrypting the - * nonce sent by the server using the user's password as the key. - * - * @param user The user name. This should not include the domain name. - * @param password The password. - * @param host The host that is originating the authentication request. - * @param domain The domain to authenticate within. - * @param nonce the 8 byte array the server sent. - * @return The type 3 message. - * @throws AuthenticationException If {@encrypt(byte[],byte[])} fails. - */ - public String getType3Message(String user, String password, - String host, String domain, byte[] nonce) - throws AuthenticationException { - int ntRespLen = 0; - int lmRespLen = 24; - domain = domain.toUpperCase(); - host = host.toUpperCase(); - user = user.toUpperCase(); - byte[] domainBytes = EncodingUtil.getBytes(domain, DEFAULT_CHARSET); - byte[] hostBytes = EncodingUtil.getBytes(host, DEFAULT_CHARSET); - byte[] userBytes = EncodingUtil.getBytes(user, credentialCharset); - int domainLen = domainBytes.length; - int hostLen = hostBytes.length; - int userLen = userBytes.length; - int finalLength = 64 + ntRespLen + lmRespLen + domainLen - + userLen + hostLen; - prepareResponse(finalLength); - byte[] ntlmssp = EncodingUtil.getBytes("NTLMSSP", DEFAULT_CHARSET); - addBytes(ntlmssp); - addByte((byte) 0); - addByte((byte) 3); - addByte((byte) 0); - addByte((byte) 0); - addByte((byte) 0); - // LM Resp Length (twice) - addBytes(convertShort(24)); - addBytes(convertShort(24)); - // LM Resp Offset - addBytes(convertShort(finalLength - 24)); - addByte((byte) 0); - addByte((byte) 0); - // NT Resp Length (twice) - addBytes(convertShort(0)); - addBytes(convertShort(0)); - // NT Resp Offset - addBytes(convertShort(finalLength)); - addByte((byte) 0); - addByte((byte) 0); - // Domain length (twice) - addBytes(convertShort(domainLen)); - addBytes(convertShort(domainLen)); - // Domain offset. - addBytes(convertShort(64)); - addByte((byte) 0); - addByte((byte) 0); - // User Length (twice) - addBytes(convertShort(userLen)); - addBytes(convertShort(userLen)); - // User offset - addBytes(convertShort(64 + domainLen)); - addByte((byte) 0); - addByte((byte) 0); - // Host length (twice) - addBytes(convertShort(hostLen)); - addBytes(convertShort(hostLen)); - // Host offset - addBytes(convertShort(64 + domainLen + userLen)); - for (int i = 0; i < 6; i++) { - addByte((byte) 0); - } - // Message length - addBytes(convertShort(finalLength)); - addByte((byte) 0); - addByte((byte) 0); - // Flags - addByte((byte) 6); - addByte((byte) 82); - addByte((byte) 0); - addByte((byte) 0); - addBytes(domainBytes); - addBytes(userBytes); - addBytes(hostBytes); - addBytes(hashPassword(password, nonce)); - return getResponse(); - } - /** - * Creates the LANManager and NT response for the given password using the - * given nonce. - * @param password the password to create a hash for. - * @param nonce the nonce sent by the server. - * @return The response. - * @throws HttpException If {@link #encrypt(byte[],byte[])} fails. - */ - private byte[] hashPassword(String password, byte[] nonce) - throws AuthenticationException { - byte[] passw = EncodingUtil.getBytes(password.toUpperCase(), credentialCharset); - byte[] lmPw1 = new byte[7]; - byte[] lmPw2 = new byte[7]; - int len = passw.length; - if (len > 7) { - len = 7; - } - int idx; - for (idx = 0; idx < len; idx++) { - lmPw1[idx] = passw[idx]; - } - for (; idx < 7; idx++) { - lmPw1[idx] = (byte) 0; - } - len = passw.length; - if (len > 14) { - len = 14; - } - for (idx = 7; idx < len; idx++) { - lmPw2[idx - 7] = passw[idx]; - } - for (; idx < 14; idx++) { - lmPw2[idx - 7] = (byte) 0; - } - // Create LanManager hashed Password - byte[] magic = { - (byte) 0x4B, (byte) 0x47, (byte) 0x53, (byte) 0x21, - (byte) 0x40, (byte) 0x23, (byte) 0x24, (byte) 0x25 - }; - byte[] lmHpw1; - lmHpw1 = encrypt(lmPw1, magic); - byte[] lmHpw2 = encrypt(lmPw2, magic); - byte[] lmHpw = new byte[21]; - for (int i = 0; i < lmHpw1.length; i++) { - lmHpw[i] = lmHpw1[i]; - } - for (int i = 0; i < lmHpw2.length; i++) { - lmHpw[i + 8] = lmHpw2[i]; - } - for (int i = 0; i < 5; i++) { - lmHpw[i + 16] = (byte) 0; - } - // Create the responses. - byte[] lmResp = new byte[24]; - calcResp(lmHpw, nonce, lmResp); - return lmResp; - } - /** - * Takes a 21 byte array and treats it as 3 56-bit DES keys. The 8 byte - * plaintext is encrypted with each key and the resulting 24 bytes are - * stored in the results array. - * - * @param keys The keys. - * @param plaintext The plain text to encrypt. - * @param results Where the results are stored. - * @throws AuthenticationException If {@link #encrypt(byte[],byte[])} fails. - */ - private void calcResp(byte[] keys, byte[] plaintext, byte[] results) - throws AuthenticationException { - byte[] keys1 = new byte[7]; - byte[] keys2 = new byte[7]; - byte[] keys3 = new byte[7]; - for (int i = 0; i < 7; i++) { - keys1[i] = keys[i]; - } - for (int i = 0; i < 7; i++) { - keys2[i] = keys[i + 7]; - } - for (int i = 0; i < 7; i++) { - keys3[i] = keys[i + 14]; - } - byte[] results1 = encrypt(keys1, plaintext); - byte[] results2 = encrypt(keys2, plaintext); - byte[] results3 = encrypt(keys3, plaintext); - for (int i = 0; i < 8; i++) { - results[i] = results1[i]; - } - for (int i = 0; i < 8; i++) { - results[i + 8] = results2[i]; - } - for (int i = 0; i < 8; i++) { - results[i + 16] = results3[i]; - } - } - /** - * Converts a given number to a two byte array in little endian order. - * @param num the number to convert. - * @return The byte representation of num in little endian order. - */ - private byte[] convertShort(int num) { - byte[] val = new byte[2]; - String hex = Integer.toString(num, 16); - while (hex.length() < 4) { - hex = "0" + hex; - } - String low = hex.substring(2, 4); - String high = hex.substring(0, 2); - val[0] = (byte) Integer.parseInt(low, 16); - val[1] = (byte) Integer.parseInt(high, 16); - return val; - } - /** - * @return Returns the credentialCharset. - */ - public String getCredentialCharset() { - return credentialCharset; - } - /** - * @param credentialCharset The credentialCharset to set. - */ - public void setCredentialCharset(String credentialCharset) { - this.credentialCharset = credentialCharset; - } diff --git a/clients/java/src/org/apache/commons/httpclient/auth/NTLMScheme.java b/clients/java/src/org/apache/commons/httpclient/auth/NTLMScheme.java deleted file mode 100644 index 3b19394..0000000 --- a/clients/java/src/org/apache/commons/httpclient/auth/NTLMScheme.java +++ /dev/null @@ -1,355 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/NTLMScheme.java,v 1.21 2004/05/13 04:02:00 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
ntlm
- */
- public String getSchemeName() {
- return "ntlm";
- }
- /**
- * The concept of an authentication realm is not supported by the NTLM
- * authentication scheme. Always returns
null
.
- *
- * @return
null
- */
- public String getRealm() {
- return null;
- }
- /**
- * Returns a String identifying the authentication challenge. This is
- * used, in combination with the host and port to determine if
- * authorization has already been attempted or not. Schemes which
- * require multiple requests to complete the authentication should
- * return a different value for each stage in the request.
- *
- *
Additionally, the ID should take into account any changes to the - * authentication challenge and return a different value when appropriate. - * For example when the realm changes in basic authentication it should be - * considered a different authentication attempt and a different value should - * be returned.
- * - * @return String a String identifying the authentication challenge. The - * returned value may be null. - * - * @deprecated no longer used - */ - public String getID() { - return ntlmchallenge; - } - /** - * Returns the authentication parameter with the given name, if available. - * - *There are no valid parameters for NTLM authentication so this method always returns - * null .
- * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - public String getParameter(String name) { - if (name == null) { - throw new IllegalArgumentException("Parameter name may not be null"); - } - return null; - } - /** - * Returns true . NTLM authentication scheme is connection based. - * - * @return true . - * - * @since 3.0 - */ - public boolean isConnectionBased() { - return true; - } - /** - * Create a NTLM authorization string for the given - * challenge and NT credentials. - * - * @param challenge The challenge. - * @param credentials {@link NTCredentials} - * - * @return a ntlm authorization string - * @throws AuthenticationException is thrown if authentication fails - * - * @deprecated Use non-static {@link #authenticate(Credentials, HttpMethod)} - */ - public static String authenticate( - final NTCredentials credentials, final String challenge) - throws AuthenticationException { - LOG.trace("enter NTLMScheme.authenticate(NTCredentials, String)"); - if (credentials == null) { - throw new IllegalArgumentException("Credentials may not be null"); - } - NTLM ntlm = new NTLM(); - String s = ntlm.getResponseFor(challenge, - credentials.getUserName(), credentials.getPassword(), - credentials.getHost(), credentials.getDomain()); - return "NTLM " + s; - } - /** - * Create a NTLM authorization string for the given - * challenge and NT credentials. - * - * @param challenge The challenge. - * @param credentials {@link NTCredentials} - * @param charset The charset to use for encoding the credentials - * - * @return a ntlm authorization string - * @throws AuthenticationException is thrown if authentication fails - * - * @deprecated Use non-static {@link #authenticate(Credentials, HttpMethod)} - * - * @since 3.0 - */ - public static String authenticate( - final NTCredentials credentials, - final String challenge, - String charset - ) throws AuthenticationException { - LOG.trace("enter NTLMScheme.authenticate(NTCredentials, String)"); - if (credentials == null) { - throw new IllegalArgumentException("Credentials may not be null"); - } - NTLM ntlm = new NTLM(); - ntlm.setCredentialCharset(charset); - String s = ntlm.getResponseFor( - challenge, - credentials.getUserName(), - credentials.getPassword(), - credentials.getHost(), - credentials.getDomain()); - return "NTLM " + s; - } - /** - * Produces NTLM authorization string for the given set of - * {@link Credentials}. - * - * @param credentials The set of credentials to be used for athentication - * @param method Method name is ignored by the NTLM authentication scheme - * @param uri URI is ignored by the NTLM authentication scheme - * @throws InvalidCredentialsException if authentication credentials - * are not valid or not applicable for this authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return an NTLM authorization string - * - * @deprecated Use {@link #authenticate(Credentials, HttpMethod)} - */ - public String authenticate(Credentials credentials, String method, String uri) - throws AuthenticationException { - LOG.trace("enter NTLMScheme.authenticate(Credentials, String, String)"); - NTCredentials ntcredentials = null; - try { - ntcredentials = (NTCredentials) credentials; - } catch (ClassCastException e) { - throw new InvalidCredentialsException( - "Credentials cannot be used for NTLM authentication: " - + credentials.getClass().getName()); - } - return NTLMScheme.authenticate(ntcredentials, this.ntlmchallenge); - } - /** - * Produces NTLM authorization string for the given set of - * {@link Credentials}. - * - * @param credentials The set of credentials to be used for athentication - * @param method The method being authenticated - * - * @throws InvalidCredentialsException if authentication credentials - * are not valid or not applicable for this authentication scheme - * @throws AuthenticationException if authorization string cannot - * be generated due to an authentication failure - * - * @return an NTLM authorization string - * - * @since 3.0 - */ - public String authenticate( - Credentials credentials, - HttpMethod method - ) throws AuthenticationException { - LOG.trace("enter NTLMScheme.authenticate(Credentials, HttpMethod)"); - if (this.state == UNINITIATED) { - throw new IllegalStateException("NTLM authentication process has not been initiated"); - } - NTCredentials ntcredentials = null; - try { - ntcredentials = (NTCredentials) credentials; - } catch (ClassCastException e) { - throw new InvalidCredentialsException( - "Credentials cannot be used for NTLM authentication: " - + credentials.getClass().getName()); - } - NTLM ntlm = new NTLM(); - ntlm.setCredentialCharset(method.getParams().getCredentialCharset()); - String response = null; - if (this.state == INITIATED || this.state == FAILED) { - response = ntlm.getType1Message( - ntcredentials.getHost(), - ntcredentials.getDomain()); - this.state = TYPE1_MSG_GENERATED; - } else { - response = ntlm.getType3Message( - ntcredentials.getUserName(), - ntcredentials.getPassword(), - ntcredentials.getHost(), - ntcredentials.getDomain(), - ntlm.parseType2Message(this.ntlmchallenge)); - this.state = TYPE3_MSG_GENERATED; - } - return "NTLM " + response; - } diff --git a/clients/java/src/org/apache/commons/httpclient/auth/RFC2617Scheme.java b/clients/java/src/org/apache/commons/httpclient/auth/RFC2617Scheme.java deleted file mode 100644 index 8177074..0000000 --- a/clients/java/src/org/apache/commons/httpclient/auth/RFC2617Scheme.java +++ /dev/null @@ -1,155 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/auth/RFC2617Scheme.java,v 1.10 2004/05/13 04:02:00 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *Additionally, the ID should take into account any changes to the - * authentication challenge and return a different value when appropriate. - * For example when the realm changes in basic authentication it should be - * considered a different authentication attempt and a different value should - * be returned.
- * - *This method simply returns the realm for the challenge.
- * - * @return String a String identifying the authentication challenge. The - * returned value may be null. - * - * @deprecated no longer used - */ - public String getID() { - return getRealm(); - } diff --git a/clients/java/src/org/apache/commons/httpclient/auth/package.html b/clients/java/src/org/apache/commons/httpclient/auth/package.html deleted file mode 100644 index a3224c6..0000000 --- a/clients/java/src/org/apache/commons/httpclient/auth/package.html +++ /dev/null @@ -1,11 +0,0 @@ -
- * This value is required for generating
- * the
Cookie
request header because the specification requires that if
- *
Set-Cookie2
header contains a blank value for port attribute,
- * the
Cookie
header should also contain a port attribute with no value.
- *
- * @param value
true
if port attribute is specified as blank in response
- * header.
- *
- * @see #isPortAttributeBlank
- */
- public void setPortAttributeBlank(boolean value) {
- isPortAttributeBlank = value;
- }
- /**
- * @return
true
if the port attribute in
Set-Cookie2
header
- * had no value (was of the form Port="").
- *
- * @see #setPortAttributeBlank
- */
- public boolean isPortAttributeBlank() {
- return isPortAttributeBlank;
- }
- /**
- * Indicates whether the cookie had a version attribute specified in the
- *
Set-Cookie2
response header.
- *
- * @param value
true
if version attribute is specified in response
- * header.
- * @see #isVersionAttributeSpecified()
- */
- public void setVersionAttributeSpecified(boolean value) {
- hasVersionAttribute = value;
- }
- /**
- * @return
true
if cookie version attribute was specified in the
- *
Set-Cookie2
header.
- *
- * @see #setVersionAttributeSpecified
- */
- public boolean isVersionAttributeSpecified() {
- return hasVersionAttribute;
- }
- /**
- * Return a textual representation of the cookie.
- *
- * @return string.
- */
- public String toExternalForm() {
- CookieSpec spec =
- CookiePolicy.getCookieSpec(CookiePolicy.RFC_2965);
- return spec.formatCookie(this);
- }
- /**
- * Comment URL attribute
- */
- private String cookieCommentURL;
- /**
- * Port attribute.
- */
- private int[] cookiePorts;
- /**
- * Discard attribute.
- */
- private boolean discard = false;
- /**
- * Indicates if the set-cookie2 header included a Port attribute for this
- * cookie
- */
- private boolean hasPortAttribute = false;
- /**
- * Indicates if the set-cookie2 header's Port attribute did not have
- * any value.
- */
- private boolean isPortAttributeBlank = false;
- /**
- * Indicates if the set-cookie2 header included a Version attribute
- */
- private boolean hasVersionAttribute = false;
diff --git a/clients/java/src/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java b/clients/java/src/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java
deleted file mode 100644
index e85f43d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java
+++ /dev/null
@@ -1,79 +0,0 @@
- * $HeadURL:https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/java/org/apache/commons/httpclient/cookie/CookieAttributeHandler.java $
- * $Revision:400312 $
- * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
- * ====================================================================
- * 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
- *
RFC 2109 specification is used per default. Other supported specification - * can be chosen when appropriate or set default when desired - *
The following specifications are provided: - *
Supported versions: - *
Cookie management specification must define - *
This method will not perform the validation of the resultant - * {@link Cookie}s
- * - * @see #validate(String, int, String, boolean, Cookie) - * - * @param host the host which sent the Set-Cookie header - * @param port the port which sent the Set-Cookie header - * @param path the path which sent the Set-Cookie header - * @param secure true when the Set-Cookie header - * was received over secure conection - * @param header the Set-Cookie received from the server - * @return an array of Cookie s parsed from the Set-Cookie value - * @throws MalformedCookieException if an exception occurs during parsing - * @throws IllegalArgumentException if an input parameter is illegal - */ - Cookie[] parse(String host, int port, String path, boolean secure, - final String header) - throws MalformedCookieException, IllegalArgumentException; - /** - * Parse the "Set-Cookie" Header into an array of Cookies. - * - *This method will not perform the validation of the resultant - * {@link Cookie}s
- * - * @see #validate(String, int, String, boolean, Cookie) - * - * @param host the host which sent the Set-Cookie header - * @param port the port which sent the Set-Cookie header - * @param path the path which sent the Set-Cookie header - * @param secure true when the Set-Cookie header - * was received over secure conection - * @param header the Set-Cookie received from the server - * @return an array of Cookie s parsed from the header - * @throws MalformedCookieException if an exception occurs during parsing - * @throws IllegalArgumentException if an input parameter is illegal - */ - Cookie[] parse(String host, int port, String path, boolean secure, - final Header header) - throws MalformedCookieException, IllegalArgumentException; - /** - * Parse the cookie attribute and update the corresponsing Cookie - * properties. - * - * @param attribute cookie attribute from the Set-Cookie - * @param cookie the to be updated - * @throws MalformedCookieException if an exception occurs during parsing - * @throws IllegalArgumentException if an input parameter is illegal - */ - void parseAttribute(NameValuePair attribute, Cookie cookie) - throws MalformedCookieException, IllegalArgumentException; - /** - * Validate the cookie according to validation rules defined by the - * cookie specification. - * - * @param host the host from which the {@link Cookie} was received - * @param port the port from which the {@link Cookie} was received - * @param path the path from which the {@link Cookie} was received - * @param secure true when the {@link Cookie} was received - * using a secure connection - * @param cookie the Cookie to validate - * @throws MalformedCookieException if the cookie is invalid - * @throws IllegalArgumentException if an input parameter is illegal - */ - void validate(String host, int port, String path, boolean secure, - final Cookie cookie) - throws MalformedCookieException, IllegalArgumentException; - /** - * Sets the {@link Collection} of date patterns used for parsing. The String patterns must be - * compatible with {@link java.text.SimpleDateFormat}. - * - * @param datepatterns collection of date patterns - */ - void setValidDateFormats(Collection datepatterns); - /** - * Returns the {@link Collection} of date patterns used for parsing. The String patterns are compatible - * with the {@link java.text.SimpleDateFormat}. - * - * @return collection of date patterns - */ - Collection getValidDateFormats(); - /** - * Determines if a Cookie matches a location. - * - * @param host the host to which the request is being submitted - * @param port the port to which the request is being submitted - * @param path the path to which the request is being submitted - * @param secure true if the request is using a secure connection - * @param cookie the Cookie to be matched - * - * @return true if the cookie should be submitted with a request - * with given attributes, false otherwise. - */ - boolean match(String host, int port, String path, boolean secure, - final Cookie cookie); - /** - * Determines which of an array of Cookies matches a location. - * - * @param host the host to which the request is being submitted - * @param port the port to which the request is being submitted - * (currenlty ignored) - * @param path the path to which the request is being submitted - * @param secure true if the request is using a secure protocol - * @param cookies an array of Cookie s to be matched - * - * @return true if the cookie should be submitted with a request - * with given attributes, false otherwise. - */ - Cookie[] match(String host, int port, String path, boolean secure, - final Cookie cookies[]); - /** - * Performs domain-match as defined by the cookie specification. - * @param host The target host. - * @param domain The cookie domain attribute. - * @return true if the specified host matches the given domain. - * - * @since 3.0 - */ - boolean domainMatch(String host, String domain); - /** - * Performs path-match as defined by the cookie specification. - * @param path The target path. - * @param topmostPath The cookie path attribute. - * @return true if the paths match - * - * @since 3.0 - */ - boolean pathMatch(String path, String topmostPath); - /** - * Create a "Cookie" header value for an array of cookies. - * - * @param cookie the cookie to be formatted as string - * @return a string suitable for sending in a "Cookie" header. - */ - String formatCookie(Cookie cookie); - /** - * Create a "Cookie" header value for an array of cookies. - * - * @param cookies the Cookies to be formatted - * @return a string suitable for sending in a Cookie header. - * @throws IllegalArgumentException if an input parameter is illegal - */ - String formatCookies(Cookie[] cookies) throws IllegalArgumentException; - /** - * Create a "Cookie" Header for an array of Cookies. - * - * @param cookies the Cookies format into a Cookie header - * @return a Header for the given Cookies. - * @throws IllegalArgumentException if an input parameter is illegal - */ - Header formatCookieHeader(Cookie[] cookies) throws IllegalArgumentException; - /** - * Create a "Cookie" Header for single Cookie. - * - * @param cookie the Cookie format as a Cookie header - * @return a Cookie header. - * @throws IllegalArgumentException if an input parameter is illegal - */ - Header formatCookieHeader(Cookie cookie) throws IllegalArgumentException; diff --git a/clients/java/src/org/apache/commons/httpclient/cookie/CookieSpecBase.java b/clients/java/src/org/apache/commons/httpclient/cookie/CookieSpecBase.java deleted file mode 100644 index f97f081..0000000 --- a/clients/java/src/org/apache/commons/httpclient/cookie/CookieSpecBase.java +++ /dev/null @@ -1,659 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/CookieSpecBase.java,v 1.28 2004/11/06 19:15:42 mbecke Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *The syntax for the Set-Cookie response header is: - * - *
- * set-cookie = "Set-Cookie:" cookies - * cookies = 1#cookie - * cookie = NAME "=" VALUE * (";" cookie-av) - * NAME = attr - * VALUE = value - * cookie-av = "Comment" "=" value - * | "Domain" "=" value - * | "Max-Age" "=" value - * | "Path" "=" value - * | "Secure" - * | "Version" "=" 1*DIGIT - *- * - * @param host the host from which the Set-Cookie value was - * received - * @param port the port from which the Set-Cookie value was - * received - * @param path the path from which the Set-Cookie value was - * received - * @param secure true when the Set-Cookie value was - * received over secure conection - * @param header the Set-Cookie received from the server - * @return an array of Cookie s parsed from the Set-Cookie value - * @throws MalformedCookieException if an exception occurs during parsing - */ - public Cookie[] parse(String host, int port, String path, - boolean secure, final String header) - throws MalformedCookieException { - LOG.trace("enter CookieSpecBase.parse(" - + "String, port, path, boolean, Header)"); - if (host == null) { - throw new IllegalArgumentException( - "Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException( - "Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException( - "Path of origin may not be null."); - } - if (header == null) { - throw new IllegalArgumentException("Header may not be null."); - } - if (path.trim().equals("")) { - path = PATH_DELIM; - } - host = host.toLowerCase(); - String defaultPath = path; - int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - HeaderElement[] headerElements = null; - boolean isNetscapeCookie = false; - int i1 = header.toLowerCase().indexOf("expires="); - if (i1 != -1) { - i1 += "expires=".length(); - int i2 = header.indexOf(";", i1); - if (i2 == -1) { - i2 = header.length(); - } - try { - DateUtil.parseDate(header.substring(i1, i2), this.datepatterns); - isNetscapeCookie = true; - } catch (DateParseException e) { - // Does not look like a valid expiry date - } - } - if (isNetscapeCookie) { - headerElements = new HeaderElement[] { - new HeaderElement(header.toCharArray()) - }; - } else { - headerElements = HeaderElement.parseElements(header.toCharArray()); - } - Cookie[] cookies = new Cookie[headerElements.length]; - for (int i = 0; i < headerElements.length; i++) { - HeaderElement headerelement = headerElements[i]; - Cookie cookie = null; - try { - cookie = new Cookie(host, - headerelement.getName(), - headerelement.getValue(), - defaultPath, - null, - false); - } catch (IllegalArgumentException e) { - throw new MalformedCookieException(e.getMessage()); - } - // cycle through the parameters - NameValuePair[] parameters = headerelement.getParameters(); - // could be null. In case only a header element and no parameters. - if (parameters != null) { - for (int j = 0; j < parameters.length; j++) { - parseAttribute(parameters[j], cookie); - } - } - cookies[i] = cookie; - } - return cookies; - } - /** - * Parse the "Set-Cookie" {@link Header} into an array of {@link - * Cookie}s. - * - *
The syntax for the Set-Cookie response header is: - * - *
- * set-cookie = "Set-Cookie:" cookies - * cookies = 1#cookie - * cookie = NAME "=" VALUE * (";" cookie-av) - * NAME = attr - * VALUE = value - * cookie-av = "Comment" "=" value - * | "Domain" "=" value - * | "Max-Age" "=" value - * | "Path" "=" value - * | "Secure" - * | "Version" "=" 1*DIGIT - *- * - * @param host the host from which the Set-Cookie header was - * received - * @param port the port from which the Set-Cookie header was - * received - * @param path the path from which the Set-Cookie header was - * received - * @param secure true when the Set-Cookie header was - * received over secure conection - * @param header the Set-Cookie received from the server - * @return an array of Cookie s parsed from the "Set-Cookie" - * header - * @throws MalformedCookieException if an exception occurs during parsing - */ - public Cookie[] parse( - String host, int port, String path, boolean secure, final Header header) - throws MalformedCookieException { - LOG.trace("enter CookieSpecBase.parse(" - + "String, port, path, boolean, String)"); - if (header == null) { - throw new IllegalArgumentException("Header may not be null."); - } - return parse(host, port, path, secure, header.getValue()); - } - /** - * Parse the cookie attribute and update the corresponsing {@link Cookie} - * properties. - * - * @param attribute {@link HeaderElement} cookie attribute from the - * Set- Cookie - * @param cookie {@link Cookie} to be updated - * @throws MalformedCookieException if an exception occurs during parsing - */ - public void parseAttribute( - final NameValuePair attribute, final Cookie cookie) - throws MalformedCookieException { - if (attribute == null) { - throw new IllegalArgumentException("Attribute may not be null."); - } - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null."); - } - final String paramName = attribute.getName().toLowerCase(); - String paramValue = attribute.getValue(); - if (paramName.equals("path")) { - if ((paramValue == null) || (paramValue.trim().equals(""))) { - paramValue = "/"; - } - cookie.setPath(paramValue); - cookie.setPathAttributeSpecified(true); - } else if (paramName.equals("domain")) { - if (paramValue == null) { - throw new MalformedCookieException( - "Missing value for domain attribute"); - } - if (paramValue.trim().equals("")) { - throw new MalformedCookieException( - "Blank value for domain attribute"); - } - cookie.setDomain(paramValue); - cookie.setDomainAttributeSpecified(true); - } else if (paramName.equals("max-age")) { - if (paramValue == null) { - throw new MalformedCookieException( - "Missing value for max-age attribute"); - } - int age; - try { - age = Integer.parseInt(paramValue); - } catch (NumberFormatException e) { - throw new MalformedCookieException ("Invalid max-age " - + "attribute: " + e.getMessage()); - } - cookie.setExpiryDate( - new Date(System.currentTimeMillis() + age * 1000L)); - } else if (paramName.equals("secure")) { - cookie.setSecure(true); - } else if (paramName.equals("comment")) { - cookie.setComment(paramValue); - } else if (paramName.equals("expires")) { - if (paramValue == null) { - throw new MalformedCookieException( - "Missing value for expires attribute"); - } - try { - cookie.setExpiryDate(DateUtil.parseDate(paramValue, this.datepatterns)); - } catch (DateParseException dpe) { - LOG.debug("Error parsing cookie date", dpe); - throw new MalformedCookieException( - "Unable to parse expiration date parameter: " - + paramValue); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Unrecognized cookie attribute: " - + attribute.toString()); - } - } - } - public Collection getValidDateFormats() { - return this.datepatterns; - } - public void setValidDateFormats(final Collection datepatterns) { - this.datepatterns = datepatterns; - } - /** - * Performs most common {@link Cookie} validation - * - * @param host the host from which the {@link Cookie} was received - * @param port the port from which the {@link Cookie} was received - * @param path the path from which the {@link Cookie} was received - * @param secure true when the {@link Cookie} was received using a - * secure connection - * @param cookie The cookie to validate. - * @throws MalformedCookieException if an exception occurs during - * validation - */ - public void validate(String host, int port, String path, - boolean secure, final Cookie cookie) - throws MalformedCookieException { - LOG.trace("enter CookieSpecBase.validate(" - + "String, port, path, boolean, Cookie)"); - if (host == null) { - throw new IllegalArgumentException( - "Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException( - "Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException( - "Path of origin may not be null."); - } - if (path.trim().equals("")) { - path = PATH_DELIM; - } - host = host.toLowerCase(); - // check version - if (cookie.getVersion() < 0) { - throw new MalformedCookieException ("Illegal version number " - + cookie.getValue()); - } - // security check... we musn't allow the server to give us an - // invalid domain scope - // Validate the cookies domain attribute. NOTE: Domains without - // any dots are allowed to support hosts on private LANs that don't - // have DNS names. Since they have no dots, to domain-match the - // request-host and domain must be identical for the cookie to sent - // back to the origin-server. - if (host.indexOf(".") >= 0) { - // Not required to have at least two dots. RFC 2965. - // A Set-Cookie2 with Domain=ajax.com will be accepted. - // domain must match host - if (!host.endsWith(cookie.getDomain())) { - String s = cookie.getDomain(); - if (s.startsWith(".")) { - s = s.substring(1, s.length()); - } - if (!host.equals(s)) { - throw new MalformedCookieException( - "Illegal domain attribute \"" + cookie.getDomain() - + "\". Domain of origin: \"" + host + "\""); - } - } - } else { - if (!host.equals(cookie.getDomain())) { - throw new MalformedCookieException( - "Illegal domain attribute \"" + cookie.getDomain() - + "\". Domain of origin: \"" + host + "\""); - } - } - // another security check... we musn't allow the server to give us a - // cookie that doesn't match this path - if (!path.startsWith(cookie.getPath())) { - throw new MalformedCookieException( - "Illegal path attribute \"" + cookie.getPath() - + "\". Path of origin: \"" + path + "\""); - } - } - /** - * Return true if the cookie should be submitted with a request - * with given attributes, false otherwise. - * @param host the host to which the request is being submitted - * @param port the port to which the request is being submitted (ignored) - * @param path the path to which the request is being submitted - * @param secure true if the request is using a secure connection - * @param cookie {@link Cookie} to be matched - * @return true if the cookie matches the criterium - */ - public boolean match(String host, int port, String path, - boolean secure, final Cookie cookie) { - LOG.trace("enter CookieSpecBase.match(" - + "String, int, String, boolean, Cookie"); - if (host == null) { - throw new IllegalArgumentException( - "Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException( - "Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException( - "Path of origin may not be null."); - } - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (path.trim().equals("")) { - path = PATH_DELIM; - } - host = host.toLowerCase(); - if (cookie.getDomain() == null) { - LOG.warn("Invalid cookie state: domain not specified"); - return false; - } - if (cookie.getPath() == null) { - LOG.warn("Invalid cookie state: path not specified"); - return false; - } - return - // only add the cookie if it hasn't yet expired - (cookie.getExpiryDate() == null - || cookie.getExpiryDate().after(new Date())) - // and the domain pattern matches - && (domainMatch(host, cookie.getDomain())) - // and the path is null or matching - && (pathMatch(path, cookie.getPath())) - // and if the secure flag is set, only if the request is - // actually secure - && (cookie.getSecure() ? secure : true); - } - /** - * Performs domain-match as implemented in common browsers. - * @param host The target host. - * @param domain The cookie domain attribute. - * @return true if the specified host matches the given domain. - */ - public boolean domainMatch(final String host, String domain) { - if (host.equals(domain)) { - return true; - } - if (!domain.startsWith(".")) { - domain = "." + domain; - } - return host.endsWith(domain) || host.equals(domain.substring(1)); - } - /** - * Performs path-match as implemented in common browsers. - * @param path The target path. - * @param topmostPath The cookie path attribute. - * @return true if the paths match - */ - public boolean pathMatch(final String path, final String topmostPath) { - boolean match = path.startsWith (topmostPath); - // if there is a match and these values are not exactly the same we have - // to make sure we're not matcing "/foobar" and "/foo" - if (match && path.length() != topmostPath.length()) { - if (!topmostPath.endsWith(PATH_DELIM)) { - match = (path.charAt(topmostPath.length()) == PATH_DELIM_CHAR); - } - } - return match; - } - /** - * Return an array of {@link Cookie}s that should be submitted with a - * request with given attributes, false otherwise. - * @param host the host to which the request is being submitted - * @param port the port to which the request is being submitted (currently - * ignored) - * @param path the path to which the request is being submitted - * @param secure true if the request is using a secure protocol - * @param cookies an array of Cookie s to be matched - * @return an array of Cookie s matching the criterium - */ - public Cookie[] match(String host, int port, String path, - boolean secure, final Cookie cookies[]) { - LOG.trace("enter CookieSpecBase.match(" - + "String, int, String, boolean, Cookie[])"); - if (cookies == null) { - return null; - } - List matching = new LinkedList(); - for (int i = 0; i < cookies.length; i++) { - if (match(host, port, path, secure, cookies[i])) { - addInPathOrder(matching, cookies[i]); - } - } - return (Cookie[]) matching.toArray(new Cookie[matching.size()]); - } - /** - * Adds the given cookie into the given list in descending path order. That - * is, more specific path to least specific paths. This may not be the - * fastest algorythm, but it'll work OK for the small number of cookies - * we're generally dealing with. - * - * @param list - the list to add the cookie to - * @param addCookie - the Cookie to add to list - */ - private static void addInPathOrder(List list, Cookie addCookie) { - int i = 0; - for (i = 0; i < list.size(); i++) { - Cookie c = (Cookie) list.get(i); - if (addCookie.compare(addCookie, c) > 0) { - break; - } - } - list.add(i, addCookie); - } - /** - * Return a string suitable for sending in a "Cookie" header - * @param cookie a {@link Cookie} to be formatted as string - * @return a string suitable for sending in a "Cookie" header. - */ - public String formatCookie(Cookie cookie) { - LOG.trace("enter CookieSpecBase.formatCookie(Cookie)"); - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - StringBuffer buf = new StringBuffer(); - buf.append(cookie.getName()); - buf.append("="); - String s = cookie.getValue(); - if (s != null) { - buf.append(s); - } - return buf.toString(); - } - /** - * Create a "Cookie" header value containing all {@link Cookie}s in - * cookies suitable for sending in a "Cookie" header - * @param cookies an array of {@link Cookie}s to be formatted - * @return a string suitable for sending in a Cookie header. - * @throws IllegalArgumentException if an input parameter is illegal - */ - public String formatCookies(Cookie[] cookies) - throws IllegalArgumentException { - LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])"); - if (cookies == null) { - throw new IllegalArgumentException("Cookie array may not be null"); - } - if (cookies.length == 0) { - throw new IllegalArgumentException("Cookie array may not be empty"); - } - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < cookies.length; i++) { - if (i > 0) { - buffer.append("; "); - } - buffer.append(formatCookie(cookies[i])); - } - return buffer.toString(); - } - /** - * Create a "Cookie" {@link Header} containing all {@link Cookie}s - * in cookies . - * @param cookies an array of {@link Cookie}s to be formatted as a " - * Cookie" header - * @return a "Cookie" {@link Header}. - */ - public Header formatCookieHeader(Cookie[] cookies) { - LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie[])"); - return new Header("Cookie", formatCookies(cookies)); - } - /** - * Create a "Cookie" {@link Header} containing the {@link Cookie}. - * @param cookie Cookie s to be formatted as a Cookie - * header - * @return a Cookie header. - */ - public Header formatCookieHeader(Cookie cookie) { - LOG.trace("enter CookieSpecBase.formatCookieHeader(Cookie)"); - return new Header("Cookie", formatCookie(cookie)); - } diff --git a/clients/java/src/org/apache/commons/httpclient/cookie/CookieVersionSupport.java b/clients/java/src/org/apache/commons/httpclient/cookie/CookieVersionSupport.java deleted file mode 100644 index a4c044f..0000000 --- a/clients/java/src/org/apache/commons/httpclient/cookie/CookieVersionSupport.java +++ /dev/null @@ -1,48 +0,0 @@ - * $Header: $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
null
- */
- public Collection getValidDateFormats() {
- return null;
- }
- /**
- * Does nothing.
- */
- public void setValidDateFormats(Collection datepatterns) {
- }
- /**
- * @return
null
- */
- public String formatCookie(Cookie cookie) {
- return null;
- }
- /**
- * @return
null
- */
- public Header formatCookieHeader(Cookie cookie) throws IllegalArgumentException {
- return null;
- }
- /**
- * @return
null
- */
- public Header formatCookieHeader(Cookie[] cookies) throws IllegalArgumentException {
- return null;
- }
- /**
- * @return
null
- */
- public String formatCookies(Cookie[] cookies) throws IllegalArgumentException {
- return null;
- }
- /**
- * @return
false
- */
- public boolean match(String host, int port, String path, boolean secure, Cookie cookie) {
- return false;
- }
- /**
- * Returns an empty {@link Cookie cookie} array. All parameters are ignored.
- */
- public Cookie[] match(String host, int port, String path, boolean secure, Cookie[] cookies) {
- return new Cookie[0];
- }
- /**
- * Returns an empty {@link Cookie cookie} array. All parameters are ignored.
- */
- public Cookie[] parse(String host, int port, String path, boolean secure, Header header)
- throws MalformedCookieException, IllegalArgumentException {
- return new Cookie[0];
- }
- /**
- * Does nothing.
- */
- public void parseAttribute(NameValuePair attribute, Cookie cookie)
- throws MalformedCookieException, IllegalArgumentException {
- }
- /**
- * Does nothing.
- */
- public void validate(String host, int port, String path, boolean secure, Cookie cookie)
- throws MalformedCookieException, IllegalArgumentException {
- }
- /**
- * @return
false
- */
- public boolean domainMatch(final String host, final String domain) {
- return false;
- }
- /**
- * @return
false
- */
- public boolean pathMatch(final String path, final String topmostPath) {
- return false;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/cookie/MalformedCookieException.java b/clients/java/src/org/apache/commons/httpclient/cookie/MalformedCookieException.java
deleted file mode 100644
index f0658d9..0000000
--- a/clients/java/src/org/apache/commons/httpclient/cookie/MalformedCookieException.java
+++ /dev/null
@@ -1,73 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/MalformedCookieException.java,v 1.8 2004/05/13 04:02:00 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
Netscape cookie draft specific cookie management functions - * @author B.C. Holmes - * @author Park, Sung-Gu - * @author Doug Sale - * @author Rod Waldhoff - * @author dIon Gillard - * @author Sean C. Sullivan - * @author John Evans - * @author Marc A. Saegesser - * @author Oleg Kalnichevski - * @author Mike Bowler - * @since 2.0 -public class NetscapeDraftSpec extends CookieSpecBase { - /** Default constructor */ - public NetscapeDraftSpec() { - super(); - } - /** - * Parses the Set-Cookie value into an array of Cookie s. - * - *
Syntax of the Set-Cookie HTTP Response Header:
- * - *This is the format a CGI script would use to add to - * the HTTP headers a new piece of data which is to be stored by - * the client for later retrieval.
- * - *- * Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure - *- * - *
Please note that Netscape draft specification does not fully - * conform to the HTTP header format. Netscape draft does not specify - * whether multiple cookies may be sent in one header. Hence, comma - * character may be present in unquoted cookie value or unquoted - * parameter value.
- * - * @link http://wp.netscape.com/newsref/std/cookie_spec.html - * - * @param host the host from which the Set-Cookie value was - * received - * @param port the port from which the Set-Cookie value was - * received - * @param path the path from which the Set-Cookie value was - * received - * @param secure true when the Set-Cookie value was - * received over secure conection - * @param header the Set-Cookie received from the server - * @return an array of Cookie s parsed from the Set-Cookie value - * @throws MalformedCookieException if an exception occurs during parsing - * - * @since 3.0 - */ - public Cookie[] parse(String host, int port, String path, - boolean secure, final String header) - throws MalformedCookieException { - LOG.trace("enter NetscapeDraftSpec.parse(String, port, path, boolean, Header)"); - if (host == null) { - throw new IllegalArgumentException("Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException("Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException("Path of origin may not be null."); - } - if (header == null) { - throw new IllegalArgumentException("Header may not be null."); - } - if (path.trim().equals("")) { - path = PATH_DELIM; - } - host = host.toLowerCase(); - String defaultPath = path; - int lastSlashIndex = defaultPath.lastIndexOf(PATH_DELIM); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - HeaderElement headerelement = new HeaderElement(header.toCharArray()); - Cookie cookie = new Cookie(host, - headerelement.getName(), - headerelement.getValue(), - defaultPath, - null, - false); - // cycle through the parameters - NameValuePair[] parameters = headerelement.getParameters(); - // could be null. In case only a header element and no parameters. - if (parameters != null) { - for (int j = 0; j < parameters.length; j++) { - parseAttribute(parameters[j], cookie); - } - } - return new Cookie[] {cookie}; - } - /** - * Parse the cookie attribute and update the corresponsing {@link Cookie} - * properties as defined by the Netscape draft specification - * - * @param attribute {@link NameValuePair} cookie attribute from the - * Set- Cookie - * @param cookie {@link Cookie} to be updated - * @throws MalformedCookieException if an exception occurs during parsing - */ - public void parseAttribute( - final NameValuePair attribute, final Cookie cookie) - throws MalformedCookieException { - if (attribute == null) { - throw new IllegalArgumentException("Attribute may not be null."); - } - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null."); - } - final String paramName = attribute.getName().toLowerCase(); - final String paramValue = attribute.getValue(); - if (paramName.equals("expires")) { - if (paramValue == null) { - throw new MalformedCookieException( - "Missing value for expires attribute"); - } - try { - DateFormat expiryFormat = new SimpleDateFormat( - "EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); - Date date = expiryFormat.parse(paramValue); - cookie.setExpiryDate(date); - } catch (ParseException e) { - throw new MalformedCookieException("Invalid expires " - + "attribute: " + e.getMessage()); - } - } else { - super.parseAttribute(attribute, cookie); - } - } - /** - * Performs domain-match as described in the Netscape draft. - * @param host The target host. - * @param domain The cookie domain attribute. - * @return true if the specified host matches the given domain. - */ - public boolean domainMatch(final String host, final String domain) { - return host.endsWith(domain); - } - /** - * Performs Netscape draft compliant {@link Cookie} validation - * - * @param host the host from which the {@link Cookie} was received - * @param port the port from which the {@link Cookie} was received - * @param path the path from which the {@link Cookie} was received - * @param secure true when the {@link Cookie} was received - * using a secure connection - * @param cookie The cookie to validate. - * @throws MalformedCookieException if an exception occurs during - * validation - */ - public void validate(String host, int port, String path, - boolean secure, final Cookie cookie) - throws MalformedCookieException { - LOG.trace("enterNetscapeDraftCookieProcessor " - + "RCF2109CookieProcessor.validate(Cookie)"); - // Perform generic validation - super.validate(host, port, path, secure, cookie); - // Perform Netscape Cookie draft specific validation - if (host.indexOf(".") >= 0) { - int domainParts = new StringTokenizer(cookie.getDomain(), ".") - .countTokens(); - if (isSpecialDomain(cookie.getDomain())) { - if (domainParts < 2) { - throw new MalformedCookieException("Domain attribute \"" - + cookie.getDomain() - + "\" violates the Netscape cookie specification for " - + "special domains"); - } - } else { - if (domainParts < 3) { - throw new MalformedCookieException("Domain attribute \"" - + cookie.getDomain() - + "\" violates the Netscape cookie specification"); - } - } - } - } - /** - * Checks if the given domain is in one of the seven special - * top level domains defined by the Netscape cookie specification. - * @param domain The domain. - * @return True if the specified domain is "special" - */ - private static boolean isSpecialDomain(final String domain) { - final String ucDomain = domain.toUpperCase(); - if (ucDomain.endsWith(".COM") - || ucDomain.endsWith(".EDU") - || ucDomain.endsWith(".NET") - || ucDomain.endsWith(".GOV") - || ucDomain.endsWith(".MIL") - || ucDomain.endsWith(".ORG") - || ucDomain.endsWith(".INT")) { - return true; - } - return false; - } diff --git a/clients/java/src/org/apache/commons/httpclient/cookie/RFC2109Spec.java b/clients/java/src/org/apache/commons/httpclient/cookie/RFC2109Spec.java deleted file mode 100644 index 829c740..0000000 --- a/clients/java/src/org/apache/commons/httpclient/cookie/RFC2109Spec.java +++ /dev/null @@ -1,292 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/cookie/RFC2109Spec.java,v 1.21 2004/06/05 16:49:20 olegk Exp $ - * $Revision: 507134 $ - * $Date: 2007-02-13 19:18:05 +0100 (Tue, 13 Feb 2007) $ - * ==================================================================== - * 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 - *
RFC 2109 specific cookie management functions
- * @author B.C. Holmes
- * @author
Park, Sung-Gu
- * @author
Doug Sale
- * @author Rod Waldhoff
- * @author dIon Gillard
- * @author Sean C. Sullivan
- * @author
John Evans
- * @author Marc A. Saegesser
- * @author
Oleg Kalnichevski
- * @author
Mike Bowler
- * @since 2.0
-public class RFC2109Spec extends CookieSpecBase {
- private final ParameterFormatter formatter;
- /**
- * Cookie Response Header name for cookies processed
- * by this spec.
- */
- public final static String SET_COOKIE_KEY = "set-cookie";
- /** Default constructor */
- public RFC2109Spec() {
- super();
- this.formatter = new ParameterFormatter();
- this.formatter.setAlwaysUseQuotes(true);
- }
- /**
- * Parse RFC 2109 specific cookie attribute and update the corresponsing
- * {@link Cookie} properties.
- *
- * @param attribute {@link NameValuePair} cookie attribute from the
- *
Set- Cookie
- * @param cookie {@link Cookie} to be updated
- * @throws MalformedCookieException if an exception occurs during parsing
- */
- public void parseAttribute(
- final NameValuePair attribute, final Cookie cookie)
- throws MalformedCookieException {
- if (attribute == null) {
- throw new IllegalArgumentException("Attribute may not be null.");
- }
- if (cookie == null) {
- throw new IllegalArgumentException("Cookie may not be null.");
- }
- final String paramName = attribute.getName().toLowerCase();
- final String paramValue = attribute.getValue();
- if (paramName.equals("path")) {
- if (paramValue == null) {
- throw new MalformedCookieException(
- "Missing value for path attribute");
- }
- if (paramValue.trim().equals("")) {
- throw new MalformedCookieException(
- "Blank value for path attribute");
- }
- cookie.setPath(paramValue);
- cookie.setPathAttributeSpecified(true);
- } else if (paramName.equals("version")) {
- if (paramValue == null) {
- throw new MalformedCookieException(
- "Missing value for version attribute");
- }
- try {
- cookie.setVersion(Integer.parseInt(paramValue));
- } catch (NumberFormatException e) {
- throw new MalformedCookieException("Invalid version: "
- + e.getMessage());
- }
- } else {
- super.parseAttribute(attribute, cookie);
- }
- }
- /**
- * Performs RFC 2109 compliant {@link Cookie} validation
- *
- * @param host the host from which the {@link Cookie} was received
- * @param port the port from which the {@link Cookie} was received
- * @param path the path from which the {@link Cookie} was received
- * @param secure
true
when the {@link Cookie} was received using a
- * secure connection
- * @param cookie The cookie to validate
- * @throws MalformedCookieException if an exception occurs during
- * validation
- */
- public void validate(String host, int port, String path,
- boolean secure, final Cookie cookie) throws MalformedCookieException {
- LOG.trace("enter RFC2109Spec.validate(String, int, String, "
- + "boolean, Cookie)");
- // Perform generic validation
- super.validate(host, port, path, secure, cookie);
- // Perform RFC 2109 specific validation
- if (cookie.getName().indexOf(' ') != -1) {
- throw new MalformedCookieException("Cookie name may not contain blanks");
- }
- if (cookie.getName().startsWith("$")) {
- throw new MalformedCookieException("Cookie name may not start with $");
- }
- if (cookie.isDomainAttributeSpecified()
- && (!cookie.getDomain().equals(host))) {
- // domain must start with dot
- if (!cookie.getDomain().startsWith(".")) {
- throw new MalformedCookieException("Domain attribute \""
- + cookie.getDomain()
- + "\" violates RFC 2109: domain must start with a dot");
- }
- // domain must have at least one embedded dot
- int dotIndex = cookie.getDomain().indexOf('.', 1);
- if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) {
- throw new MalformedCookieException("Domain attribute \""
- + cookie.getDomain()
- + "\" violates RFC 2109: domain must contain an embedded dot");
- }
- host = host.toLowerCase();
- if (!host.endsWith(cookie.getDomain())) {
- throw new MalformedCookieException(
- "Illegal domain attribute \"" + cookie.getDomain()
- + "\". Domain of origin: \"" + host + "\"");
- }
- // host minus domain may not contain any dots
- String hostWithoutDomain = host.substring(0, host.length()
- - cookie.getDomain().length());
- if (hostWithoutDomain.indexOf('.') != -1) {
- throw new MalformedCookieException("Domain attribute \""
- + cookie.getDomain()
- + "\" violates RFC 2109: host minus domain may not contain any dots");
- }
- }
- }
- /**
- * Performs domain-match as defined by the RFC2109.
- * @param host The target host.
- * @param domain The cookie domain attribute.
- * @return true if the specified host matches the given domain.
- *
- * @since 3.0
- */
- public boolean domainMatch(String host, String domain) {
- boolean match = host.equals(domain)
- || (domain.startsWith(".") && host.endsWith(domain));
- return match;
- }
- /**
- * Return a name/value string suitable for sending in a
"Cookie"
- * header as defined in RFC 2109 for backward compatibility with cookie
- * version 0
- * @param buffer The string buffer to use for output
- * @param param The parameter.
- * @param version The cookie version
- */
- private void formatParam(final StringBuffer buffer, final NameValuePair param, int version) {
- if (version < 1) {
- buffer.append(param.getName());
- buffer.append("=");
- if (param.getValue() != null) {
- buffer.append(param.getValue());
- }
- } else {
- this.formatter.format(buffer, param);
- }
- }
- /**
- * Return a string suitable for sending in a
"Cookie"
header
- * as defined in RFC 2109 for backward compatibility with cookie version 0
- * @param buffer The string buffer to use for output
- * @param cookie The {@link Cookie} to be formatted as string
- * @param version The version to use.
- */
- private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) {
- String value = cookie.getValue();
- if (value == null) {
- value = "";
- }
- formatParam(buffer, new NameValuePair(cookie.getName(), value), version);
- if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) {
- buffer.append("; ");
- formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version);
- }
- if ((cookie.getDomain() != null)
- && cookie.isDomainAttributeSpecified()) {
- buffer.append("; ");
- formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version);
- }
- }
- /**
- * Return a string suitable for sending in a
"Cookie"
header as
- * defined in RFC 2109
- * @param cookie a {@link Cookie} to be formatted as string
- * @return a string suitable for sending in a
"Cookie"
header.
- */
- public String formatCookie(Cookie cookie) {
- LOG.trace("enter RFC2109Spec.formatCookie(Cookie)");
- if (cookie == null) {
- throw new IllegalArgumentException("Cookie may not be null");
- }
- int version = cookie.getVersion();
- StringBuffer buffer = new StringBuffer();
- formatParam(buffer,
- new NameValuePair("$Version", Integer.toString(version)),
- version);
- buffer.append("; ");
- formatCookieAsVer(buffer, cookie, version);
- return buffer.toString();
- }
- /**
- * Create a RFC 2109 compliant
"Cookie"
header value containing all
- * {@link Cookie}s in
cookies
suitable for sending in a
"Cookie"
- *
header
- * @param cookies an array of {@link Cookie}s to be formatted
- * @return a string suitable for sending in a Cookie header.
- */
- public String formatCookies(Cookie[] cookies) {
- LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
- int version = Integer.MAX_VALUE;
- // Pick the lowerest common denominator
- for (int i = 0; i < cookies.length; i++) {
- Cookie cookie = cookies[i];
- if (cookie.getVersion() < version) {
- version = cookie.getVersion();
- }
- }
- final StringBuffer buffer = new StringBuffer();
- formatParam(buffer,
- new NameValuePair("$Version", Integer.toString(version)),
- version);
- for (int i = 0; i < cookies.length; i++) {
- buffer.append("; ");
- formatCookieAsVer(buffer, cookies[i], version);
- }
- return buffer.toString();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/cookie/RFC2965Spec.java b/clients/java/src/org/apache/commons/httpclient/cookie/RFC2965Spec.java
deleted file mode 100644
index e1a4559..0000000
--- a/clients/java/src/org/apache/commons/httpclient/cookie/RFC2965Spec.java
+++ /dev/null
@@ -1,1118 +0,0 @@
- * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/cookie/RFC2965Spec.java $
- * $Revision: 507134 $
- * $Date: 2007-02-13 19:18:05 +0100 (Tue, 13 Feb 2007) $
- * ====================================================================
- * 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
- *
RFC 2965 specific cookie management functions.
- * @author [email protected] (Samit Jain) - * @since 3.1 -public class RFC2965Spec extends CookieSpecBase implements CookieVersionSupport { - private static final Comparator PATH_COMPOARATOR = new CookiePathComparator(); - /** - * Cookie Response Header name for cookies processed - * by this spec. - */ - public final static String SET_COOKIE2_KEY = "set-cookie2"; - /** - * used for formatting RFC 2956 style cookies - */ - private final ParameterFormatter formatter; - /** - * Stores the list of attribute handlers - */ - private final List attribHandlerList; - /** - * Stores attribute name -> attribute handler mappings - */ - private final Map attribHandlerMap; - /** - * Fallback cookie spec (RFC 2109) - */ - private final CookieSpec rfc2109; - /** - * Default constructor - * */ - public RFC2965Spec() { - super(); - this.formatter = new ParameterFormatter(); - this.formatter.setAlwaysUseQuotes(true); - this.attribHandlerMap = new HashMap(10); - this.attribHandlerList = new ArrayList(10); - this.rfc2109 = new RFC2109Spec(); - registerAttribHandler(Cookie2.PATH, new Cookie2PathAttributeHandler()); - registerAttribHandler(Cookie2.DOMAIN, new Cookie2DomainAttributeHandler()); - registerAttribHandler(Cookie2.PORT, new Cookie2PortAttributeHandler()); - registerAttribHandler(Cookie2.MAXAGE, new Cookie2MaxageAttributeHandler()); - registerAttribHandler(Cookie2.SECURE, new CookieSecureAttributeHandler()); - registerAttribHandler(Cookie2.COMMENT, new CookieCommentAttributeHandler()); - registerAttribHandler(Cookie2.COMMENTURL, new CookieCommentUrlAttributeHandler()); - registerAttribHandler(Cookie2.DISCARD, new CookieDiscardAttributeHandler()); - registerAttribHandler(Cookie2.VERSION, new Cookie2VersionAttributeHandler()); - } - protected void registerAttribHandler( - final String name, final CookieAttributeHandler handler) { - if (name == null) { - throw new IllegalArgumentException("Attribute name may not be null"); - } - if (handler == null) { - throw new IllegalArgumentException("Attribute handler may not be null"); - } - if (!this.attribHandlerList.contains(handler)) { - this.attribHandlerList.add(handler); - } - this.attribHandlerMap.put(name, handler); - } - /** - * Finds an attribute handler {@link CookieAttributeHandler} for the - * given attribute. Returns null if no attribute handler is - * found for the specified attribute. - * - * @param name attribute name. e.g. Domain, Path, etc. - * @return an attribute handler or null - */ - protected CookieAttributeHandler findAttribHandler(final String name) { - return (CookieAttributeHandler) this.attribHandlerMap.get(name); - } - /** - * Gets attribute handler {@link CookieAttributeHandler} for the - * given attribute. - * - * @param name attribute name. e.g. Domain, Path, etc. - * @throws IllegalStateException if handler not found for the - * specified attribute. - */ - protected CookieAttributeHandler getAttribHandler(final String name) { - CookieAttributeHandler handler = findAttribHandler(name); - if (handler == null) { - throw new IllegalStateException("Handler not registered for " + - name + " attribute."); - } else { - return handler; - } - } - protected Iterator getAttribHandlerIterator() { - return this.attribHandlerList.iterator(); - } - /** - * Parses the Set-Cookie2 value into an array of Cookie s. - * - *The syntax for the Set-Cookie2 response header is: - * - *
- * set-cookie = "Set-Cookie2:" cookies - * cookies = 1#cookie - * cookie = NAME "=" VALUE * (";" cookie-av) - * NAME = attr - * VALUE = value - * cookie-av = "Comment" "=" value - * | "CommentURL" "=" http_URL - * | "Discard" - * | "Domain" "=" value - * | "Max-Age" "=" value - * | "Path" "=" value - * | "Port" [ "=" portlist ] - * | "Secure" - * | "Version" "=" 1*DIGIT - * portlist = 1#portnum - * portnum = 1*DIGIT - *- * - * @param host the host from which the Set-Cookie2 value was - * received - * @param port the port from which the Set-Cookie2 value was - * received - * @param path the path from which the Set-Cookie2 value was - * received - * @param secure true when the Set-Cookie2 value was - * received over secure conection - * @param header the Set-Cookie2 Header received from the server - * @return an array of Cookie s parsed from the Set-Cookie2 value - * @throws MalformedCookieException if an exception occurs during parsing - */ - public Cookie[] parse( - String host, int port, String path, boolean secure, final Header header) - throws MalformedCookieException { - LOG.trace("enter RFC2965.parse(" - + "String, int, String, boolean, Header)"); - if (header == null) { - throw new IllegalArgumentException("Header may not be null."); - } - if (header.getName() == null) { - throw new IllegalArgumentException("Header name may not be null."); - } - if (header.getName().equalsIgnoreCase(SET_COOKIE2_KEY)) { - // parse cookie2 cookies - return parse(host, port, path, secure, header.getValue()); - } else if (header.getName().equalsIgnoreCase(RFC2109Spec.SET_COOKIE_KEY)) { - // delegate parsing of old-style cookies to rfc2109Spec - return this.rfc2109.parse(host, port, path, secure, header.getValue()); - } else { - throw new MalformedCookieException("Header name is not valid. " + - "RFC 2965 supports \"set-cookie\" " + - "and \"set-cookie2\" headers."); - } - } - /** - * @see #parse(String, int, String, boolean, org.apache.commons.httpclient.Header) - */ - public Cookie[] parse(String host, int port, String path, - boolean secure, final String header) - throws MalformedCookieException { - LOG.trace("enter RFC2965Spec.parse(" - + "String, int, String, boolean, String)"); - // before we do anything, lets check validity of arguments - if (host == null) { - throw new IllegalArgumentException( - "Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException( - "Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException( - "Path of origin may not be null."); - } - if (header == null) { - throw new IllegalArgumentException("Header may not be null."); - } - if (path.trim().equals("")) { - path = PATH_DELIM; - } - host = getEffectiveHost(host); - HeaderElement[] headerElements = - HeaderElement.parseElements(header.toCharArray()); - List cookies = new LinkedList(); - for (int i = 0; i < headerElements.length; i++) { - HeaderElement headerelement = headerElements[i]; - Cookie2 cookie = null; - try { - cookie = new Cookie2(host, - headerelement.getName(), - headerelement.getValue(), - path, - null, - false, - new int[] {port}); - } catch (IllegalArgumentException ex) { - throw new MalformedCookieException(ex.getMessage()); - } - NameValuePair[] parameters = headerelement.getParameters(); - // could be null. In case only a header element and no parameters. - if (parameters != null) { - // Eliminate duplicate attribues. The first occurence takes precedence - Map attribmap = new HashMap(parameters.length); - for (int j = parameters.length - 1; j >= 0; j--) { - NameValuePair param = parameters[j]; - attribmap.put(param.getName().toLowerCase(), param); - } - for (Iterator it = attribmap.entrySet().iterator(); it.hasNext(); ) { - Map.Entry entry = (Map.Entry) it.next(); - parseAttribute((NameValuePair) entry.getValue(), cookie); - } - } - cookies.add(cookie); - // cycle through the parameters - } - return (Cookie[]) cookies.toArray(new Cookie[cookies.size()]); - } - /** - * Parse RFC 2965 specific cookie attribute and update the corresponsing - * {@link org.apache.commons.httpclient.Cookie} properties. - * - * @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the - * Set-Cookie2 header. - * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated - * @throws MalformedCookieException if an exception occurs during parsing - */ - public void parseAttribute( - final NameValuePair attribute, final Cookie cookie) - throws MalformedCookieException { - if (attribute == null) { - throw new IllegalArgumentException("Attribute may not be null."); - } - if (attribute.getName() == null) { - throw new IllegalArgumentException("Attribute Name may not be null."); - } - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null."); - } - final String paramName = attribute.getName().toLowerCase(); - final String paramValue = attribute.getValue(); - CookieAttributeHandler handler = findAttribHandler(paramName); - if (handler == null) { - // ignore unknown attribute-value pairs - if (LOG.isDebugEnabled()) - LOG.debug("Unrecognized cookie attribute: " + - attribute.toString()); - } else { - handler.parse(cookie, paramValue); - } - } - /** - * Performs RFC 2965 compliant {@link org.apache.commons.httpclient.Cookie} validation - * - * @param host the host from which the {@link org.apache.commons.httpclient.Cookie} was received - * @param port the port from which the {@link org.apache.commons.httpclient.Cookie} was received - * @param path the path from which the {@link org.apache.commons.httpclient.Cookie} was received - * @param secure true when the {@link org.apache.commons.httpclient.Cookie} was received using a - * secure connection - * @param cookie The cookie to validate - * @throws MalformedCookieException if an exception occurs during - * validation - */ - public void validate(final String host, int port, final String path, - boolean secure, final Cookie cookie) - throws MalformedCookieException { - LOG.trace("enter RFC2965Spec.validate(String, int, String, " - + "boolean, Cookie)"); - if (cookie instanceof Cookie2) { - if (cookie.getName().indexOf(' ') != -1) { - throw new MalformedCookieException("Cookie name may not contain blanks"); - } - if (cookie.getName().startsWith("$")) { - throw new MalformedCookieException("Cookie name may not start with $"); - } - CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); - for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) { - CookieAttributeHandler handler = (CookieAttributeHandler) i.next(); - handler.validate(cookie, origin); - } - } else { - // old-style cookies are validated according to the old rules - this.rfc2109.validate(host, port, path, secure, cookie); - } - } - /** - * Return true if the cookie should be submitted with a request - * with given attributes, false otherwise. - * @param host the host to which the request is being submitted - * @param port the port to which the request is being submitted (ignored) - * @param path the path to which the request is being submitted - * @param secure true if the request is using a secure connection - * @return true if the cookie matches the criterium - */ - public boolean match(String host, int port, String path, - boolean secure, final Cookie cookie) { - LOG.trace("enter RFC2965.match(" - + "String, int, String, boolean, Cookie"); - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (cookie instanceof Cookie2) { - // check if cookie has expired - if (cookie.isPersistent() && cookie.isExpired()) { - return false; - } - CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); - for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) { - CookieAttributeHandler handler = (CookieAttributeHandler) i.next(); - if (!handler.match(cookie, origin)) { - return false; - } - } - return true; - } else { - // old-style cookies are matched according to the old rules - return this.rfc2109.match(host, port, path, secure, cookie); - } - } - private void doFormatCookie2(final Cookie2 cookie, final StringBuffer buffer) { - String name = cookie.getName(); - String value = cookie.getValue(); - if (value == null) { - value = ""; - } - this.formatter.format(buffer, new NameValuePair(name, value)); - // format domain attribute - if (cookie.getDomain() != null && cookie.isDomainAttributeSpecified()) { - buffer.append("; "); - this.formatter.format(buffer, new NameValuePair("$Domain", cookie.getDomain())); - } - // format path attribute - if ((cookie.getPath() != null) && (cookie.isPathAttributeSpecified())) { - buffer.append("; "); - this.formatter.format(buffer, new NameValuePair("$Path", cookie.getPath())); - } - // format port attribute - if (cookie.isPortAttributeSpecified()) { - String portValue = ""; - if (!cookie.isPortAttributeBlank()) { - portValue = createPortAttribute(cookie.getPorts()); - } - buffer.append("; "); - this.formatter.format(buffer, new NameValuePair("$Port", portValue)); - } - } - /** - * Return a string suitable for sending in a "Cookie" header as - * defined in RFC 2965 - * @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string - * @return a string suitable for sending in a "Cookie" header. - */ - public String formatCookie(final Cookie cookie) { - LOG.trace("enter RFC2965Spec.formatCookie(Cookie)"); - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (cookie instanceof Cookie2) { - Cookie2 cookie2 = (Cookie2) cookie; - int version = cookie2.getVersion(); - final StringBuffer buffer = new StringBuffer(); - this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version))); - buffer.append("; "); - doFormatCookie2(cookie2, buffer); - return buffer.toString(); - } else { - // old-style cookies are formatted according to the old rules - return this.rfc2109.formatCookie(cookie); - } - } - /** - * Create a RFC 2965 compliant "Cookie" header value containing all - * {@link org.apache.commons.httpclient.Cookie}s suitable for - * sending in a "Cookie" header - * @param cookies an array of {@link org.apache.commons.httpclient.Cookie}s to be formatted - * @return a string suitable for sending in a Cookie header. - */ - public String formatCookies(final Cookie[] cookies) { - LOG.trace("enter RFC2965Spec.formatCookieHeader(Cookie[])"); - if (cookies == null) { - throw new IllegalArgumentException("Cookies may not be null"); - } - // check if cookies array contains a set-cookie (old style) cookie - boolean hasOldStyleCookie = false; - int version = -1; - for (int i = 0; i < cookies.length; i++) { - Cookie cookie = cookies[i]; - if (!(cookie instanceof Cookie2)) { - hasOldStyleCookie = true; - break; - } - if (cookie.getVersion() > version) { - version = cookie.getVersion(); - } - } - if (version < 0) { - version = 0; - } - if (hasOldStyleCookie || version < 1) { - // delegate old-style cookie formatting to rfc2109Spec - return this.rfc2109.formatCookies(cookies); - } - // Arrange cookies by path - Arrays.sort(cookies, PATH_COMPOARATOR); - final StringBuffer buffer = new StringBuffer(); - // format cookie version - this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version))); - for (int i = 0; i < cookies.length; i++) { - buffer.append("; "); - Cookie2 cookie = (Cookie2) cookies[i]; - // format cookie attributes - doFormatCookie2(cookie, buffer); - } - return buffer.toString(); - } - /** - * Retrieves valid Port attribute value for the given ports array. - * e.g. "8000,8001,8002" - * - * @param ports int array of ports - */ - private String createPortAttribute(int[] ports) { - StringBuffer portValue = new StringBuffer(); - for (int i = 0, len = ports.length; i < len; i++) { - if (i > 0) { - portValue.append(","); - } - portValue.append(ports[i]); - } - return portValue.toString(); - } - /** - * Parses the given Port attribute value (e.g. "8000,8001,8002") - * into an array of ports. - * - * @param portValue port attribute value - * @return parsed array of ports - * @throws MalformedCookieException if there is a problem in - * parsing due to invalid portValue. - */ - private int[] parsePortAttribute(final String portValue) - throws MalformedCookieException { - StringTokenizer st = new StringTokenizer(portValue, ","); - int[] ports = new int[st.countTokens()]; - try { - int i = 0; - while(st.hasMoreTokens()) { - ports[i] = Integer.parseInt(st.nextToken().trim()); - if (ports[i] < 0) { - throw new MalformedCookieException ("Invalid Port attribute."); - } - ++i; - } - } catch (NumberFormatException e) { - throw new MalformedCookieException ("Invalid Port " - + "attribute: " + e.getMessage()); - } - return ports; - } - /** - * Gets 'effective host name' as defined in RFC 2965. - *
- * If a host name contains no dots, the effective host name is - * that name with the string .local appended to it. Otherwise - * the effective host name is the same as the host name. Note - * that all effective host names contain at least one dot. - * - * @param host host name where cookie is received from or being sent to. - * @return - */ - private static String getEffectiveHost(final String host) { - String effectiveHost = host.toLowerCase(); - if (host.indexOf('.') < 0) { - effectiveHost += ".local"; - } - return effectiveHost; - } - /** - * Performs domain-match as defined by the RFC2965. - *
- * Host A's name domain-matches host B's if - *
null
.
- */
- public ByteArrayRequestEntity(byte[] content, String contentType) {
- super();
- if (content == null) {
- throw new IllegalArgumentException("The content cannot be null");
- }
- this.content = content;
- this.contentType = contentType;
- }
- /**
- * @return
true
- */
- public boolean isRepeatable() {
- return true;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
- */
- public String getContentType() {
- return contentType;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream)
- */
- public void writeRequest(OutputStream out) throws IOException {
- out.write(content);
- }
- /**
- * @return The length of the content.
- */
- public long getContentLength() {
- return content.length;
- }
- /**
- * @return Returns the content.
- */
- public byte[] getContent() {
- return content;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/DeleteMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/DeleteMethod.java
deleted file mode 100644
index 9282506..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/DeleteMethod.java
+++ /dev/null
@@ -1,96 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/DeleteMethod.java,v 1.14 2004/04/18 23:51:37 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
requestBodyStream
or one of
- *
CONTENT_LENGTH_AUTO
and
CONTENT_LENGTH_CHUNKED
.
- *
- * @deprecated
- */
- private long requestContentLength = InputStreamRequestEntity.CONTENT_LENGTH_AUTO;
- private boolean chunked = false;
- // ----------------------------------------------------------- Constructors
- /**
- * No-arg constructor.
- *
- * @since 2.0
- */
- public EntityEnclosingMethod() {
- super();
- setFollowRedirects(false);
- }
- /**
- * Constructor specifying a URI.
- *
- * @param uri either an absolute or relative URI
- *
- * @since 2.0
- */
- public EntityEnclosingMethod(String uri) {
- super(uri);
- setFollowRedirects(false);
- }
- /**
- * Returns
true
if there is a request body to be sent.
- *
- *
This method must be overridden by sub-classes that implement - * alternative request content input methods - *
- * - * @return boolean - * - * @since 2.0beta1 - */ - protected boolean hasRequestContent() { - LOG.trace("enter EntityEnclosingMethod.hasRequestContent()"); - return (this.requestEntity != null) - || (this.requestStream != null) - || (this.requestString != null); - } - /** - * Clears the request body. - * - *This method must be overridden by sub-classes that implement - * alternative request content input methods.
- * - * @since 2.0beta1 - */ - protected void clearRequestBody() { - LOG.trace("enter EntityEnclosingMethod.clearRequestBody()"); - this.requestStream = null; - this.requestString = null; - this.requestEntity = null; - } - /** - * Generates the request body. - * - *This method must be overridden by sub-classes that implement - * alternative request content input methods.
- * - * @return request body as an array of bytes. If the request content - * has not been set, returns null . - * - * @since 2.0beta1 - */ - protected byte[] generateRequestBody() { - LOG.trace("enter EntityEnclosingMethod.renerateRequestBody()"); - return null; - } - protected RequestEntity generateRequestEntity() { - byte[] requestBody = generateRequestBody(); - if (requestBody != null) { - // use the request body, if it exists. - // this is just for backwards compatability - this.requestEntity = new ByteArrayRequestEntity(requestBody); - } else if (this.requestStream != null) { - this.requestEntity = new InputStreamRequestEntity( - requestStream, - requestContentLength); - this.requestStream = null; - } else if (this.requestString != null) { - String charset = getRequestCharSet(); - try { - this.requestEntity = new StringRequestEntity( - requestString, null, charset); - } catch (UnsupportedEncodingException e) { - if (LOG.isWarnEnabled()) { - LOG.warn(charset + " not supported"); - } - try { - this.requestEntity = new StringRequestEntity( - requestString, null, null); - } catch (UnsupportedEncodingException ignore) { - } - } - } - return this.requestEntity; - } - /** - * Entity enclosing requests cannot be redirected without user intervention - * according to RFC 2616. - * - * @return
false
.
- *
- * @since 2.0
- */
- public boolean getFollowRedirects() {
- return false;
- }
- /**
- * Entity enclosing requests cannot be redirected without user intervention
- * according to RFC 2616.
- *
- * @param followRedirects must always be
false
- */
- public void setFollowRedirects(boolean followRedirects) {
- if (followRedirects == true) {
- throw new IllegalArgumentException("Entity enclosing requests cannot be redirected without user intervention");
- }
- super.setFollowRedirects(false);
- }
- /**
- * Sets length information about the request body.
- *
- *
- * Note: If you specify a content length the request is unbuffered. This - * prevents redirection and automatic retry if a request fails the first - * time. This means that the HttpClient can not perform authorization - * automatically but will throw an Exception. You will have to set the - * necessary 'Authorization' or 'Proxy-Authorization' headers manually. - *
- * - * @param length size in bytes or any of CONTENT_LENGTH_AUTO, - * CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED - * is specified the content will not be buffered internally and the - * Content-Length header of the request will be used. In this case - * the user is responsible to supply the correct content length. - * If CONTENT_LENGTH_AUTO is specified the request will be buffered - * before it is sent over the network. - * - * @deprecated Use {@link #setContentChunked(boolean)} or - * {@link #setRequestEntity(RequestEntity)} - */ - public void setRequestContentLength(int length) { - LOG.trace("enter EntityEnclosingMethod.setRequestContentLength(int)"); - this.requestContentLength = length; - } - /** - * Returns the request's charset. The charset is parsed from the request entity's - * content type, unless the content type header has been set manually. - * - * @see RequestEntity#getContentType() - * - * @since 3.0 - */ - public String getRequestCharSet() { - if (getRequestHeader("Content-Type") == null) { - // check the content type from request entity - // We can't call getRequestEntity() since it will probably call - // this method. - if (this.requestEntity != null) { - return getContentCharSet( - new Header("Content-Type", requestEntity.getContentType())); - } else { - return super.getRequestCharSet(); - } - } else { - return super.getRequestCharSet(); - } - } - /** - * Sets length information about the request body. - * - *- * Note: If you specify a content length the request is unbuffered. This - * prevents redirection and automatic retry if a request fails the first - * time. This means that the HttpClient can not perform authorization - * automatically but will throw an Exception. You will have to set the - * necessary 'Authorization' or 'Proxy-Authorization' headers manually. - *
- * - * @param length size in bytes or any of CONTENT_LENGTH_AUTO, - * CONTENT_LENGTH_CHUNKED. If number of bytes or CONTENT_LENGTH_CHUNKED - * is specified the content will not be buffered internally and the - * Content-Length header of the request will be used. In this case - * the user is responsible to supply the correct content length. - * If CONTENT_LENGTH_AUTO is specified the request will be buffered - * before it is sent over the network. - * - * @deprecated Use {@link #setContentChunked(boolean)} or - * {@link #setRequestEntity(RequestEntity)} - */ - public void setRequestContentLength(long length) { - LOG.trace("enter EntityEnclosingMethod.setRequestContentLength(int)"); - this.requestContentLength = length; - } - /** - * Sets whether or not the content should be chunked. - * - * @param chunked
true
if the content should be chunked
- *
- * @since 3.0
- */
- public void setContentChunked(boolean chunked) {
- this.chunked = chunked;
- }
- /**
- * Returns the length of the request body.
- *
- * @return number of bytes in the request body
- */
- protected long getRequestContentLength() {
- LOG.trace("enter EntityEnclosingMethod.getRequestContentLength()");
- if (!hasRequestContent()) {
- return 0;
- }
- if (this.chunked) {
- return -1;
- }
- if (this.requestEntity == null) {
- this.requestEntity = generateRequestEntity();
- }
- return (this.requestEntity == null) ? 0 : this.requestEntity.getContentLength();
- }
- /**
- * Populates the request headers map to with additional
- * {@link org.apache.commons.httpclient.Header headers} to be submitted to
- * the given {@link HttpConnection}.
- *
- *
- * This implementation adds tt>Content-Length or Transfer-Encoding - * headers. - *
- * - *- * Subclasses may want to override this method to to add additional - * headers, and may choose to invoke this implementation (via - * super ) to add the "standard" headers. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #writeRequestHeaders - * - * @since 3.0 - */ - protected void addRequestHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter EntityEnclosingMethod.addRequestHeaders(HttpState, " - + "HttpConnection)"); - super.addRequestHeaders(state, conn); - addContentLengthRequestHeader(state, conn); - // only use the content type of the request entity if it has not already been - // set manually - if (getRequestHeader("Content-Type") == null) { - RequestEntity requestEntity = getRequestEntity(); - if (requestEntity != null && requestEntity.getContentType() != null) { - setRequestHeader("Content-Type", requestEntity.getContentType()); - } - } - } - /** - * Generates Content-Length or Transfer-Encoding: Chunked - * request header, as long as no Content-Length request header - * already exists. - * - * @param state current state of http requests - * @param conn the connection to use for I/O - * - * @throws IOException when errors occur reading or writing to/from the - * connection - * @throws HttpException when a recoverable error occurs - */ - protected void addContentLengthRequestHeader(HttpState state, - HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter EntityEnclosingMethod.addContentLengthRequestHeader(" - + "HttpState, HttpConnection)"); - if ((getRequestHeader("content-length") == null) - && (getRequestHeader("Transfer-Encoding") == null)) { - long len = getRequestContentLength(); - if (len < 0) { - if (getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1)) { - addRequestHeader("Transfer-Encoding", "chunked"); - } else { - throw new ProtocolException(getEffectiveVersion() + - " does not support chunk encoding"); - } - } else { - addRequestHeader("Content-Length", String.valueOf(len)); - } - } - } - /** - * Sets the request body to be the specified inputstream. - * - * @param body Request body content as {@link java.io.InputStream} - * - * @deprecated use {@link #setRequestEntity(RequestEntity)} - */ - public void setRequestBody(InputStream body) { - LOG.trace("enter EntityEnclosingMethod.setRequestBody(InputStream)"); - clearRequestBody(); - this.requestStream = body; - } - /** - * Sets the request body to be the specified string. - * The string will be submitted, using the encoding - * specified in the Content-Type request header.
setRequestHeader("Content-type", "text/xml; charset=UTF-8");
- * Returns true if the 'Expect: 100-Continue' handshake - * is activated. The purpose of the 'Expect: 100-Continue' - * handshake 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. - *
- * - * @return true if 'Expect: 100-Continue' handshake is to - * be used, false otherwise. - * - * @since 2.0beta1 - * - * @deprecated Use {@link HttpMethodParams} - * - * @see #getParams() - * @see HttpMethodParams - * @see HttpMethodParams#USE_EXPECT_CONTINUE - */ - public boolean getUseExpectHeader() { - return getParams().getBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); - } - /** - *- * Activates 'Expect: 100-Continue' handshake. The purpose of - * the 'Expect: 100-Continue' handshake 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. - *
- * - *- * The use of the 'Expect: 100-continue' handshake can result in - * noticable peformance improvement for entity enclosing requests - * (such as POST and PUT) that require the target server's - * authentication. - *
- * - *- * '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. - *
- * - * @param value boolean value - * - * @since 2.0beta1 - * - * @deprecated Use {@link HttpMethodParams} - * - * @see #getParams() - * @see HttpMethodParams - * @see HttpMethodParams#USE_EXPECT_CONTINUE - */ - public void setUseExpectHeader(boolean value) { - getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, value); - } - /** - * Returns true if there is a request body to be sent. - * 'Expect: 100-continue' handshake may not be used if request - * body is not present - * - * @return boolean - * - * @since 2.0beta1 - */ - protected abstract boolean hasRequestContent(); - /** - * Sets the Expect header if it has not already been set, - * in addition to the "standard" set of headers. - * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - */ - protected void addRequestHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter ExpectContinueMethod.addRequestHeaders(HttpState, HttpConnection)"); - super.addRequestHeaders(state, conn); - // If the request is being retried, the header may already be present - boolean headerPresent = (getRequestHeader("Expect") != null); - // See if the expect header should be sent - // = HTTP/1.1 or higher - // = request body present - if (getParams().isParameterTrue(HttpMethodParams.USE_EXPECT_CONTINUE) - && getEffectiveVersion().greaterEquals(HttpVersion.HTTP_1_1) - && hasRequestContent()) - { - if (!headerPresent) { - setRequestHeader("Expect", "100-continue"); - } - } else { - if (headerPresent) { - removeRequestHeader("Expect"); - } - } - } diff --git a/clients/java/src/org/apache/commons/httpclient/methods/FileRequestEntity.java b/clients/java/src/org/apache/commons/httpclient/methods/FileRequestEntity.java deleted file mode 100644 index 0bb0286..0000000 --- a/clients/java/src/org/apache/commons/httpclient/methods/FileRequestEntity.java +++ /dev/null @@ -1,83 +0,0 @@ - * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/methods/FileRequestEntity.java $ - * $Revision: 486665 $ - * $Date: 2006-12-13 15:19:07 +0100 (Wed, 13 Dec 2006) $ - * ==================================================================== - * 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 - *- * @author Remy Maucherat - * @author Sung-Gu Park - * @author Sean C. Sullivan - * @author Mike Bowler - * @author Jeff Dever - * @version $Revision: 480424 $ - * @since 1.0 -public class GetMethod extends HttpMethodBase { - // -------------------------------------------------------------- Constants - /** Log object for this class. */ - private static final Log LOG = LogFactory.getLog(GetMethod.class); - // ----------------------------------------------------------- Constructors - /** - * No-arg constructor. - * - * @since 1.0 - */ - public GetMethod() { - setFollowRedirects(true); - } - /** - * Constructor specifying a URI. - * - * @param uri either an absolute or relative URI - * - * @since 1.0 - */ - public GetMethod(String uri) { - super(uri); - LOG.trace("enter GetMethod(String)"); - setFollowRedirects(true); - } - // --------------------------------------------------------- Public Methods - /** - * Returns "GET" . - * - * @return "GET" - * - * @since 2.0 - */ - public String getName() { - return "GET"; - } - // ------------------------------------------------------------- Properties - /** - * Recycles the HTTP method so that it can be used again. - * Note that all of the instance variables will be reset - * once this method has been called. This method will also - * release the connection being used by this HTTP method. - * - * @see #releaseConnection() - * - * @since 1.0 - * - * @deprecated no longer supported and will be removed in the future - * version of HttpClient - */ - public void recycle() { - LOG.trace("enter GetMethod.recycle()"); - super.recycle(); - setFollowRedirects(true); - } diff --git a/clients/java/src/org/apache/commons/httpclient/methods/HeadMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/HeadMethod.java deleted file mode 100644 index 13d8583..0000000 --- a/clients/java/src/org/apache/commons/httpclient/methods/HeadMethod.java +++ /dev/null @@ -1,219 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/HeadMethod.java,v 1.29 2004/06/13 20:22:19 olegk Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
null
.
- */
- public InputStreamRequestEntity(InputStream content, String contentType) {
- this(content, CONTENT_LENGTH_AUTO, contentType);
- }
- /**
- * Creates a new InputStreamRequestEntity with the given content and content length.
- * @param content The content to set.
- * @param contentLength The content size in bytes or a negative number if not known.
- * If {@link #CONTENT_LENGTH_AUTO} is given the content will be buffered in order to
- * determine its size when {@link #getContentLength()} is called.
- */
- public InputStreamRequestEntity(InputStream content, long contentLength) {
- this(content, contentLength, null);
- }
- /**
- * Creates a new InputStreamRequestEntity with the given content, content length, and
- * content type.
- * @param content The content to set.
- * @param contentLength The content size in bytes or a negative number if not known.
- * If {@link #CONTENT_LENGTH_AUTO} is given the content will be buffered in order to
- * determine its size when {@link #getContentLength()} is called.
- * @param contentType The type of the content, or
null
.
- */
- public InputStreamRequestEntity(InputStream content, long contentLength, String contentType) {
- if (content == null) {
- throw new IllegalArgumentException("The content cannot be null");
- }
- this.content = content;
- this.contentLength = contentLength;
- this.contentType = contentType;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
- */
- public String getContentType() {
- return contentType;
- }
- /**
- * Buffers request body input stream.
- */
- private void bufferContent() {
- if (this.buffer != null) {
- // Already been buffered
- return;
- }
- if (this.content != null) {
- try {
- ByteArrayOutputStream tmp = new ByteArrayOutputStream();
- byte[] data = new byte[4096];
- int l = 0;
- while ((l = this.content.read(data)) >= 0) {
- tmp.write(data, 0, l);
- }
- this.buffer = tmp.toByteArray();
- this.content = null;
- this.contentLength = buffer.length;
- } catch (IOException e) {
- LOG.error(e.getMessage(), e);
- this.buffer = null;
- this.content = null;
- this.contentLength = 0;
- }
- }
- }
- /**
- * Tests if this method is repeatable. Only
true
if the content has been
- * buffered.
- *
- * @see #getContentLength()
- */
- public boolean isRepeatable() {
- return buffer != null;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream)
- */
- public void writeRequest(OutputStream out) throws IOException {
- if (content != null) {
- byte[] tmp = new byte[4096];
- int total = 0;
- int i = 0;
- while ((i = content.read(tmp)) >= 0) {
- out.write(tmp, 0, i);
- total += i;
- }
- } else if (buffer != null) {
- out.write(buffer);
- } else {
- throw new IllegalStateException("Content must be set before entity is written");
- }
- }
- /**
- * Gets the content length. If the content length has not been set, the content will be
- * buffered to determine the actual content length.
- */
- public long getContentLength() {
- if (contentLength == CONTENT_LENGTH_AUTO && buffer == null) {
- bufferContent();
- }
- return contentLength;
- }
- /**
- * @return Returns the content.
- */
- public InputStream getContent() {
- return content;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/MultipartPostMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/MultipartPostMethod.java
deleted file mode 100644
index 4bdfcc5..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/MultipartPostMethod.java
+++ /dev/null
@@ -1,333 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/MultipartPostMethod.java,v 1.27 2004/10/06 03:39:59 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
- * This implementation adds tt>Content-Length and Content-Type - * headers, when appropriate. - *
- * - *- * Subclasses may want to override this method to to add additional - * headers, and may choose to invoke this implementation (via - * super ) to add the "standard" headers. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - * - * @see #writeRequestHeaders - */ - protected void addRequestHeaders(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter MultipartPostMethod.addRequestHeaders(HttpState state, " - + "HttpConnection conn)"); - super.addRequestHeaders(state, conn); - addContentLengthRequestHeader(state, conn); - addContentTypeRequestHeader(state, conn); - } - /** - * Writes the request body to the given {@link HttpConnection connection}. - * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @return true - * - * @throws IOException if an I/O (transport) error occurs. Some transport exceptions - * can be recovered from. - * @throws HttpException if a protocol exception occurs. Usually protocol exceptions - * cannot be recovered from. - */ - protected boolean writeRequestBody(HttpState state, HttpConnection conn) - throws IOException, HttpException { - LOG.trace("enter MultipartPostMethod.writeRequestBody(HttpState state, " - + "HttpConnection conn)"); - OutputStream out = conn.getRequestOutputStream(); - Part.sendParts(out, getParts()); - return true; - } - /** - *Return the length of the request body.
- * - *Once this method has been invoked, the request parameters cannot be - * altered until the method is {@link #recycle recycled}.
- * - * @return The request content length. - */ - protected long getRequestContentLength() throws IOException { - LOG.trace("enter MultipartPostMethod.getRequestContentLength()"); - return Part.getLengthOfParts(getParts()); - } - /** - * Recycles the HTTP method so that it can be used again. - * Note that all of the instance variables will be reset - * once this method has been called. This method will also - * release the connection being used by this HTTP method. - * - * @see #releaseConnection() - * - * @deprecated no longer supported and will be removed in the future - * version of HttpClient - */ - public void recycle() { - LOG.trace("enter MultipartPostMethod.recycle()"); - super.recycle(); - parameters.clear(); - } diff --git a/clients/java/src/org/apache/commons/httpclient/methods/OptionsMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/OptionsMethod.java deleted file mode 100644 index 5ce4cb9..0000000 --- a/clients/java/src/org/apache/commons/httpclient/methods/OptionsMethod.java +++ /dev/null @@ -1,192 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/OptionsMethod.java,v 1.15 2004/04/18 23:51:37 jsdever Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *- * This implementation will parse the Allow header to obtain - * the set of methods supported by the resource identified by the Request-URI. - *
- * - * @param state the {@link HttpState state} information associated with this method - * @param conn the {@link HttpConnection connection} used to execute - * this HTTP method - * - * @see #readResponse - * @see #readResponseHeaders - * @since 2.0 - */ - protected void processResponseHeaders(HttpState state, HttpConnection conn) { - LOG.trace("enter OptionsMethod.processResponseHeaders(HttpState, HttpConnection)"); - Header allowHeader = getResponseHeader("allow"); - if (allowHeader != null) { - String allowHeaderValue = allowHeader.getValue(); - StringTokenizer tokenizer = - new StringTokenizer(allowHeaderValue, ","); - while (tokenizer.hasMoreElements()) { - String methodAllowed = - tokenizer.nextToken().trim().toUpperCase(); - methodsAllowed.addElement(methodAllowed); - } - } - } - /** - * Return true if the method needs a content-length header in the request. - * - * @return true if a content-length header will be expected by the server - * - * @since 1.0 - * - * @deprecated only entity enclosing methods set content length header - */ - public boolean needContentLength() { - return false; - } diff --git a/clients/java/src/org/apache/commons/httpclient/methods/PostMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/PostMethod.java deleted file mode 100644 index 5cf43db..0000000 --- a/clients/java/src/org/apache/commons/httpclient/methods/PostMethod.java +++ /dev/null @@ -1,411 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/PostMethod.java,v 1.58 2004/08/08 12:50:09 olegk Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *
NameValuePair
s.
- */
- private Vector params = new Vector();
- // ----------------------------------------------------------- Constructors
- /**
- * No-arg constructor.
- *
- * @since 1.0
- */
- public PostMethod() {
- super();
- }
- /**
- * Constructor specifying a URI.
- *
- * @param uri either an absolute or relative URI
- *
- * @since 1.0
- */
- public PostMethod(String uri) {
- super(uri);
- }
- // ----------------------------------------------------- Instance Methods
- /**
- * Returns
"POST"
.
- *
- * @return
"POST"
- *
- * @since 2.0
- */
- public String getName() {
- return "POST";
- }
- /**
- * Returns
true
if there is a request body to be sent.
- *
- *
This method must be overwritten by sub-classes that implement - * alternative request content input methods - *
- * - * @return boolean - * - * @since 2.0beta1 - */ - protected boolean hasRequestContent() { - LOG.trace("enter PostMethod.hasRequestContent()"); - if (!this.params.isEmpty()) { - return true; - } else { - return super.hasRequestContent(); - } - } - /** - * Clears request body. - * - *This method must be overwritten by sub-classes that implement - * alternative request content input methods
- * - * @since 2.0beta1 - */ - protected void clearRequestBody() { - LOG.trace("enter PostMethod.clearRequestBody()"); - this.params.clear(); - super.clearRequestBody(); - } - /** - * Generates a request entity from the post parameters, if present. Calls - * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set. - * - * @since 3.0 - */ - protected RequestEntity generateRequestEntity() { - if (!this.params.isEmpty()) { - // Use a ByteArrayRequestEntity instead of a StringRequestEntity. - // This is to avoid potential encoding issues. Form url encoded strings - // are ASCII by definition but the content type may not be. Treating the content - // as bytes allows us to keep the current charset without worrying about how - // this charset will effect the encoding of the form url encoded string. - String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet()); - ByteArrayRequestEntity entity = new ByteArrayRequestEntity( - EncodingUtil.getAsciiBytes(content), - FORM_URL_ENCODED_CONTENT_TYPE - ); - return entity; - } else { - return super.generateRequestEntity(); - } - } - /** - * Sets the value of parameter with parameterName to parameterValue. This method - * does not preserve the initial insertion order. - * - * @param parameterName name of the parameter - * @param parameterValue value of the parameter - * - * @since 2.0 - */ - public void setParameter(String parameterName, String parameterValue) { - LOG.trace("enter PostMethod.setParameter(String, String)"); - removeParameter(parameterName); - addParameter(parameterName, parameterValue); - } - /** - * Gets the parameter of the specified name. If there exists more than one - * parameter with the name paramName, then only the first one is returned. - * - * @param paramName name of the parameter - * - * @return If a parameter exists with the name argument, the coresponding - * NameValuePair is returned. Otherwise null. - * - * @since 2.0 - * - */ - public NameValuePair getParameter(String paramName) { - LOG.trace("enter PostMethod.getParameter(String)"); - if (paramName == null) { - return null; - } - Iterator iter = this.params.iterator(); - while (iter.hasNext()) { - NameValuePair parameter = (NameValuePair) iter.next(); - if (paramName.equals(parameter.getName())) { - return parameter; - } - } - return null; - } - /** - * Gets the parameters currently added to the PostMethod. If there are no - * parameters, a valid array is returned with zero elements. The returned - * array object contains an array of pointers to the internal data - * members. - * - * @return An array of the current parameters - * - * @since 2.0 - * - */ - public NameValuePair[] getParameters() { - LOG.trace("enter PostMethod.getParameters()"); - int numPairs = this.params.size(); - Object[] objectArr = this.params.toArray(); - NameValuePair[] nvPairArr = new NameValuePair[numPairs]; - for (int i = 0; i < numPairs; i++) { - nvPairArr[i] = (NameValuePair) objectArr[i]; - } - return nvPairArr; - } - /** - * Adds a new parameter to be used in the POST request body. - * - * @param paramName The parameter name to add. - * @param paramValue The parameter value to add. - * - * @throws IllegalArgumentException if either argument is null - * - * @since 1.0 - */ - public void addParameter(String paramName, String paramValue) - throws IllegalArgumentException { - LOG.trace("enter PostMethod.addParameter(String, String)"); - if ((paramName == null) || (paramValue == null)) { - throw new IllegalArgumentException( - "Arguments to addParameter(String, String) cannot be null"); - } - super.clearRequestBody(); - this.params.add(new NameValuePair(paramName, paramValue)); - } - /** - * Adds a new parameter to be used in the POST request body. - * - * @param param The parameter to add. - * - * @throws IllegalArgumentException if the argument is null or contains - * null values - * - * @since 2.0 - */ - public void addParameter(NameValuePair param) - throws IllegalArgumentException { - LOG.trace("enter PostMethod.addParameter(NameValuePair)"); - if (param == null) { - throw new IllegalArgumentException("NameValuePair may not be null"); - } - addParameter(param.getName(), param.getValue()); - } - /** - * Adds an array of parameters to be used in the POST request body. Logs a - * warning if the parameters argument is null. - * - * @param parameters The array of parameters to add. - * - * @since 2.0 - */ - public void addParameters(NameValuePair[] parameters) { - LOG.trace("enter PostMethod.addParameters(NameValuePair[])"); - if (parameters == null) { - LOG.warn("Attempt to addParameters(null) ignored"); - } else { - super.clearRequestBody(); - for (int i = 0; i < parameters.length; i++) { - this.params.add(parameters[i]); - } - } - } - /** - * Removes all parameters with the given paramName. If there is more than - * one parameter with the given paramName, all of them are removed. If - * there is just one, it is removed. If there are none, then the request - * is ignored. - * - * @param paramName The parameter name to remove. - * - * @return true if at least one parameter was removed - * - * @throws IllegalArgumentException When the parameter name passed is null - * - * @since 2.0 - */ - public boolean removeParameter(String paramName) - throws IllegalArgumentException { - LOG.trace("enter PostMethod.removeParameter(String)"); - if (paramName == null) { - throw new IllegalArgumentException( - "Argument passed to removeParameter(String) cannot be null"); - } - boolean removed = false; - Iterator iter = this.params.iterator(); - while (iter.hasNext()) { - NameValuePair pair = (NameValuePair) iter.next(); - if (paramName.equals(pair.getName())) { - iter.remove(); - removed = true; - } - } - return removed; - } - /** - * Removes all parameter with the given paramName and paramValue. If there - * is more than one parameter with the given paramName, only one is - * removed. If there are none, then the request is ignored. - * - * @param paramName The parameter name to remove. - * @param paramValue The parameter value to remove. - * - * @return true if a parameter was removed. - * - * @throws IllegalArgumentException when param name or value are null - * - * @since 2.0 - */ - public boolean removeParameter(String paramName, String paramValue) - throws IllegalArgumentException { - LOG.trace("enter PostMethod.removeParameter(String, String)"); - if (paramName == null) { - throw new IllegalArgumentException("Parameter name may not be null"); - } - if (paramValue == null) { - throw new IllegalArgumentException("Parameter value may not be null"); - } - Iterator iter = this.params.iterator(); - while (iter.hasNext()) { - NameValuePair pair = (NameValuePair) iter.next(); - if (paramName.equals(pair.getName()) - && paramValue.equals(pair.getValue())) { - iter.remove(); - return true; - } - } - return false; - } - /** - * Sets an array of parameters to be used in the POST request body - * - * @param parametersBody The array of parameters to add. - * - * @throws IllegalArgumentException when param parameters are null - * - * @since 2.0beta1 - */ - public void setRequestBody(NameValuePair[] parametersBody) - throws IllegalArgumentException { - LOG.trace("enter PostMethod.setRequestBody(NameValuePair[])"); - if (parametersBody == null) { - throw new IllegalArgumentException("Array of parameters may not be null"); - } - clearRequestBody(); - addParameters(parametersBody); - } diff --git a/clients/java/src/org/apache/commons/httpclient/methods/PutMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/PutMethod.java deleted file mode 100644 index c1bdc2b..0000000 --- a/clients/java/src/org/apache/commons/httpclient/methods/PutMethod.java +++ /dev/null @@ -1,90 +0,0 @@ - * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/PutMethod.java,v 1.26 2004/04/18 23:51:37 jsdever Exp $ - * $Revision: 480424 $ - * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $ - * ==================================================================== - * 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 - *Creates a new entity with the given content. This constructor - * will use the default platform charset to convert the content string - * and will provide no content type.
- * - * @see #StringRequestEntity(String, String, String) - * - * @param content The content to set. - * - * @deprecated use {@link #StringRequestEntity(String, String, String)} instead - */ - public StringRequestEntity(String content) { - super(); - if (content == null) { - throw new IllegalArgumentException("The content cannot be null"); - } - this.contentType = null; - this.charset = null; - this.content = content.getBytes(); - } - /** - * Creates a new entity with the given content, content type, and charset. - * - * @param content The content to set. - * @param contentType The type of the content, or
null
. The value retured
- * by {@link #getContentType()}. If this content type contains a charset and the charset
- * parameter is null, the content's type charset will be used.
- * @param charset The charset of the content, or
null
. Used to convert the
- * content to bytes. If the content type does not contain a charset and charset is not null,
- * then the charset will be appended to the content type.
- */
- public StringRequestEntity(String content, String contentType, String charset)
- throws UnsupportedEncodingException {
- super();
- if (content == null) {
- throw new IllegalArgumentException("The content cannot be null");
- }
- this.contentType = contentType;
- this.charset = charset;
- // resolve the content type and the charset
- if (contentType != null) {
- HeaderElement[] values = HeaderElement.parseElements(contentType);
- NameValuePair charsetPair = null;
- for (int i = 0; i < values.length; i++) {
- if ((charsetPair = values[i].getParameterByName("charset")) != null) {
- // charset found
- break;
- }
- }
- if (charset == null && charsetPair != null) {
- // use the charset from the content type
- this.charset = charsetPair.getValue();
- } else if (charset != null && charsetPair == null) {
- // append the charset to the content type
- this.contentType = contentType + "; charset=" + charset;
- }
- }
- if (this.charset != null) {
- this.content = content.getBytes(this.charset);
- } else {
- this.content = content.getBytes();
- }
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
- */
- public String getContentType() {
- return contentType;
- }
- /**
- * @return
true
- */
- public boolean isRepeatable() {
- return true;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.RequestEntity#writeRequest(java.io.OutputStream)
- */
- public void writeRequest(OutputStream out) throws IOException {
- if (out == null) {
- throw new IllegalArgumentException("Output stream may not be null");
- }
- out.write(this.content);
- out.flush();
- }
- /**
- * @return The length of the content.
- */
- public long getContentLength() {
- return this.content.length;
- }
- /**
- * @return Returns the content.
- */
- public String getContent() {
- if (this.charset != null) {
- try {
- return new String(this.content, this.charset);
- } catch (UnsupportedEncodingException e) {
- return new String(this.content);
- }
- } else {
- return new String(this.content);
- }
- }
- /**
- * @return Returns the charset used to convert the content to bytes.
null
if
- * no charset as been specified.
- */
- public String getCharset() {
- return charset;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/TraceMethod.java b/clients/java/src/org/apache/commons/httpclient/methods/TraceMethod.java
deleted file mode 100644
index cf03fcf..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/TraceMethod.java
+++ /dev/null
@@ -1,108 +0,0 @@
- * $Header: $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
the
- * {@link #DEFAULT_CONTENT_TYPE default} is used
- * @param charset the charset encoding for this part, if
null
the
- * {@link #DEFAULT_CHARSET default} is used
- */
- public FilePart(String name, PartSource partSource, String contentType, String charset) {
- super(
- name,
- contentType == null ? DEFAULT_CONTENT_TYPE : contentType,
- charset == null ? "ISO-8859-1" : charset,
- DEFAULT_TRANSFER_ENCODING
- );
- if (partSource == null) {
- throw new IllegalArgumentException("Source may not be null");
- }
- this.source = partSource;
- }
- /**
- * FilePart Constructor.
- *
- * @param name the name for this part
- * @param partSource the source for this part
- */
- public FilePart(String name, PartSource partSource) {
- this(name, partSource, null, null);
- }
- /**
- * FilePart Constructor.
- *
- * @param name the name of the file part
- * @param file the file to post
- *
- * @throws FileNotFoundException if the
file
is not a normal
- * file or if it is not readable.
- */
- public FilePart(String name, File file)
- throws FileNotFoundException {
- this(name, new FilePartSource(file), null, null);
- }
- /**
- * FilePart Constructor.
- *
- * @param name the name of the file part
- * @param file the file to post
- * @param contentType the content type for this part, if
null
the
- * {@link #DEFAULT_CONTENT_TYPE default} is used
- * @param charset the charset encoding for this part, if
null
the
- * {@link #DEFAULT_CHARSET default} is used
- *
- * @throws FileNotFoundException if the
file
is not a normal
- * file or if it is not readable.
- */
- public FilePart(String name, File file, String contentType, String charset)
- throws FileNotFoundException {
- this(name, new FilePartSource(file), contentType, charset);
- }
- /**
- * FilePart Constructor.
- *
- * @param name the name of the file part
- * @param fileName the file name
- * @param file the file to post
- *
- * @throws FileNotFoundException if the
file
is not a normal
- * file or if it is not readable.
- */
- public FilePart(String name, String fileName, File file)
- throws FileNotFoundException {
- this(name, new FilePartSource(fileName, file), null, null);
- }
- /**
- * FilePart Constructor.
- *
- * @param name the name of the file part
- * @param fileName the file name
- * @param file the file to post
- * @param contentType the content type for this part, if
null
the
- * {@link #DEFAULT_CONTENT_TYPE default} is used
- * @param charset the charset encoding for this part, if
null
the
- * {@link #DEFAULT_CHARSET default} is used
- *
- * @throws FileNotFoundException if the
file
is not a normal
- * file or if it is not readable.
- */
- public FilePart(String name, String fileName, File file, String contentType, String charset)
- throws FileNotFoundException {
- this(name, new FilePartSource(fileName, file), contentType, charset);
- }
- /**
- * Write the disposition header to the output stream
- * @param out The output stream
- * @throws IOException If an IO problem occurs
- * @see Part#sendDispositionHeader(OutputStream)
- */
- protected void sendDispositionHeader(OutputStream out)
- throws IOException {
- LOG.trace("enter sendDispositionHeader(OutputStream out)");
- super.sendDispositionHeader(out);
- String filename = this.source.getFileName();
- if (filename != null) {
- out.write(FILE_NAME_BYTES);
- out.write(QUOTE_BYTES);
- out.write(EncodingUtil.getAsciiBytes(filename));
- out.write(QUOTE_BYTES);
- }
- }
- /**
- * Write the data in "source" to the specified stream.
- * @param out The output stream.
- * @throws IOException if an IO problem occurs.
- * @see org.apache.commons.httpclient.methods.multipart.Part#sendData(OutputStream)
- */
- protected void sendData(OutputStream out) throws IOException {
- LOG.trace("enter sendData(OutputStream out)");
- if (lengthOfData() == 0) {
- // this file contains no data, so there is nothing to send.
- // we don't want to create a zero length buffer as this will
- // cause an infinite loop when reading.
- LOG.debug("No data to send.");
- return;
- }
- byte[] tmp = new byte[4096];
- InputStream instream = source.createInputStream();
- try {
- int len;
- while ((len = instream.read(tmp)) >= 0) {
- out.write(tmp, 0, len);
- }
- } finally {
- // we're done with the stream, close it
- instream.close();
- }
- }
- /**
- * Returns the source of the file part.
- *
- * @return The source.
- */
- protected PartSource getSource() {
- LOG.trace("enter getSource()");
- return this.source;
- }
- /**
- * Return the length of the data.
- * @return The length.
- * @throws IOException if an IO problem occurs
- * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData()
- */
- protected long lengthOfData() throws IOException {
- LOG.trace("enter lengthOfData()");
- return source.getLength();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/multipart/FilePartSource.java b/clients/java/src/org/apache/commons/httpclient/methods/multipart/FilePartSource.java
deleted file mode 100644
index 3ce3275..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/multipart/FilePartSource.java
+++ /dev/null
@@ -1,131 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/FilePartSource.java,v 1.10 2004/04/18 23:51:37 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
This entity is designed to be used in conjunction with the - * {@link org.apache.commons.httpclient.methods.PostMethod post method} to provide - * multipart posts. Example usage:
- * File f = new File("/path/fileToUpload.txt"); - * PostMethod filePost = new PostMethod("http://host/some_path"); - * Part[] parts = { - * new StringPart("param_name", "value"), - * new FilePart(f.getName(), f) - * }; - * filePost.setRequestEntity( - * new MultipartRequestEntity(parts, filePost.getParams()) - * ); - * HttpClient client = new HttpClient(); - * int status = client.executeMethod(filePost); - * @since 3.0 -public class MultipartRequestEntity implements RequestEntity { - private static final Log log = LogFactory.getLog(MultipartRequestEntity.class); - /** The Content-Type for multipart/form-data. */ - private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data"; - /** - * The pool of ASCII chars to be used for generating a multipart boundary. - */ - private static byte[] MULTIPART_CHARS = EncodingUtil.getAsciiBytes( - "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); - /** - * Generates a random multipart boundary string. - * @return - */ - private static byte[] generateMultipartBoundary() { - Random rand = new Random(); - byte[] bytes = new byte[rand.nextInt(11) + 30]; // a random size from 30 to 40 - for (int i = 0; i < bytes.length; i++) { - bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]; - } - return bytes; - } - /** The MIME parts as set by the constructor */ - protected Part[] parts; - private byte[] multipartBoundary; - private HttpMethodParams params; - /** - * Creates a new multipart entity containing the given parts. - * @param parts The parts to include. - * @param params The params of the HttpMethod using this entity. - */ - public MultipartRequestEntity(Part[] parts, HttpMethodParams params) { - if (parts == null) { - throw new IllegalArgumentException("parts cannot be null"); - } - if (params == null) { - throw new IllegalArgumentException("params cannot be null"); - } - this.parts = parts; - this.params = params; - } - /** - * Returns the MIME boundary string that is used to demarcate boundaries of - * this part. The first call to this method will implicitly create a new - * boundary string. To create a boundary string first the - * HttpMethodParams.MULTIPART_BOUNDARY parameter is considered. Otherwise - * a random one is generated. - * - * @return The boundary string of this entity in ASCII encoding. - */ - protected byte[] getMultipartBoundary() { - if (multipartBoundary == null) { - String temp = (String) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY); - if (temp != null) { - multipartBoundary = EncodingUtil.getAsciiBytes(temp); - } else { - multipartBoundary = generateMultipartBoundary(); - } - } - return multipartBoundary; - } - /** - * Returns
true
if all parts are repeatable,
false
otherwise.
- * @see org.apache.commons.httpclient.methods.RequestEntity#isRepeatable()
- */
- public boolean isRepeatable() {
- for (int i = 0; i < parts.length; i++) {
- if (!parts[i].isRepeatable()) {
- return false;
- }
- }
- return true;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.RequestEntity#writeRequest(java.io.OutputStream)
- */
- public void writeRequest(OutputStream out) throws IOException {
- Part.sendParts(out, parts, getMultipartBoundary());
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.RequestEntity#getContentLength()
- */
- public long getContentLength() {
- try {
- return Part.getLengthOfParts(parts, getMultipartBoundary());
- } catch (Exception e) {
- log.error("An exception occurred while getting the length of the parts", e);
- return 0;
- }
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.RequestEntity#getContentType()
- */
- public String getContentType() {
- StringBuffer buffer = new StringBuffer(MULTIPART_FORM_CONTENT_TYPE);
- buffer.append("; boundary=");
- buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary()));
- return buffer.toString();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/multipart/Part.java b/clients/java/src/org/apache/commons/httpclient/methods/multipart/Part.java
deleted file mode 100644
index fc96d29..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/multipart/Part.java
+++ /dev/null
@@ -1,438 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/Part.java,v 1.16 2005/01/14 21:16:40 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
to exclude the content type header
- */
- public abstract String getContentType();
- /**
- * Return the character encoding of this part.
- * @return the character encoding, or
null
to exclude the character
- * encoding header
- */
- public abstract String getCharSet();
- /**
- * Return the transfer encoding of this part.
- * @return the transfer encoding, or
null
to exclude the transfer encoding header
- */
- public abstract String getTransferEncoding();
- /**
- * Gets the part boundary to be used.
- * @return the part boundary as an array of bytes.
- *
- * @since 3.0
- */
- protected byte[] getPartBoundary() {
- if (boundaryBytes == null) {
- // custom boundary bytes have not been set, use the default.
- return DEFAULT_BOUNDARY_BYTES;
- } else {
- return boundaryBytes;
- }
- }
- /**
- * Sets the part boundary. Only meant to be used by
- * {@link Part#sendParts(OutputStream, Part[], byte[])}
- * and {@link Part#getLengthOfParts(Part[], byte[])}
- * @param boundaryBytes An array of ASCII bytes.
- * @since 3.0
- */
- void setPartBoundary(byte[] boundaryBytes) {
- this.boundaryBytes = boundaryBytes;
- }
- /**
- * Tests if this part can be sent more than once.
- * @return
true
if {@link #sendData(OutputStream)} can be successfully called
- * more than once.
- * @since 3.0
- */
- public boolean isRepeatable() {
- return true;
- }
- /**
- * Write the start to the specified output stream
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected void sendStart(OutputStream out) throws IOException {
- LOG.trace("enter sendStart(OutputStream out)");
- out.write(EXTRA_BYTES);
- out.write(getPartBoundary());
- out.write(CRLF_BYTES);
- }
- /**
- * Write the content disposition header to the specified output stream
- *
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected void sendDispositionHeader(OutputStream out) throws IOException {
- LOG.trace("enter sendDispositionHeader(OutputStream out)");
- out.write(CONTENT_DISPOSITION_BYTES);
- out.write(QUOTE_BYTES);
- out.write(EncodingUtil.getAsciiBytes(getName()));
- out.write(QUOTE_BYTES);
- }
- /**
- * Write the content type header to the specified output stream
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected void sendContentTypeHeader(OutputStream out) throws IOException {
- LOG.trace("enter sendContentTypeHeader(OutputStream out)");
- String contentType = getContentType();
- if (contentType != null) {
- out.write(CRLF_BYTES);
- out.write(CONTENT_TYPE_BYTES);
- out.write(EncodingUtil.getAsciiBytes(contentType));
- String charSet = getCharSet();
- if (charSet != null) {
- out.write(CHARSET_BYTES);
- out.write(EncodingUtil.getAsciiBytes(charSet));
- }
- }
- }
- /**
- * Write the content transfer encoding header to the specified
- * output stream
- *
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected void sendTransferEncodingHeader(OutputStream out) throws IOException {
- LOG.trace("enter sendTransferEncodingHeader(OutputStream out)");
- String transferEncoding = getTransferEncoding();
- if (transferEncoding != null) {
- out.write(CRLF_BYTES);
- out.write(CONTENT_TRANSFER_ENCODING_BYTES);
- out.write(EncodingUtil.getAsciiBytes(transferEncoding));
- }
- }
- /**
- * Write the end of the header to the output stream
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected void sendEndOfHeader(OutputStream out) throws IOException {
- LOG.trace("enter sendEndOfHeader(OutputStream out)");
- out.write(CRLF_BYTES);
- out.write(CRLF_BYTES);
- }
- /**
- * Write the data to the specified output stream
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected abstract void sendData(OutputStream out) throws IOException;
- /**
- * Return the length of the main content
- *
- * @return long The length.
- * @throws IOException If an IO problem occurs
- */
- protected abstract long lengthOfData() throws IOException;
- /**
- * Write the end data to the output stream.
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- protected void sendEnd(OutputStream out) throws IOException {
- LOG.trace("enter sendEnd(OutputStream out)");
- out.write(CRLF_BYTES);
- }
- /**
- * Write all the data to the output stream.
- * If you override this method make sure to override
- * #length() as well
- *
- * @param out The output stream
- * @throws IOException If an IO problem occurs.
- */
- public void send(OutputStream out) throws IOException {
- LOG.trace("enter send(OutputStream out)");
- sendStart(out);
- sendDispositionHeader(out);
- sendContentTypeHeader(out);
- sendTransferEncodingHeader(out);
- sendEndOfHeader(out);
- sendData(out);
- sendEnd(out);
- }
- /**
- * Return the full length of all the data.
- * If you override this method make sure to override
- * #send(OutputStream) as well
- *
- * @return long The length.
- * @throws IOException If an IO problem occurs
- */
- public long length() throws IOException {
- LOG.trace("enter length()");
- if (lengthOfData() < 0) {
- return -1;
- }
- ByteArrayOutputStream overhead = new ByteArrayOutputStream();
- sendStart(overhead);
- sendDispositionHeader(overhead);
- sendContentTypeHeader(overhead);
- sendTransferEncodingHeader(overhead);
- sendEndOfHeader(overhead);
- sendEnd(overhead);
- return overhead.size() + lengthOfData();
- }
- /**
- * Return a string representation of this object.
- * @return A string representation of this object.
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return this.getName();
- }
- /**
- * Write all parts and the last boundary to the specified output stream.
- *
- * @param out The stream to write to.
- * @param parts The parts to write.
- *
- * @throws IOException If an I/O error occurs while writing the parts.
- */
- public static void sendParts(OutputStream out, final Part[] parts)
- throws IOException {
- sendParts(out, parts, DEFAULT_BOUNDARY_BYTES);
- }
- /**
- * Write all parts and the last boundary to the specified output stream.
- *
- * @param out The stream to write to.
- * @param parts The parts to write.
- * @param partBoundary The ASCII bytes to use as the part boundary.
- *
- * @throws IOException If an I/O error occurs while writing the parts.
- *
- * @since 3.0
- */
- public static void sendParts(OutputStream out, Part[] parts, byte[] partBoundary)
- throws IOException {
- if (parts == null) {
- throw new IllegalArgumentException("Parts may not be null");
- }
- if (partBoundary == null || partBoundary.length == 0) {
- throw new IllegalArgumentException("partBoundary may not be empty");
- }
- for (int i = 0; i < parts.length; i++) {
- // set the part boundary before the part is sent
- parts[i].setPartBoundary(partBoundary);
- parts[i].send(out);
- }
- out.write(EXTRA_BYTES);
- out.write(partBoundary);
- out.write(EXTRA_BYTES);
- out.write(CRLF_BYTES);
- }
- /**
- * Return the total sum of all parts and that of the last boundary
- *
- * @param parts The parts.
- * @return The total length
- *
- * @throws IOException If an I/O error occurs while writing the parts.
- */
- public static long getLengthOfParts(Part[] parts)
- throws IOException {
- return getLengthOfParts(parts, DEFAULT_BOUNDARY_BYTES);
- }
- /**
- * Gets the length of the multipart message including the given parts.
- *
- * @param parts The parts.
- * @param partBoundary The ASCII bytes to use as the part boundary.
- * @return The total length
- *
- * @throws IOException If an I/O error occurs while writing the parts.
- *
- * @since 3.0
- */
- public static long getLengthOfParts(Part[] parts, byte[] partBoundary) throws IOException {
- LOG.trace("getLengthOfParts(Parts[])");
- if (parts == null) {
- throw new IllegalArgumentException("Parts may not be null");
- }
- long total = 0;
- for (int i = 0; i < parts.length; i++) {
- // set the part boundary before we calculate the part's length
- parts[i].setPartBoundary(partBoundary);
- long l = parts[i].length();
- if (l < 0) {
- return -1;
- }
- total += l;
- }
- total += EXTRA_BYTES.length;
- total += partBoundary.length;
- total += EXTRA_BYTES.length;
- total += CRLF_BYTES.length;
- return total;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/multipart/PartBase.java b/clients/java/src/org/apache/commons/httpclient/methods/multipart/PartBase.java
deleted file mode 100644
index e8f6a0d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/multipart/PartBase.java
+++ /dev/null
@@ -1,146 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartBase.java,v 1.5 2004/04/18 23:51:37 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
- * @param charSet The character encoding, or
null
- * @param transferEncoding The transfer encoding, or
null
- */
- public PartBase(String name, String contentType, String charSet, String transferEncoding) {
- if (name == null) {
- throw new IllegalArgumentException("Name must not be null");
- }
- this.name = name;
- this.contentType = contentType;
- this.charSet = charSet;
- this.transferEncoding = transferEncoding;
- }
- /**
- * Returns the name.
- * @return The name.
- * @see org.apache.commons.httpclient.methods.multipart.Part#getName()
- */
- public String getName() {
- return this.name;
- }
- /**
- * Returns the content type of this part.
- * @return String The name.
- */
- public String getContentType() {
- return this.contentType;
- }
- /**
- * Return the character encoding of this part.
- * @return String The name.
- */
- public String getCharSet() {
- return this.charSet;
- }
- /**
- * Returns the transfer encoding of this part.
- * @return String The name.
- */
- public String getTransferEncoding() {
- return transferEncoding;
- }
- /**
- * Sets the character encoding.
- *
- * @param charSet the character encoding, or
null
to exclude the character
- * encoding header
- */
- public void setCharSet(String charSet) {
- this.charSet = charSet;
- }
- /**
- * Sets the content type.
- *
- * @param contentType the content type, or
null
to exclude the content type header
- */
- public void setContentType(String contentType) {
- this.contentType = contentType;
- }
- /**
- * Sets the part name.
- *
- * @param name
- */
- public void setName(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Name must not be null");
- }
- this.name = name;
- }
- /**
- * Sets the transfer encoding.
- *
- * @param transferEncoding the transfer encoding, or
null
to exclude the
- * transfer encoding header
- */
- public void setTransferEncoding(String transferEncoding) {
- this.transferEncoding = transferEncoding;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/multipart/PartSource.java b/clients/java/src/org/apache/commons/httpclient/methods/multipart/PartSource.java
deleted file mode 100644
index 912f394..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/multipart/PartSource.java
+++ /dev/null
@@ -1,72 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/methods/multipart/PartSource.java,v 1.6 2004/04/18 23:51:37 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
null
- * the {@link #DEFAULT_CHARSET default} is used
- */
- public StringPart(String name, String value, String charset) {
- super(
- name,
- DEFAULT_CONTENT_TYPE,
- charset == null ? DEFAULT_CHARSET : charset,
- DEFAULT_TRANSFER_ENCODING
- );
- if (value == null) {
- throw new IllegalArgumentException("Value may not be null");
- }
- if (value.indexOf(0) != -1) {
- // See RFC 2048, 2.8. "8bit Data"
- throw new IllegalArgumentException("NULs may not be present in string parts");
- }
- this.value = value;
- }
- /**
- * Constructor.
- *
- * @param name The name of the part
- * @param value the string to post
- */
- public StringPart(String name, String value) {
- this(name, value, null);
- }
- /**
- * Gets the content in bytes. Bytes are lazily created to allow the charset to be changed
- * after the part is created.
- *
- * @return the content in bytes
- */
- private byte[] getContent() {
- if (content == null) {
- content = EncodingUtil.getBytes(value, getCharSet());
- }
- return content;
- }
- /**
- * Writes the data to the given OutputStream.
- * @param out the OutputStream to write to
- * @throws IOException if there is a write error
- */
- protected void sendData(OutputStream out) throws IOException {
- LOG.trace("enter sendData(OutputStream)");
- out.write(getContent());
- }
- /**
- * Return the length of the data.
- * @return The length of the data.
- * @throws IOException If an IO problem occurs
- * @see org.apache.commons.httpclient.methods.multipart.Part#lengthOfData()
- */
- protected long lengthOfData() throws IOException {
- LOG.trace("enter lengthOfData()");
- return getContent().length;
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.methods.multipart.BasePart#setCharSet(java.lang.String)
- */
- public void setCharSet(String charSet) {
- super.setCharSet(charSet);
- this.content = null;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/methods/multipart/package.html b/clients/java/src/org/apache/commons/httpclient/methods/multipart/package.html
deleted file mode 100644
index 21a2d16..0000000
--- a/clients/java/src/org/apache/commons/httpclient/methods/multipart/package.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
-Dname=value
- command line arguments to the application that uses
HttpClient
.
- These properties can also be set programaticly by calling
-
System.getProperties().setProperty(name, value)
.
- This is the list of properties that
HttpClient
recognizes:
- Name
- Type
- Effect
- httpclient.useragent
- String
- Sets the User-Agent string to be sent on every HTTP request.
- httpclient.authentication.preemptive
- boolean
- Sends authorization credentials without requiring explicit requests
- from the web server
diff --git a/clients/java/src/org/apache/commons/httpclient/params/DefaultHttpParams.java b/clients/java/src/org/apache/commons/httpclient/params/DefaultHttpParams.java
deleted file mode 100644
index 0506a39..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/DefaultHttpParams.java
+++ /dev/null
@@ -1,254 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/DefaultHttpParams.java,v 1.9 2004/12/21 23:15:21 olegk Exp $
- * $Revision: 510589 $
- * $Date: 2007-02-22 18:04:52 +0100 (Thu, 22 Feb 2007) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
-import java.io.Serializable;
-import java.util.HashMap;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
- * This class represents a collection of HTTP protocol parameters. Protocol parameters
- * may be linked together to form a hierarchy. If a particular parameter value has not been
- * explicitly defined in the collection itself, its value will be drawn from the parent
- * collection of parameters.
- * @author
Oleg Kalnichevski
- * @version $Revision: 510589 $
- * @since 3.0
-public class DefaultHttpParams implements HttpParams, Serializable, Cloneable {
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(DefaultHttpParams.class);
- /** HttpParams class factory. */
- private static HttpParamsFactory httpParamsFactory = new DefaultHttpParamsFactory();
- /**
- * Gets the default HttpParams to be used.
- *
- * @return the value returned from
HttpParamsFactory#getDefaultParams()
- *
- * @see HttpParamsFactory#getDefaultParams()
- */
- public static HttpParams getDefaultParams() {
- return httpParamsFactory.getDefaultParams();
- }
- /**
- * Sets the factory that will provide the default HttpParams.
- *
- * @param httpParamsFactory an instance of HttpParamsFactory
- *
- * @see #getDefaultParams()
- */
- public static void setHttpParamsFactory(HttpParamsFactory httpParamsFactory) {
- if (httpParamsFactory == null) {
- throw new IllegalArgumentException("httpParamsFactory may not be null");
- }
- DefaultHttpParams.httpParamsFactory = httpParamsFactory;
- }
- /** The set of default values to defer to */
- private HttpParams defaults = null;
- /** Hash map of HTTP parameters that this collection contains */
- private HashMap parameters = null;
- /**
- * Creates a new collection of parameters with the given parent.
- * The collection will defer to its parent for a default value
- * if a particular parameter is not explicitly set in the collection
- * itself.
- *
- * @param defaults the parent collection to defer to, if a parameter
- * is not explictly set in the collection itself.
- */
- public DefaultHttpParams(final HttpParams defaults) {
- super();
- this.defaults = defaults;
- }
- /**
- * Creates a new collection of parameters with the collection returned
- * by {@link #getDefaultParams()} as a parent. The collection will defer
- * to its parent for a default value if a particular parameter is not
- * explicitly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public DefaultHttpParams() {
- this(getDefaultParams());
- }
- public synchronized HttpParams getDefaults() {
- return this.defaults;
- }
- public synchronized void setDefaults(final HttpParams params) {
- this.defaults = params;
- }
- public synchronized Object getParameter(final String name) {
- // See if the parameter has been explicitly defined
- Object param = null;
- if (this.parameters != null) {
- param = this.parameters.get(name);
- }
- if (param != null) {
- // If so, return
- return param;
- } else {
- // If not, see if defaults are available
- if (this.defaults != null) {
- // Return default parameter value
- return this.defaults.getParameter(name);
- } else {
- // Otherwise, return null
- return null;
- }
- }
- }
- public synchronized void setParameter(final String name, final Object value) {
- if (this.parameters == null) {
- this.parameters = new HashMap();
- }
- this.parameters.put(name, value);
- if (LOG.isDebugEnabled()) {
- LOG.debug("Set parameter " + name + " = " + value);
- }
- }
- /**
- * Assigns the value to all the parameter with the given names
- *
- * @param names array of parameter name
- * @param value parameter value
- */
- public synchronized void setParameters(final String[] names, final Object value) {
- for (int i = 0; i < names.length; i++) {
- setParameter(names[i], value);
- }
- }
- public long getLongParameter(final String name, long defaultValue) {
- Object param = getParameter(name);
- if (param == null) {
- return defaultValue;
- }
- return ((Long)param).longValue();
- }
- public void setLongParameter(final String name, long value) {
- setParameter(name, new Long(value));
- }
- public int getIntParameter(final String name, int defaultValue) {
- Object param = getParameter(name);
- if (param == null) {
- return defaultValue;
- }
- return ((Integer)param).intValue();
- }
- public void setIntParameter(final String name, int value) {
- setParameter(name, new Integer(value));
- }
- public double getDoubleParameter(final String name, double defaultValue) {
- Object param = getParameter(name);
- if (param == null) {
- return defaultValue;
- }
- return ((Double)param).doubleValue();
- }
- public void setDoubleParameter(final String name, double value) {
- setParameter(name, new Double(value));
- }
- public boolean getBooleanParameter(final String name, boolean defaultValue) {
- Object param = getParameter(name);
- if (param == null) {
- return defaultValue;
- }
- return ((Boolean)param).booleanValue();
- }
- public void setBooleanParameter(final String name, boolean value) {
- setParameter(name, value ? Boolean.TRUE : Boolean.FALSE);// Boolean.valueOf() = Java 1.4+
- }
- public boolean isParameterSet(final String name) {
- return getParameter(name) != null;
- }
- public boolean isParameterSetLocally(final String name) {
- return this.parameters != null && this.parameters.get(name) != null;
- }
- public boolean isParameterTrue(final String name) {
- return getBooleanParameter(name, false);
- }
- public boolean isParameterFalse(final String name) {
- return !getBooleanParameter(name, false);
- }
- /**
- * Removes all parameters from this collection.
- */
- public void clear() {
- this.parameters = null;
- }
- /**
- * Clones this collection of parameters. Please note that paramter values
- * themselves are not cloned.
- *
- * @see java.io.Serializable
- * @see java.lang.Object#clone()
- */
- public Object clone() throws CloneNotSupportedException
- {
- DefaultHttpParams clone = (DefaultHttpParams)super.clone();
- if (this.parameters != null) {
- clone.parameters = (HashMap)this.parameters.clone();
- }
- clone.setDefaults(this.defaults);
- return clone;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java b/clients/java/src/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java
deleted file mode 100644
index e083938..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java
+++ /dev/null
@@ -1,145 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/DefaultHttpParamsFactory.java,v 1.16 2004/11/20 21:48:47 mbecke Exp $
- * $Revision: 566065 $
- * $Date: 2007-08-15 10:34:30 +0200 (Wed, 15 Aug 2007) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
-import java.util.ArrayList;
-import java.util.Arrays;
-import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
-import org.apache.commons.httpclient.HttpVersion;
-import org.apache.commons.httpclient.SimpleHttpConnectionManager;
-import org.apache.commons.httpclient.cookie.CookiePolicy;
-import org.apache.commons.httpclient.util.DateUtil;
- * @since 3.0
-public class DefaultHttpParamsFactory implements HttpParamsFactory {
- private HttpParams httpParams;
- /**
- *
- */
- public DefaultHttpParamsFactory() {
- super();
- }
- /* (non-Javadoc)
- * @see org.apache.commons.httpclient.params.HttpParamsFactory#getDefaultParams()
- */
- public synchronized HttpParams getDefaultParams() {
- if (httpParams == null) {
- httpParams = createParams();
- }
- return httpParams;
- }
- protected HttpParams createParams() {
- HttpClientParams params = new HttpClientParams(null);
- params.setParameter(HttpMethodParams.USER_AGENT, "Jakarta Commons-HttpClient/3.1");
- params.setVersion(HttpVersion.HTTP_1_1);
- params.setConnectionManagerClass(SimpleHttpConnectionManager.class);
- params.setCookiePolicy(CookiePolicy.DEFAULT);
- params.setHttpElementCharset("US-ASCII");
- params.setContentCharset("ISO-8859-1");
- params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
- ArrayList datePatterns = new ArrayList();
- datePatterns.addAll(
- Arrays.asList(
- new String[] {
- DateUtil.PATTERN_RFC1123,
- DateUtil.PATTERN_RFC1036,
- DateUtil.PATTERN_ASCTIME,
- "EEE, dd-MMM-yyyy HH:mm:ss z",
- "EEE, dd-MMM-yyyy HH-mm-ss z",
- "EEE, dd MMM yy HH:mm:ss z",
- "EEE dd-MMM-yyyy HH:mm:ss z",
- "EEE dd MMM yyyy HH:mm:ss z",
- "EEE dd-MMM-yyyy HH-mm-ss z",
- "EEE dd-MMM-yy HH:mm:ss z",
- "EEE dd MMM yy HH:mm:ss z",
- "EEE,dd-MMM-yy HH:mm:ss z",
- "EEE,dd-MMM-yyyy HH:mm:ss z",
- "EEE, dd-MM-yyyy HH:mm:ss z",
- }
- )
- );
- params.setParameter(HttpMethodParams.DATE_PATTERNS, datePatterns);
- // TODO: To be removed. Provided for backward compatibility
- String agent = null;
- try {
- agent = System.getProperty("httpclient.useragent");
- } catch (SecurityException ignore) {
- }
- if (agent != null) {
- params.setParameter(HttpMethodParams.USER_AGENT, agent);
- }
- // TODO: To be removed. Provided for backward compatibility
- String preemptiveDefault = null;
- try {
- preemptiveDefault = System.getProperty("httpclient.authentication.preemptive");
- } catch (SecurityException ignore) {
- }
- if (preemptiveDefault != null) {
- preemptiveDefault = preemptiveDefault.trim().toLowerCase();
- if (preemptiveDefault.equals("true")) {
- params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.TRUE);
- } else if (preemptiveDefault.equals("false")) {
- params.setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, Boolean.FALSE);
- }
- }
- // TODO: To be removed. Provided for backward compatibility
- String defaultCookiePolicy = null;
- try {
- defaultCookiePolicy = System.getProperty("apache.commons.httpclient.cookiespec");
- } catch (SecurityException ignore) {
- }
- if (defaultCookiePolicy != null) {
- if ("COMPATIBILITY".equalsIgnoreCase(defaultCookiePolicy)) {
- params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
- } else if ("NETSCAPE_DRAFT".equalsIgnoreCase(defaultCookiePolicy)) {
- params.setCookiePolicy(CookiePolicy.NETSCAPE);
- } else if ("RFC2109".equalsIgnoreCase(defaultCookiePolicy)) {
- params.setCookiePolicy(CookiePolicy.RFC_2109);
- }
- }
- return params;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HostParams.java b/clients/java/src/org/apache/commons/httpclient/params/HostParams.java
deleted file mode 100644
index 079824c..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HostParams.java
+++ /dev/null
@@ -1,102 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HostParams.java,v 1.5 2004/10/06 17:32:04 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
- * This class represents a collection of HTTP protocol parameters applicable to
- * {@link org.apache.commons.httpclient.HostConfiguration instances of HostConfiguration}.
- * Protocol parameters may be linked together to form a hierarchy. If a particular
- * parameter value has not been explicitly defined in the collection itself, its
- * value will be drawn from the parent collection of parameters.
- * @author
Oleg Kalnichevski
- * @version $Revision: 480424 $
- * @since 3.0
-public class HostParams extends DefaultHttpParams {
- /**
- * Defines the request headers to be sent per default with each request.
- *
- * This parameter expects a value of type {@link java.util.Collection}. The
- * collection is expected to contain {@link org.apache.commons.httpclient.Header}s.
- *
- */
- public static final String DEFAULT_HEADERS = "http.default-headers";
- /**
- * Creates a new collection of parameters with the collection returned
- * by {@link #getDefaultParams()} as a parent. The collection will defer
- * to its parent for a default value if a particular parameter is not
- * explicitly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HostParams() {
- super();
- }
- /**
- * Creates a new collection of parameters with the given parent.
- * The collection will defer to its parent for a default value
- * if a particular parameter is not explicitly set in the collection
- * itself.
- *
- * @param defaults the parent collection to defer to, if a parameter
- * is not explictly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HostParams(HttpParams defaults) {
- super(defaults);
- }
- /**
- * Sets the virtual host name.
- *
- * @param hostname The host name
- */
- public void setVirtualHost(final String hostname) {
- setParameter(HttpMethodParams.VIRTUAL_HOST, hostname);
- }
- /**
- * Returns the virtual host name.
- *
- * @return The virtual host name
- */
- public String getVirtualHost() {
- return (String) getParameter(HttpMethodParams.VIRTUAL_HOST);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HttpClientParams.java b/clients/java/src/org/apache/commons/httpclient/params/HttpClientParams.java
deleted file mode 100644
index fcbc950..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HttpClientParams.java
+++ /dev/null
@@ -1,211 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpClientParams.java,v 1.7 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
- * This class represents a collection of HTTP protocol parameters applicable to
- * {@link org.apache.commons.httpclient.HttpClient instances of HttpClient}.
- * Protocol parameters may be linked together to form a hierarchy. If a particular
- * parameter value has not been explicitly defined in the collection itself, its
- * value will be drawn from the parent collection of parameters.
- * @author
Oleg Kalnichevski
- * @version $Revision: 480424 $
- * @since 3.0
-public class HttpClientParams extends HttpMethodParams {
- /**
- * Sets the timeout in milliseconds used when retrieving an
- * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}.
- *
- * This parameter expects a value of type {@link Long}.
- *
- */
- public static final String CONNECTION_MANAGER_TIMEOUT = "http.connection-manager.timeout";
- /**
- * Defines the default
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
- * class.
- *
- * This parameter expects a value of type {@link Class}.
- *
- */
- public static final String CONNECTION_MANAGER_CLASS = "http.connection-manager.class";
- /**
- * Defines whether authentication should be attempted preemptively.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String PREEMPTIVE_AUTHENTICATION = "http.authentication.preemptive";
- /**
- * Defines whether relative redirects should be rejected.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String REJECT_RELATIVE_REDIRECT = "http.protocol.reject-relative-redirect";
- /**
- * Defines the maximum number of redirects to be followed.
- * The limit on number of redirects is intended to prevent infinite loops.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- */
- public static final String MAX_REDIRECTS = "http.protocol.max-redirects";
- /**
- * Defines whether circular redirects (redirects to the same location) should be allowed.
- * The HTTP spec is not sufficiently clear whether circular redirects are permitted,
- * therefore optionally they can be enabled
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String ALLOW_CIRCULAR_REDIRECTS = "http.protocol.allow-circular-redirects";
- /**
- * Creates a new collection of parameters with the collection returned
- * by {@link #getDefaultParams()} as a parent. The collection will defer
- * to its parent for a default value if a particular parameter is not
- * explicitly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HttpClientParams() {
- super();
- }
- /**
- * Creates a new collection of parameters with the given parent.
- * The collection will defer to its parent for a default value
- * if a particular parameter is not explicitly set in the collection
- * itself.
- *
- * @param defaults the parent collection to defer to, if a parameter
- * is not explictly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HttpClientParams(HttpParams defaults) {
- super(defaults);
- }
- /**
- * Returns the timeout in milliseconds used when retrieving an
- * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}.
- *
- * @return timeout in milliseconds.
- */
- public long getConnectionManagerTimeout() {
- return getLongParameter(CONNECTION_MANAGER_TIMEOUT, 0);
- }
- /**
- * Sets the timeout in milliseconds used when retrieving an
- * {@link org.apache.commons.httpclient.HttpConnection HTTP connection} from the
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}.
- *
- * @param timeout the timeout in milliseconds
- */
- public void setConnectionManagerTimeout(long timeout) {
- setLongParameter(CONNECTION_MANAGER_TIMEOUT, timeout);
- }
- /**
- * Returns the default
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
- * class.
- * @return {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
- * factory class.
- */
- public Class getConnectionManagerClass() {
- return (Class) getParameter(CONNECTION_MANAGER_CLASS);
- }
- /**
- * Sets {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
- * class to be used der default.
- * @param clazz
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection manager}
- * factory class.
- */
- public void setConnectionManagerClass(Class clazz) {
- setParameter(CONNECTION_MANAGER_CLASS, clazz);
- }
- /**
- * Returns
true
if authentication should be attempted preemptively,
- *
false
otherwise.
- *
- * @return
true
if authentication should be attempted preemptively,
- *
false
otherwise.
- */
- public boolean isAuthenticationPreemptive() {
- return getBooleanParameter(PREEMPTIVE_AUTHENTICATION, false);
- }
- /**
- * Sets whether authentication should be attempted preemptively.
- *
- * @param value
true
if authentication should be attempted preemptively,
- *
false
otherwise.
- */
- public void setAuthenticationPreemptive(boolean value) {
- setBooleanParameter(PREEMPTIVE_AUTHENTICATION, value);
- }
- private static final String[] PROTOCOL_STRICTNESS_PARAMETERS = {
- REJECT_RELATIVE_REDIRECT,
- ALLOW_CIRCULAR_REDIRECTS
- };
- public void makeStrict() {
- super.makeStrict();
- setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.TRUE);
- }
- public void makeLenient() {
- super.makeLenient();
- setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.FALSE);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HttpConnectionManagerParams.java b/clients/java/src/org/apache/commons/httpclient/params/HttpConnectionManagerParams.java
deleted file mode 100644
index 7c19ce5..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HttpConnectionManagerParams.java
+++ /dev/null
@@ -1,190 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpConnectionManagerParams.java,v 1.9 2004/09/13 16:25:20 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.commons.httpclient.HostConfiguration;
-import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
- * This class represents a collection of HTTP protocol parameters applicable to
- * {@link org.apache.commons.httpclient.HttpConnectionManager HTTP connection managers}.
- * Protocol parameters may be linked together to form a hierarchy. If a particular
- * parameter value has not been explicitly defined in the collection itself, its
- * value will be drawn from the parent collection of parameters.
- * @author
Oleg Kalnichevski
- * @author Michael Becke
- * @version $Revision: 480424 $
- * @since 3.0
-public class HttpConnectionManagerParams extends HttpConnectionParams {
- /**
- * Defines the maximum number of connections allowed per host configuration.
- * These values only apply to the number of connections from a particular instance
- * of HttpConnectionManager.
- *
- * This parameter expects a value of type {@link java.util.Map}. The value
- * should map instances of {@link org.apache.commons.httpclient.HostConfiguration}
- * to {@link Integer integers}. The default value can be specified using
- * {@link org.apache.commons.httpclient.HostConfiguration#ANY_HOST_CONFIGURATION}.
- *
- */
- public static final String MAX_HOST_CONNECTIONS = "http.connection-manager.max-per-host";
- /**
- * Defines the maximum number of connections allowed overall. This value only applies
- * to the number of connections from a particular instance of HttpConnectionManager.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- */
- public static final String MAX_TOTAL_CONNECTIONS = "http.connection-manager.max-total";
- /**
- * Sets the default maximum number of connections allowed for a given
- * host config.
- *
- * @param maxHostConnections The default maximum.
- *
- * @see #MAX_HOST_CONNECTIONS
- */
- public void setDefaultMaxConnectionsPerHost(int maxHostConnections) {
- setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, maxHostConnections);
- }
- /**
- * Sets the maximum number of connections to be used for the given host config.
- *
- * @param hostConfiguration The host config to set the maximum for. Use
- * {@link HostConfiguration#ANY_HOST_CONFIGURATION} to configure the default value
- * per host.
- * @param maxHostConnections The maximum number of connections,
> 0
- *
- * @see #MAX_HOST_CONNECTIONS
- */
- public void setMaxConnectionsPerHost(
- HostConfiguration hostConfiguration,
- int maxHostConnections) {
- if (maxHostConnections <= 0) {
- throw new IllegalArgumentException("maxHostConnections must be greater than 0");
- }
- Map currentValues = (Map) getParameter(MAX_HOST_CONNECTIONS);
- // param values are meant to be immutable so we'll make a copy
- // to modify
- Map newValues = null;
- if (currentValues == null) {
- newValues = new HashMap();
- } else {
- newValues = new HashMap(currentValues);
- }
- newValues.put(hostConfiguration, new Integer(maxHostConnections));
- setParameter(MAX_HOST_CONNECTIONS, newValues);
- }
- /**
- * Gets the default maximum number of connections allowed for a given
- * host config.
- *
- * @return The default maximum.
- *
- * @see #MAX_HOST_CONNECTIONS
- */
- public int getDefaultMaxConnectionsPerHost() {
- return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION);
- }
- /**
- * Gets the maximum number of connections to be used for a particular host config. If
- * the value has not been specified for the given host the default value will be
- * returned.
- *
- * @param hostConfiguration The host config.
- * @return The maximum number of connections to be used for the given host config.
- *
- * @see #MAX_HOST_CONNECTIONS
- */
- public int getMaxConnectionsPerHost(HostConfiguration hostConfiguration) {
- Map m = (Map) getParameter(MAX_HOST_CONNECTIONS);
- if (m == null) {
- // MAX_HOST_CONNECTIONS have not been configured, using the default value
- return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS;
- } else {
- Integer max = (Integer) m.get(hostConfiguration);
- if (max == null && hostConfiguration != HostConfiguration.ANY_HOST_CONFIGURATION) {
- // the value has not been configured specifically for this host config,
- // use the default value
- return getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION);
- } else {
- return (
- max == null
- ? MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS
- : max.intValue()
- );
- }
- }
- }
- /**
- * Sets the maximum number of connections allowed.
- *
- * @param maxTotalConnections The maximum number of connections allowed.
- *
- * @see #MAX_TOTAL_CONNECTIONS
- */
- public void setMaxTotalConnections(int maxTotalConnections) {
- setIntParameter(
- HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
- maxTotalConnections);
- }
- /**
- * Gets the maximum number of connections allowed.
- *
- * @return The maximum number of connections allowed.
- *
- * @see #MAX_TOTAL_CONNECTIONS
- */
- public int getMaxTotalConnections() {
- return getIntParameter(
- HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
- MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HttpConnectionParams.java b/clients/java/src/org/apache/commons/httpclient/params/HttpConnectionParams.java
deleted file mode 100644
index 1e7fd6a..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HttpConnectionParams.java
+++ /dev/null
@@ -1,306 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpConnectionParams.java,v 1.6 2004/09/15 20:32:21 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
- * This class represents a collection of HTTP protocol parameters applicable to
- * {@link org.apache.commons.httpclient.HttpConnection HTTP connections}.
- * Protocol parameters may be linked together to form a hierarchy. If a particular
- * parameter value has not been explicitly defined in the collection itself, its
- * value will be drawn from the parent collection of parameters.
- * @author
Oleg Kalnichevski
- * @version $Revision: 480424 $
- * @since 3.0
-public class HttpConnectionParams extends DefaultHttpParams {
- /**
- * Defines the default socket timeout (
SO_TIMEOUT
) in milliseconds which is the
- * timeout for waiting for data. A timeout value of zero is interpreted as an infinite
- * timeout. This value is used when no socket timeout is set in the
- * {@link HttpMethodParams HTTP method parameters}.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- * @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.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- * @see java.net.SocketOptions#TCP_NODELAY
- */
- public static final String TCP_NODELAY = "http.tcp.nodelay";
- /**
- * Determines a hint the size of the underlying buffers used by the platform
- * for outgoing network I/O. This value is a suggestion to the kernel from
- * the application about the size of buffers to use for the data to be sent
- * over the socket.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- * @see java.net.SocketOptions#SO_SNDBUF
- */
- public static final String SO_SNDBUF = "http.socket.sendbuffer";
- /**
- * Determines a hint the size of the underlying buffers used by the platform
- * for incoming network I/O. This value is a suggestion to the kernel from
- * the application about the size of buffers to use for the data to be received
- * over the socket.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- * @see java.net.SocketOptions#SO_RCVBUF
- */
- public static final String SO_RCVBUF = "http.socket.receivebuffer";
- /**
- * Sets SO_LINGER with the specified linger time in seconds. The maximum timeout
- * value is platform specific. Value
0
implies that the option is disabled.
- * Value
-1
implies that the JRE default is used. The setting only affects
- * socket close.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- * @see java.net.SocketOptions#SO_LINGER
- */
- public static final String SO_LINGER = "http.socket.linger";
- /**
- * Determines the timeout until a connection is etablished. A value of zero
- * means the timeout is not used. The default value is zero.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- */
- public static final String CONNECTION_TIMEOUT = "http.connection.timeout";
- /**
- * Determines whether stale connection check is to be used. Disabling
- * stale connection check may result in slight performance improvement
- * at the risk of getting an I/O error when executing a request over a
- * connection that has been closed at the server side.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String STALE_CONNECTION_CHECK = "http.connection.stalecheck";
- /**
- * Creates a new collection of parameters with the collection returned
- * by {@link #getDefaultParams()} as a parent. The collection will defer
- * to its parent for a default value if a particular parameter is not
- * explicitly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HttpConnectionParams() {
- super();
- }
- /**
- * Returns the default socket timeout (
SO_TIMEOUT
) in milliseconds which is the
- * timeout for waiting for data. A timeout value of zero is interpreted as an infinite
- * timeout. This value is used when no socket timeout is set in the
- * {@link HttpMethodParams HTTP method parameters}.
- *
- * @return timeout in milliseconds
- */
- public int getSoTimeout() {
- return getIntParameter(SO_TIMEOUT, 0);
- }
- /**
- * Sets the default socket timeout (
SO_TIMEOUT
) in milliseconds which is the
- * timeout for waiting for data. A timeout value of zero is interpreted as an infinite
- * timeout. This value is used when no socket timeout is set in the
- * {@link HttpMethodParams HTTP method parameters}.
- *
- * @param timeout Timeout in milliseconds
- */
- public void setSoTimeout(int timeout) {
- setIntParameter(SO_TIMEOUT, 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.
- *
- * @param value
true
if the Nagle's algorithm is to NOT be used
- * (that is enable TCP_NODELAY),
false
otherwise.
- */
- public void setTcpNoDelay(boolean value) {
- setBooleanParameter(TCP_NODELAY, value);
- }
- /**
- * Tests if Nagle's algorithm is to be used.
- *
- * @return
true
if the Nagle's algorithm is to NOT be used
- * (that is enable TCP_NODELAY),
false
otherwise.
- */
- public boolean getTcpNoDelay() {
- return getBooleanParameter(TCP_NODELAY, true);
- }
- /**
- * Returns a hint the size of the underlying buffers used by the platform for
- * outgoing network I/O. This value is a suggestion to the kernel from the
- * application about the size of buffers to use for the data to be sent over
- * the socket.
- *
- * @return the hint size of the send buffer
- */
- public int getSendBufferSize() {
- return getIntParameter(SO_SNDBUF, -1);
- }
- /**
- * Sets a hint the size of the underlying buffers used by the platform for
- * outgoing network I/O. This value is a suggestion to the kernel from the
- * application about the size of buffers to use for the data to be sent over
- * the socket.
- *
- * @param size the hint size of the send buffer
- */
- public void setSendBufferSize(int size) {
- setIntParameter(SO_SNDBUF, size);
- }
- /**
- * Returns a hint the size of the underlying buffers used by the platform
- * for incoming network I/O. This value is a suggestion to the kernel from
- * the application about the size of buffers to use for the data to be received
- * over the socket.
- *
- * @return the hint size of the send buffer
- */
- public int getReceiveBufferSize() {
- return getIntParameter(SO_RCVBUF, -1);
- }
- /**
- * Sets a hint the size of the underlying buffers used by the platform
- * for incoming network I/O. This value is a suggestion to the kernel from
- * the application about the size of buffers to use for the data to be received
- * over the socket.
- *
- * @param size the hint size of the send buffer
- */
- public void setReceiveBufferSize(int size) {
- setIntParameter(SO_RCVBUF, size);
- }
- /**
- * Returns linger-on-close timeout. Value
0
implies that the option is
- * disabled. Value
-1
implies that the JRE default is used.
- *
- * @return the linger-on-close timeout
- */
- public int getLinger() {
- return getIntParameter(SO_LINGER, -1);
- }
- /**
- * Returns linger-on-close timeout. This option disables/enables immediate return
- * from a close() of a TCP Socket. Enabling this option with a non-zero Integer
- * timeout means that a close() will block pending the transmission and
- * acknowledgement of all data written to the peer, at which point the socket is
- * closed gracefully. Value
0
implies that the option is
- * disabled. Value
-1
implies that the JRE default is used.
- *
- * @param value the linger-on-close timeout
- */
- public void setLinger(int value) {
- setIntParameter(SO_LINGER, value);
- }
- /**
- * Returns the timeout until a connection is etablished. A value of zero
- * means the timeout is not used. The default value is zero.
- *
- * @return timeout in milliseconds.
- */
- public int getConnectionTimeout() {
- return getIntParameter(CONNECTION_TIMEOUT, 0);
- }
- /**
- * Sets the timeout until a connection is etablished. A value of zero
- * means the timeout is not used. The default value is zero.
- *
- * @param timeout Timeout in milliseconds.
- */
- public void setConnectionTimeout(int timeout) {
- setIntParameter(CONNECTION_TIMEOUT, timeout);
- }
- /**
- * Tests whether stale connection check is to be used. Disabling
- * stale connection check may result in slight performance improvement
- * at the risk of getting an I/O error when executing a request over a
- * connection that has been closed at the server side.
- *
- * @return
true
if stale connection check is to be used,
- *
false
otherwise.
- */
- public boolean isStaleCheckingEnabled() {
- return getBooleanParameter(STALE_CONNECTION_CHECK, true);
- }
- /**
- * Defines whether stale connection check is to be used. Disabling
- * stale connection check may result in slight performance improvement
- * at the risk of getting an I/O error when executing a request over a
- * connection that has been closed at the server side.
- *
- * @param value
true
if stale connection check is to be used,
- *
false
otherwise.
- */
- public void setStaleCheckingEnabled(boolean value) {
- setBooleanParameter(STALE_CONNECTION_CHECK, value);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HttpMethodParams.java b/clients/java/src/org/apache/commons/httpclient/params/HttpMethodParams.java
deleted file mode 100644
index aa7e9bb..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HttpMethodParams.java
+++ /dev/null
@@ -1,522 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpMethodParams.java,v 1.17 2004/10/06 17:32:04 olegk Exp $
- * $Revision: 483949 $
- * $Date: 2006-12-08 12:34:50 +0100 (Fri, 08 Dec 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
-import org.apache.commons.httpclient.HttpVersion;
-import org.apache.commons.httpclient.cookie.CookiePolicy;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
- * This class represents a collection of HTTP protocol parameters applicable to
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}. Protocol
- * parameters may be linked together to form a hierarchy. If a particular
- * parameter value has not been explicitly defined in the collection itself,
- * its value will be drawn from the parent collection of parameters.
- * @author
Oleg Kalnichevski
- * @author Christian Kohlschuetter
- * @version $Revision: 483949 $
- * @since 3.0
-public class HttpMethodParams extends DefaultHttpParams {
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(HttpMethodParams.class);
- /**
- * Defines the content of the
User-Agent
header used by
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}.
- *
- * This parameter expects a value of type {@link String}.
- *
- */
- public static final String USER_AGENT = "http.useragent";
- /**
- * Defines the {@link HttpVersion HTTP protocol version} used by
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} per
- * default.
- *
- * This parameter expects a value of type {@link HttpVersion}.
- *
- */
- public static final String PROTOCOL_VERSION = "http.protocol.version";
- /**
- * Defines whether {@link org.apache.commons.httpclient.HttpMethod HTTP methods} should
- * reject ambiguous {@link org.apache.commons.httpclient.StatusLine HTTP status line}.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String UNAMBIGUOUS_STATUS_LINE = "http.protocol.unambiguous-statusline";
- /**
- * Defines whether {@link org.apache.commons.httpclient.Cookie cookies} should be put on
- * a single {@link org.apache.commons.httpclient.Header response header}.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String SINGLE_COOKIE_HEADER = "http.protocol.single-cookie-header";
- /**
- * Defines whether responses with an invalid
Transfer-Encoding
header should be
- * rejected.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String STRICT_TRANSFER_ENCODING = "http.protocol.strict-transfer-encoding";
- /**
- * Defines whether the content body sent in response to
- * {@link org.apache.commons.httpclient.methods.HeadMethod} should be rejected.
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String REJECT_HEAD_BODY = "http.protocol.reject-head-body";
- /**
- * Sets period of time in milliseconds to wait for a content body sent in response to
- * {@link org.apache.commons.httpclient.methods.HeadMethod HEAD method} from a
- * non-compliant server. If the parameter is not set or set to
-1
non-compliant
- * response body check is disabled.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- */
- public static final String HEAD_BODY_CHECK_TIMEOUT = "http.protocol.head-body-timeout";
- /**
- *
- * Activates 'Expect: 100-Continue' handshake for the
- * {@link org.apache.commons.httpclient.methods.ExpectContinueMethod
- * entity enclosing methods}. The purpose of the 'Expect: 100-Continue'
- * handshake 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.
- *
- *
- *
- * The use of the 'Expect: 100-continue' handshake can result in
- * noticable peformance improvement for entity enclosing requests
- * (such as POST and PUT) that require the target server's
- * authentication.
- *
- *
- *
- * '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.
- *
- *
- * This parameter expects a value of type {@link Boolean}.
- */
- public static final String USE_EXPECT_CONTINUE = "http.protocol.expect-continue";
- /**
- * Defines the charset to be used when encoding
- * {@link org.apache.commons.httpclient.Credentials}. If not defined then the
- * {@link #HTTP_ELEMENT_CHARSET} should be used.
- *
- * This parameter expects a value of type {@link String}.
- *
- */
- public static final String CREDENTIAL_CHARSET = "http.protocol.credential-charset";
- /**
- * Defines the charset to be used for encoding HTTP protocol elements.
- *
- * This parameter expects a value of type {@link String}.
- *
- */
- public static final String HTTP_ELEMENT_CHARSET = "http.protocol.element-charset";
- /**
- * Defines the charset to be used for parsing URIs.
- *
- * This parameter expects a value of type {@link String}.
- *
- */
- public static final String HTTP_URI_CHARSET = "http.protocol.uri-charset";
- /**
- * Defines the charset to be used for encoding content body.
- *
- * This parameter expects a value of type {@link String}.
- *
- */
- public static final String HTTP_CONTENT_CHARSET = "http.protocol.content-charset";
- /**
- * Defines {@link CookiePolicy cookie policy} to be used for cookie management.
- *
- * This parameter expects a value of type {@link String}.
- *
- */
- public static final String COOKIE_POLICY = "http.protocol.cookie-policy";
- /**
- * Defines HttpClient's behavior when a response provides more bytes than
- * expected (specified with Content-Length, for example).
- *
- * Such surplus data makes the HTTP connection unreliable for keep-alive
- * requests, as malicious response data (faked headers etc.) can lead to undesired
- * results on the next request using that connection.
- *
- *
- * If this parameter is set to
true
, any detection of extra
- * input data will generate a warning in the log.
- *
- *
- * This parameter expects a value of type {@link Boolean}.
- *
- */
- public static final String WARN_EXTRA_INPUT = "http.protocol.warn-extra-input";
- /**
- * Defines the maximum number of ignorable lines before we expect
- * a HTTP response's status code.
- *
- * With HTTP/1.1 persistent connections, the problem arises that
- * broken scripts could return a wrong Content-Length
- * (there are more bytes sent than specified).
- * Unfortunately, in some cases, this is not possible after the bad response,
- * but only before the next one.
- * So, HttpClient must be able to skip those surplus lines this way.
- *
- *
- * Set this to 0 to disallow any garbage/empty lines before the status line.
- * To specify no limit, use {@link java.lang.Integer#MAX_VALUE} (default in lenient mode).
- *
- *
- * This parameter expects a value of type {@link Integer}.
- */
- public static final String STATUS_LINE_GARBAGE_LIMIT = "http.protocol.status-line-garbage-limit";
- /**
- * Sets the socket timeout (
SO_TIMEOUT
) in milliseconds to be used when executing the method.
- * A timeout value of zero is interpreted as an infinite timeout.
- *
- * This parameter expects a value of type {@link Integer}.
- *
- * @see java.net.SocketOptions#SO_TIMEOUT
- */
- public static final String SO_TIMEOUT = "http.socket.timeout";
- /**
- * The key used to look up the date patterns used for parsing. The String patterns are stored
- * in a {@link java.util.Collection} and must be compatible with
- * {@link java.text.SimpleDateFormat}.
- *
- * This parameter expects a value of type {@link java.util.Collection}.
- *
- */
- public static final String DATE_PATTERNS = "http.dateparser.patterns";
- /**
- * Sets the method retry handler parameter.
- *
- * This parameter expects a value of type {@link org.apache.commons.httpclient.HttpMethodRetryHandler}.
- *
- */
- public static final String RETRY_HANDLER = "http.method.retry-handler";
- /**
- * Sets the maximum buffered response size (in bytes) that triggers no warning. Buffered
- * responses exceeding this size will trigger a warning in the log.
- *
- * This parameter expects a value if type {@link Integer}.
- *
- */
- public static final String BUFFER_WARN_TRIGGER_LIMIT = "http.method.response.buffer.warnlimit";
- /**
- * Defines the virtual host name.
- *
- * This parameter expects a value of type {@link java.lang.String}.
- *
- */
- public static final String VIRTUAL_HOST = "http.virtual-host";
- /**
- * Sets the value to use as the multipart boundary.
- *
- * This parameter expects a value if type {@link String}.
- *
- * @see org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity
- */
- public static final String MULTIPART_BOUNDARY = "http.method.multipart.boundary";
- /**
- * Creates a new collection of parameters with the collection returned
- * by {@link #getDefaultParams()} as a parent. The collection will defer
- * to its parent for a default value if a particular parameter is not
- * explicitly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HttpMethodParams() {
- super(getDefaultParams());
- }
- /**
- * Creates a new collection of parameters with the given parent.
- * The collection will defer to its parent for a default value
- * if a particular parameter is not explicitly set in the collection
- * itself.
- *
- * @param defaults the parent collection to defer to, if a parameter
- * is not explictly set in the collection itself.
- *
- * @see #getDefaultParams()
- */
- public HttpMethodParams(HttpParams defaults) {
- super(defaults);
- }
- /**
- * Returns the charset to be used for writing HTTP headers.
- * @return The charset
- */
- public String getHttpElementCharset() {
- String charset = (String) getParameter(HTTP_ELEMENT_CHARSET);
- if (charset == null) {
- LOG.warn("HTTP element charset not configured, using US-ASCII");
- charset = "US-ASCII";
- }
- return charset;
- }
- /**
- * Sets the charset to be used for writing HTTP headers.
- * @param charset The charset
- */
- public void setHttpElementCharset(String charset) {
- setParameter(HTTP_ELEMENT_CHARSET, charset);
- }
- /**
- * Returns the default charset to be used for writing content body,
- * when no charset explicitly specified.
- * @return The charset
- */
- public String getContentCharset() {
- String charset = (String) getParameter(HTTP_CONTENT_CHARSET);
- if (charset == null) {
- LOG.warn("Default content charset not configured, using ISO-8859-1");
- charset = "ISO-8859-1";
- }
- return charset;
- }
- /**
- * Sets the charset to be used for parsing URIs.
- * @param charset The charset
- */
- public void setUriCharset(String charset) {
- setParameter(HTTP_URI_CHARSET, charset);
- }
- /**
- * Returns the charset to be used for parsing URIs.
- * @return The charset
- */
- public String getUriCharset() {
- String charset = (String) getParameter(HTTP_URI_CHARSET);
- if (charset == null) {
- charset = "UTF-8";
- }
- return charset;
- }
- /**
- * Sets the default charset to be used for writing content body,
- * when no charset explicitly specified.
- * @param charset The charset
- */
- public void setContentCharset(String charset) {
- setParameter(HTTP_CONTENT_CHARSET, charset);
- }
- /**
- * Returns the charset to be used for {@link org.apache.commons.httpclient.Credentials}. If
- * not configured the {@link #HTTP_ELEMENT_CHARSET HTTP element charset} is used.
- * @return The charset
- */
- public String getCredentialCharset() {
- String charset = (String) getParameter(CREDENTIAL_CHARSET);
- if (charset == null) {
- LOG.debug("Credential charset not configured, using HTTP element charset");
- charset = getHttpElementCharset();
- }
- return charset;
- }
- /**
- * Sets the charset to be used for writing HTTP headers.
- * @param charset The charset
- */
- public void setCredentialCharset(String charset) {
- setParameter(CREDENTIAL_CHARSET, charset);
- }
- /**
- * Returns {@link HttpVersion HTTP protocol version} to be used by the
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that
- * this collection of parameters applies to.
- *
- * @return {@link HttpVersion HTTP protocol version}
- */
- public HttpVersion getVersion() {
- Object param = getParameter(PROTOCOL_VERSION);
- if (param == null) {
- return HttpVersion.HTTP_1_1;
- }
- return (HttpVersion)param;
- }
- /**
- * Assigns the {@link HttpVersion HTTP protocol version} to be used by the
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods} that
- * this collection of parameters applies to.
- *
- * @param version the {@link HttpVersion HTTP protocol version}
- */
- public void setVersion(HttpVersion version) {
- setParameter(PROTOCOL_VERSION, version);
- }
- /**
- * Returns {@link CookiePolicy cookie policy} to be used by the
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}
- * this collection of parameters applies to.
- *
- * @return {@link CookiePolicy cookie policy}
- */
- public String getCookiePolicy() {
- Object param = getParameter(COOKIE_POLICY);
- if (param == null) {
- return CookiePolicy.DEFAULT;
- }
- return (String)param;
- }
- /**
- * Assigns the {@link CookiePolicy cookie policy} to be used by the
- * {@link org.apache.commons.httpclient.HttpMethod HTTP methods}
- * this collection of parameters applies to.
- *
- * @param policy the {@link CookiePolicy cookie policy}
- */
- public void setCookiePolicy(String policy) {
- setParameter(COOKIE_POLICY, policy);
- }
- /**
- * Returns the default socket timeout (
SO_TIMEOUT
) in milliseconds which is the
- * timeout for waiting for data. A timeout value of zero is interpreted as an infinite
- * timeout.
- *
- * @return timeout in milliseconds
- */
- public int getSoTimeout() {
- return getIntParameter(SO_TIMEOUT, 0);
- }
- /**
- * Sets the default socket timeout (
SO_TIMEOUT
) in milliseconds which is the
- * timeout for waiting for data. A timeout value of zero is interpreted as an infinite
- * timeout.
- *
- * @param timeout Timeout in milliseconds
- */
- public void setSoTimeout(int timeout) {
- setIntParameter(SO_TIMEOUT, timeout);
- }
- /**
- * Sets the virtual host name.
- *
- * @param hostname The host name
- */
- public void setVirtualHost(final String hostname) {
- setParameter(VIRTUAL_HOST, hostname);
- }
- /**
- * Returns the virtual host name.
- *
- * @return The virtual host name
- */
- public String getVirtualHost() {
- return (String) getParameter(VIRTUAL_HOST);
- }
- private static final String[] PROTOCOL_STRICTNESS_PARAMETERS = {
- UNAMBIGUOUS_STATUS_LINE,
- SINGLE_COOKIE_HEADER,
- STRICT_TRANSFER_ENCODING,
- REJECT_HEAD_BODY,
- WARN_EXTRA_INPUT
- };
- /**
- * Makes the {@link org.apache.commons.httpclient.HttpMethod HTTP methods}
- * strictly follow the HTTP protocol specification (RFC 2616 and other relevant RFCs).
- * It must be noted that popular HTTP agents have different degree of HTTP protocol
- * compliance and some HTTP serves are programmed to expect the behaviour that does not
- * strictly adhere to the HTTP specification.
- */
- public void makeStrict() {
- setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.TRUE);
- setIntParameter(STATUS_LINE_GARBAGE_LIMIT, 0);
- }
- /**
- * Makes the {@link org.apache.commons.httpclient.HttpMethod HTTP methods}
- * attempt to mimic the exact behaviour of commonly used HTTP agents,
- * which many HTTP servers expect, even though such behaviour may violate
- * the HTTP protocol specification (RFC 2616 and other relevant RFCs).
- */
- public void makeLenient() {
- setParameters(PROTOCOL_STRICTNESS_PARAMETERS, Boolean.FALSE);
- setIntParameter(STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HttpParams.java b/clients/java/src/org/apache/commons/httpclient/params/HttpParams.java
deleted file mode 100644
index 77ee3cc..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HttpParams.java
+++ /dev/null
@@ -1,232 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpParams.java,v 1.6 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
- * This interface represents a collection of HTTP protocol parameters. Protocol parameters
- * may be linked together to form a hierarchy. If a particular parameter value has not been
- * explicitly defined in the collection itself, its value will be drawn from the parent
- * collection of parameters.
- * @author
Oleg Kalnichevski
- * @version $Revision: 480424 $
- * @since 3.0
-public interface HttpParams {
- /**
- * Returns the parent collection that this collection will defer to
- * for a default value if a particular parameter is not explicitly
- * set in the collection itself
- *
- * @return the parent collection to defer to, if a particular parameter
- * is not explictly set in the collection itself.
- *
- * @see #setDefaults(HttpParams)
- */
- public HttpParams getDefaults();
- /**
- * Assigns the parent collection that this collection will defer to
- * for a default value if a particular parameter is not explicitly
- * set in the collection itself
- *
- * @param params the parent collection to defer to, if a particular
- * parameter is not explictly set in the collection itself.
- *
- * @see #getDefaults()
- */
- public void setDefaults(final HttpParams params);
- /**
- * Returns a parameter value with the given name. If the parameter is
- * not explicitly defined in this collection, its value will be drawn
- * from a higer level collection at which this parameter is defined.
- * If the parameter is not explicitly set anywhere up the hierarchy,
- *
null
value is returned.
- *
- * @param name the parent name.
- *
- * @return an object that represents the value of the parameter.
- *
- * @see #setParameter(String, Object)
- */
- public Object getParameter(final String name);
- /**
- * Assigns the value to the parameter with the given name
- *
- * @param name parameter name
- * @param value parameter value
- */
- public void setParameter(final String name, final Object value);
- /**
- * Returns a {@link Long} parameter value with the given name.
- * If the parameter is not explicitly defined in this collection, its
- * value will be drawn from a higer level collection at which this parameter
- * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
- * 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)
- */
- public long getLongParameter(final String name, long defaultValue);
- /**
- * Assigns a {@link Long} to the parameter with the given name
- *
- * @param name parameter name
- * @param value parameter value
- */
- public void setLongParameter(final String name, long value);
- /**
- * Returns an {@link Integer} parameter value with the given name.
- * If the parameter is not explicitly defined in this collection, its
- * value will be drawn from a higer level collection at which this parameter
- * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
- * 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)
- */
- public int getIntParameter(final String name, int defaultValue);
- /**
- * Assigns an {@link Integer} to the parameter with the given name
- *
- * @param name parameter name
- * @param value parameter value
- */
- public void setIntParameter(final String name, int value);
- /**
- * Returns a {@link Double} parameter value with the given name.
- * If the parameter is not explicitly defined in this collection, its
- * value will be drawn from a higer level collection at which this parameter
- * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
- * 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)
- */
- public double getDoubleParameter(final String name, double defaultValue);
- /**
- * Assigns a {@link Double} to the parameter with the given name
- *
- * @param name parameter name
- * @param value parameter value
- */
- public void setDoubleParameter(final String name, double value);
- /**
- * Returns a {@link Boolean} parameter value with the given name.
- * If the parameter is not explicitly defined in this collection, its
- * value will be drawn from a higer level collection at which this parameter
- * is defined. If the parameter is not explicitly set anywhere up the hierarchy,
- * 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)
- */
- public boolean getBooleanParameter(final String name, boolean defaultValue);
- /**
- * Assigns a {@link Boolean} to the parameter with the given name
- *
- * @param name parameter name
- * @param value parameter value
- */
- public void setBooleanParameter(final String name, boolean value);
- /**
- * Returns
true
if the parameter is set at any level,
false
otherwise.
- *
- * @param name parameter name
- *
- * @return
true
if the parameter is set at any level,
false
- * otherwise.
- */
- public boolean isParameterSet(final String name);
- /**
- * Returns
true
if the parameter is set locally,
false
otherwise.
- *
- * @param name parameter name
- *
- * @return
true
if the parameter is set locally,
false
- * otherwise.
- */
- public boolean isParameterSetLocally(final String name);
- /**
- * Returns
true
if the parameter is set and is
true
,
false
- * otherwise.
- *
- * @param name parameter name
- *
- * @return
true
if the parameter is set and is
true
,
false
- * otherwise.
- */
- public boolean isParameterTrue(final String name);
- /**
- * Returns
true
if the parameter is either not set or is
false
,
- *
false
otherwise.
- *
- * @param name parameter name
- *
- * @return
true
if the parameter is either not set or is
false
,
- *
false
otherwise.
- */
- public boolean isParameterFalse(final String name);
diff --git a/clients/java/src/org/apache/commons/httpclient/params/HttpParamsFactory.java b/clients/java/src/org/apache/commons/httpclient/params/HttpParamsFactory.java
deleted file mode 100644
index 312b8a3..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/HttpParamsFactory.java
+++ /dev/null
@@ -1,51 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/params/HttpParamsFactory.java,v 1.5 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.params;
- * A factory for getting the default set of parameters to use when creating an instance of
- *
HttpParams
.
- * @see org.apache.commons.httpclient.params.DefaultHttpParams#setHttpParamsFactory(HttpParamsFactory)
- * @since 3.0
-public interface HttpParamsFactory {
- /**
- * Gets the default parameters. This method may be called more than once and is not required
- * to always return the same value.
- *
- * @return an instance of HttpParams
- */
- HttpParams getDefaultParams();
diff --git a/clients/java/src/org/apache/commons/httpclient/params/package.html b/clients/java/src/org/apache/commons/httpclient/params/package.html
deleted file mode 100644
index c4be9e8..0000000
--- a/clients/java/src/org/apache/commons/httpclient/params/package.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
Package Documentation for org.apache.commons.httpclient.params
- HttpClient preferences framework.
- @since 3.0
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.java b/clients/java/src/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.java
deleted file mode 100644
index db9de65..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.java
+++ /dev/null
@@ -1,164 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ControllerThreadSocketFactory.java,v 1.2 2004/04/18 23:51:38 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.util.TimeoutController;
- * This helper class is intedned to help work around the limitation of older Java versions
- * (older than 1.4) that prevents from specifying a connection timeout when creating a
- * socket. This factory executes a controller thread overssing the process of socket
- * initialisation. If the socket constructor cannot be created within the specified time
- * limit, the controller terminates and throws an {@link ConnectTimeoutException}
- * @author Ortwin Glueck
- * @author Oleg Kalnichevski
- * @since 3.0
-public final class ControllerThreadSocketFactory {
- private ControllerThreadSocketFactory() {
- super();
- }
- /**
- * This method spawns a controller thread overseeing the process of socket
- * initialisation. If the socket constructor cannot be created within the specified time
- * limit, the controller terminates and throws an {@link ConnectTimeoutException}
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param timeout the timeout value to be used in milliseconds. If the socket cannot be
- * completed within the given time limit, it will be abandoned
- *
- * @return a connected Socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- * @throws ConnectTimeoutException if socket cannot be connected within the
- * given time limit
- *
- */
- public static Socket createSocket(
- final ProtocolSocketFactory socketfactory,
- final String host,
- final int port,
- final InetAddress localAddress,
- final int localPort,
- int timeout)
- throws IOException, UnknownHostException, ConnectTimeoutException
- {
- SocketTask task = new SocketTask() {
- public void doit() throws IOException {
- setSocket(socketfactory.createSocket(host, port, localAddress, localPort));
- }
- };
- try {
- TimeoutController.execute(task, timeout);
- } catch (TimeoutController.TimeoutException e) {
- throw new ConnectTimeoutException(
- "The host did not accept the connection within timeout of "
- + timeout + " ms");
- }
- Socket socket = task.getSocket();
- if (task.exception != null) {
- throw task.exception;
- }
- return socket;
- }
- public static Socket createSocket(final SocketTask task, int timeout)
- throws IOException, UnknownHostException, ConnectTimeoutException
- {
- try {
- TimeoutController.execute(task, timeout);
- } catch (TimeoutController.TimeoutException e) {
- throw new ConnectTimeoutException(
- "The host did not accept the connection within timeout of "
- + timeout + " ms");
- }
- Socket socket = task.getSocket();
- if (task.exception != null) {
- throw task.exception;
- }
- return socket;
- }
- /**
- * Helper class for wrapping socket based tasks.
- */
- public static abstract class SocketTask implements Runnable {
- /** The socket */
- private Socket socket;
- /** The exception */
- private IOException exception;
- /**
- * Set the socket.
- * @param newSocket The new socket.
- */
- protected void setSocket(final Socket newSocket) {
- socket = newSocket;
- }
- /**
- * Return the socket.
- * @return Socket The socket.
- */
- protected Socket getSocket() {
- return socket;
- }
- /**
- * Perform the logic.
- * @throws IOException If an IO problem occurs
- */
- public abstract void doit() throws IOException;
- /** Execute the logic in this object and keep track of any exceptions. */
- public void run() {
- try {
- doit();
- } catch (IOException e) {
- exception = e;
- }
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.java b/clients/java/src/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.java
deleted file mode 100644
index 011d4bf..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.java
+++ /dev/null
@@ -1,157 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/DefaultProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.params.HttpConnectionParams;
- * The default class for creating protocol sockets. This class just uses the
- * {@link java.net.Socket socket} constructors.
- * @author Michael Becke
- * @since 2.0
-public class DefaultProtocolSocketFactory implements ProtocolSocketFactory {
- /**
- * The factory singleton.
- */
- private static final DefaultProtocolSocketFactory factory = new DefaultProtocolSocketFactory();
- /**
- * Gets an singleton instance of the DefaultProtocolSocketFactory.
- * @return a DefaultProtocolSocketFactory
- */
- static DefaultProtocolSocketFactory getSocketFactory() {
- return factory;
- }
- /**
- * Constructor for DefaultProtocolSocketFactory.
- */
- public DefaultProtocolSocketFactory() {
- super();
- }
- /**
- * @see #createSocket(java.lang.String,int,java.net.InetAddress,int)
- */
- public Socket createSocket(
- String host,
- int port,
- InetAddress localAddress,
- int localPort
- ) throws IOException, UnknownHostException {
- return new Socket(host, port, localAddress, localPort);
- }
- /**
- * Attempts to get a new socket connection to the given host within the given time limit.
- *
- * This method employs several techniques to circumvent the limitations of older JREs that
- * do not support connect timeout. When running in JRE 1.4 or above reflection is used to
- * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older
- * JREs a controller thread is executed. The controller thread attempts to create a new socket
- * within the given limit of time. If socket constructor does not return until the timeout
- * expires, the controller terminates and throws an {@link ConnectTimeoutException}
- *
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param params {@link HttpConnectionParams Http connection parameters}
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- * @throws ConnectTimeoutException if socket cannot be connected within the
- * given time limit
- *
- * @since 3.0
- */
- public Socket createSocket(
- final String host,
- final int port,
- final InetAddress localAddress,
- final int localPort,
- final HttpConnectionParams params
- ) throws IOException, UnknownHostException, ConnectTimeoutException {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- int timeout = params.getConnectionTimeout();
- if (timeout == 0) {
- return createSocket(host, port, localAddress, localPort);
- } else {
- // To be eventually deprecated when migrated to Java 1.4 or above
- Socket socket = ReflectionSocketFactory.createSocket(
- "javax.net.SocketFactory", host, port, localAddress, localPort, timeout);
- if (socket == null) {
- socket = ControllerThreadSocketFactory.createSocket(
- this, host, port, localAddress, localPort, timeout);
- }
- return socket;
- }
- }
- /**
- * @see ProtocolSocketFactory#createSocket(java.lang.String,int)
- */
- public Socket createSocket(String host, int port)
- throws IOException, UnknownHostException {
- return new Socket(host, port);
- }
- /**
- * All instances of DefaultProtocolSocketFactory are the same.
- */
- public boolean equals(Object obj) {
- return ((obj != null) && obj.getClass().equals(getClass()));
- }
- /**
- * All instances of DefaultProtocolSocketFactory have the same hash code.
- */
- public int hashCode() {
- return getClass().hashCode();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/Protocol.java b/clients/java/src/org/apache/commons/httpclient/protocol/Protocol.java
deleted file mode 100644
index b176db1..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/Protocol.java
+++ /dev/null
@@ -1,296 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/Protocol.java,v 1.10 2004/04/18 23:51:38 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.commons.httpclient.util.LangUtils;
- * A class to encapsulate the specifics of a protocol. This class class also
- * provides the ability to customize the set and characteristics of the
- * protocols used.
- *
One use case for modifying the default set of protocols would be to set a
- * custom SSL socket factory. This would look something like the following:
- * Protocol myHTTPS = new Protocol( "https", new MySSLSocketFactory(), 443 );
- * Protocol.registerProtocol( "https", myHTTPS );
- * @author Michael Becke
- * @author Jeff Dever
- * @author
Mike Bowler
- * @since 2.0
-public class Protocol {
- /** The available protocols */
- private static final Map PROTOCOLS = Collections.synchronizedMap(new HashMap());
- /**
- * Registers a new protocol with the given identifier. If a protocol with
- * the given ID already exists it will be overridden. This ID is the same
- * one used to retrieve the protocol from getProtocol(String).
- *
- * @param id the identifier for this protocol
- * @param protocol the protocol to register
- *
- * @see #getProtocol(String)
- */
- public static void registerProtocol(String id, Protocol protocol) {
- if (id == null) {
- throw new IllegalArgumentException("id is null");
- }
- if (protocol == null) {
- throw new IllegalArgumentException("protocol is null");
- }
- PROTOCOLS.put(id, protocol);
- }
- /**
- * Unregisters the protocol with the given ID.
- *
- * @param id the ID of the protocol to remove
- */
- public static void unregisterProtocol(String id) {
- if (id == null) {
- throw new IllegalArgumentException("id is null");
- }
- PROTOCOLS.remove(id);
- }
- /**
- * Gets the protocol with the given ID.
- *
- * @param id the protocol ID
- *
- * @return Protocol a protocol
- *
- * @throws IllegalStateException if a protocol with the ID cannot be found
- */
- public static Protocol getProtocol(String id)
- throws IllegalStateException {
- if (id == null) {
- throw new IllegalArgumentException("id is null");
- }
- Protocol protocol = (Protocol) PROTOCOLS.get(id);
- if (protocol == null) {
- protocol = lazyRegisterProtocol(id);
- }
- return protocol;
- }
- /**
- * Lazily registers the protocol with the given id.
- *
- * @param id the protocol ID
- *
- * @return the lazily registered protocol
- *
- * @throws IllegalStateException if the protocol with id is not recognized
- */
- private static Protocol lazyRegisterProtocol(String id)
- throws IllegalStateException {
- if ("http".equals(id)) {
- final Protocol http
- = new Protocol("http", DefaultProtocolSocketFactory.getSocketFactory(), 80);
- Protocol.registerProtocol("http", http);
- return http;
- }
- if ("https".equals(id)) {
- final Protocol https
- = new Protocol("https", SSLProtocolSocketFactory.getSocketFactory(), 443);
- Protocol.registerProtocol("https", https);
- return https;
- }
- throw new IllegalStateException("unsupported protocol: '" + id + "'");
- }
- /** the scheme of this protocol (e.g. http, https) */
- private String scheme;
- /** The socket factory for this protocol */
- private ProtocolSocketFactory socketFactory;
- /** The default port for this protocol */
- private int defaultPort;
- /** True if this protocol is secure */
- private boolean secure;
- /**
- * Constructs a new Protocol. Whether the created protocol is secure depends on
- * the class of
factory
.
- *
- * @param scheme the scheme (e.g. http, https)
- * @param factory the factory for creating sockets for communication using
- * this protocol
- * @param defaultPort the port this protocol defaults to
- */
- public Protocol(String scheme, ProtocolSocketFactory factory, int defaultPort) {
- if (scheme == null) {
- throw new IllegalArgumentException("scheme is null");
- }
- if (factory == null) {
- throw new IllegalArgumentException("socketFactory is null");
- }
- if (defaultPort <= 0) {
- throw new IllegalArgumentException("port is invalid: " + defaultPort);
- }
- this.scheme = scheme;
- this.socketFactory = factory;
- this.defaultPort = defaultPort;
- this.secure = (factory instanceof SecureProtocolSocketFactory);
- }
- /**
- * Constructs a new Protocol. Whether the created protocol is secure depends on
- * the class of
factory
.
- *
- * @param scheme the scheme (e.g. http, https)
- * @param factory the factory for creating sockets for communication using
- * this protocol
- * @param defaultPort the port this protocol defaults to
- * @deprecated Use the constructor that uses ProtocolSocketFactory, this version of
- * the constructor is only kept for backwards API compatibility.
- */
- public Protocol(String scheme,
- SecureProtocolSocketFactory factory, int defaultPort) {
- this(scheme, (ProtocolSocketFactory) factory, defaultPort);
- }
- /**
- * Returns the defaultPort.
- * @return int
- */
- public int getDefaultPort() {
- return defaultPort;
- }
- /**
- * Returns the socketFactory. If secure the factory is a
- * SecureProtocolSocketFactory.
- * @return SocketFactory
- */
- public ProtocolSocketFactory getSocketFactory() {
- return socketFactory;
- }
- /**
- * Returns the scheme.
- * @return The scheme
- */
- public String getScheme() {
- return scheme;
- }
- /**
- * Returns true if this protocol is secure
- * @return true if this protocol is secure
- */
- public boolean isSecure() {
- return secure;
- }
- /**
- * Resolves the correct port for this protocol. Returns the given port if
- * valid or the default port otherwise.
- *
- * @param port the port to be resolved
- *
- * @return the given port or the defaultPort
- */
- public int resolvePort(int port) {
- return port <= 0 ? getDefaultPort() : port;
- }
- /**
- * Return a string representation of this object.
- * @return a string representation of this object.
- */
- public String toString() {
- return scheme + ":" + defaultPort;
- }
- /**
- * Return true if the specified object equals this object.
- * @param obj The object to compare against.
- * @return true if the objects are equal.
- */
- public boolean equals(Object obj) {
- if (obj instanceof Protocol) {
- Protocol p = (Protocol) obj;
- return (
- defaultPort == p.getDefaultPort()
- && scheme.equalsIgnoreCase(p.getScheme())
- && secure == p.isSecure()
- && socketFactory.equals(p.getSocketFactory()));
- } else {
- return false;
- }
- }
- /**
- * Return a hash code for this object
- * @return The hash code.
- */
- public int hashCode() {
- int hash = LangUtils.HASH_SEED;
- hash = LangUtils.hashCode(hash, this.defaultPort);
- hash = LangUtils.hashCode(hash, this.scheme.toLowerCase());
- hash = LangUtils.hashCode(hash, this.secure);
- hash = LangUtils.hashCode(hash, this.socketFactory);
- return hash;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java b/clients/java/src/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java
deleted file mode 100644
index 544259d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java
+++ /dev/null
@@ -1,124 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.params.HttpConnectionParams;
- * A factory for creating Sockets.
- *
Both {@link java.lang.Object#equals(java.lang.Object) Object.equals()} and
- * {@link java.lang.Object#hashCode() Object.hashCode()} should be overridden appropriately.
- * Protocol socket factories are used to uniquely identify
Protocol
s and
- *
HostConfiguration
s, and
equals()
and
hashCode()
are
- * required for the correct operation of some connection managers.
- * @see Protocol
- * @author Michael Becke
- * @author
Mike Bowler
- * @since 2.0
-public interface ProtocolSocketFactory {
- /**
- * Gets a new socket connection to the given host.
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- */
- Socket createSocket(
- String host,
- int port,
- InetAddress localAddress,
- int localPort
- ) throws IOException, UnknownHostException;
- /**
- * Gets a new socket connection to the given host.
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param params {@link HttpConnectionParams Http connection parameters}
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- * @throws ConnectTimeoutException if socket cannot be connected within the
- * given time limit
- *
- * @since 3.0
- */
- Socket createSocket(
- String host,
- int port,
- InetAddress localAddress,
- int localPort,
- HttpConnectionParams params
- ) throws IOException, UnknownHostException, ConnectTimeoutException;
- /**
- * Gets a new socket connection to the given host.
- *
- * @param host the host name/IP
- * @param port the port on the host
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- */
- Socket createSocket(
- String host,
- int port
- ) throws IOException, UnknownHostException;
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java b/clients/java/src/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java
deleted file mode 100644
index f6e5171..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java
+++ /dev/null
@@ -1,169 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/ReflectionSocketFactory.java,v 1.4 2004/12/21 23:15:21 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import org.apache.commons.httpclient.ConnectTimeoutException;
- * This helper class uses refelction in order to execute Socket methods
- * available in Java 1.4 and above
- * @author Oleg Kalnichevski
- * @since 3.0
-public final class ReflectionSocketFactory {
- private static boolean REFLECTION_FAILED = false;
- private static Constructor INETSOCKETADDRESS_CONSTRUCTOR = null;
- private static Method SOCKETCONNECT_METHOD = null;
- private static Method SOCKETBIND_METHOD = null;
- private static Class SOCKETTIMEOUTEXCEPTION_CLASS = null;
- private ReflectionSocketFactory() {
- super();
- }
- /**
- * This method attempts to execute Socket method available since Java 1.4
- * using reflection. If the methods are not available or could not be executed
- *
null
is returned
- *
- * @param socketfactoryName name of the socket factory class
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param timeout the timeout value to be used in milliseconds. If the socket cannot be
- * completed within the given time limit, it will be abandoned
- *
- * @return a connected Socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- * @throws ConnectTimeoutException if socket cannot be connected within the
- * given time limit
- *
- */
- public static Socket createSocket(
- final String socketfactoryName,
- final String host,
- final int port,
- final InetAddress localAddress,
- final int localPort,
- int timeout)
- throws IOException, UnknownHostException, ConnectTimeoutException
- {
- if (REFLECTION_FAILED) {
- //This is known to have failed before. Do not try it again
- return null;
- }
- // This code uses reflection to essentially do the following:
- //
- // SocketFactory socketFactory = Class.forName(socketfactoryName).getDefault();
- // Socket socket = socketFactory.createSocket();
- // SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
- // SocketAddress remoteaddr = new InetSocketAddress(host, port);
- // socket.bind(localaddr);
- // socket.connect(remoteaddr, timeout);
- // return socket;
- try {
- Class socketfactoryClass = Class.forName(socketfactoryName);
- Method method = socketfactoryClass.getMethod("getDefault",
- new Class[] {});
- Object socketfactory = method.invoke(null,
- new Object[] {});
- method = socketfactoryClass.getMethod("createSocket",
- new Class[] {});
- Socket socket = (Socket) method.invoke(socketfactory, new Object[] {});
- if (INETSOCKETADDRESS_CONSTRUCTOR == null) {
- Class addressClass = Class.forName("java.net.InetSocketAddress");
- INETSOCKETADDRESS_CONSTRUCTOR = addressClass.getConstructor(
- new Class[] { InetAddress.class, Integer.TYPE });
- }
- Object remoteaddr = INETSOCKETADDRESS_CONSTRUCTOR.newInstance(
- new Object[] { InetAddress.getByName(host), new Integer(port)});
- Object localaddr = INETSOCKETADDRESS_CONSTRUCTOR.newInstance(
- new Object[] { localAddress, new Integer(localPort)});
- if (SOCKETCONNECT_METHOD == null) {
- SOCKETCONNECT_METHOD = Socket.class.getMethod("connect",
- new Class[] {Class.forName("java.net.SocketAddress"), Integer.TYPE});
- }
- if (SOCKETBIND_METHOD == null) {
- SOCKETBIND_METHOD = Socket.class.getMethod("bind",
- new Class[] {Class.forName("java.net.SocketAddress")});
- }
- SOCKETBIND_METHOD.invoke(socket, new Object[] { localaddr});
- SOCKETCONNECT_METHOD.invoke(socket, new Object[] { remoteaddr, new Integer(timeout)});
- return socket;
- }
- catch (InvocationTargetException e) {
- Throwable cause = e.getTargetException();
- if (SOCKETTIMEOUTEXCEPTION_CLASS == null) {
- try {
- SOCKETTIMEOUTEXCEPTION_CLASS = Class.forName("java.net.SocketTimeoutException");
- } catch (ClassNotFoundException ex) {
- // At this point this should never happen. Really.
- REFLECTION_FAILED = true;
- return null;
- }
- }
- if (SOCKETTIMEOUTEXCEPTION_CLASS.isInstance(cause)) {
- throw new ConnectTimeoutException(
- "The host did not accept the connection within timeout of "
- + timeout + " ms", cause);
- }
- if (cause instanceof IOException) {
- throw (IOException)cause;
- }
- return null;
- }
- catch (Exception e) {
- REFLECTION_FAILED = true;
- return null;
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java b/clients/java/src/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java
deleted file mode 100644
index f176fed..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java
+++ /dev/null
@@ -1,182 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java,v 1.10 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import javax.net.ssl.SSLSocketFactory;
-import org.apache.commons.httpclient.ConnectTimeoutException;
-import org.apache.commons.httpclient.params.HttpConnectionParams;
- * A SecureProtocolSocketFactory that uses JSSE to create sockets.
- * @author Michael Becke
- * @author
Mike Bowler
- * @since 2.0
-public class SSLProtocolSocketFactory implements SecureProtocolSocketFactory {
- /**
- * The factory singleton.
- */
- private static final SSLProtocolSocketFactory factory = new SSLProtocolSocketFactory();
- /**
- * Gets an singleton instance of the SSLProtocolSocketFactory.
- * @return a SSLProtocolSocketFactory
- */
- static SSLProtocolSocketFactory getSocketFactory() {
- return factory;
- }
- /**
- * Constructor for SSLProtocolSocketFactory.
- */
- public SSLProtocolSocketFactory() {
- super();
- }
- /**
- * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
- */
- public Socket createSocket(
- String host,
- int port,
- InetAddress clientHost,
- int clientPort)
- throws IOException, UnknownHostException {
- return SSLSocketFactory.getDefault().createSocket(
- host,
- port,
- clientHost,
- clientPort
- );
- }
- /**
- * Attempts to get a new socket connection to the given host within the given time limit.
- *
- * This method employs several techniques to circumvent the limitations of older JREs that
- * do not support connect timeout. When running in JRE 1.4 or above reflection is used to
- * call Socket#connect(SocketAddress endpoint, int timeout) method. When executing in older
- * JREs a controller thread is executed. The controller thread attempts to create a new socket
- * within the given limit of time. If socket constructor does not return until the timeout
- * expires, the controller terminates and throws an {@link ConnectTimeoutException}
- *
- *
- * @param host the host name/IP
- * @param port the port on the host
- * @param localAddress the local host name/IP to bind the socket to
- * @param localPort the port on the local machine
- * @param params {@link HttpConnectionParams Http connection parameters}
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- *
- * @since 3.0
- */
- public Socket createSocket(
- final String host,
- final int port,
- final InetAddress localAddress,
- final int localPort,
- final HttpConnectionParams params
- ) throws IOException, UnknownHostException, ConnectTimeoutException {
- if (params == null) {
- throw new IllegalArgumentException("Parameters may not be null");
- }
- int timeout = params.getConnectionTimeout();
- if (timeout == 0) {
- return createSocket(host, port, localAddress, localPort);
- } else {
- // To be eventually deprecated when migrated to Java 1.4 or above
- Socket socket = ReflectionSocketFactory.createSocket(
- "javax.net.ssl.SSLSocketFactory", host, port, localAddress, localPort, timeout);
- if (socket == null) {
- socket = ControllerThreadSocketFactory.createSocket(
- this, host, port, localAddress, localPort, timeout);
- }
- return socket;
- }
- }
- /**
- * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
- */
- public Socket createSocket(String host, int port)
- throws IOException, UnknownHostException {
- return SSLSocketFactory.getDefault().createSocket(
- host,
- port
- );
- }
- /**
- * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
- */
- public Socket createSocket(
- Socket socket,
- String host,
- int port,
- boolean autoClose)
- throws IOException, UnknownHostException {
- return ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(
- socket,
- host,
- port,
- autoClose
- );
- }
- /**
- * All instances of SSLProtocolSocketFactory are the same.
- */
- public boolean equals(Object obj) {
- return ((obj != null) && obj.getClass().equals(getClass()));
- }
- /**
- * All instances of SSLProtocolSocketFactory have the same hash code.
- */
- public int hashCode() {
- return getClass().hashCode();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.java b/clients/java/src/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.java
deleted file mode 100644
index f5fa9fb..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.java
+++ /dev/null
@@ -1,72 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/protocol/SecureProtocolSocketFactory.java,v 1.6 2004/04/18 23:51:38 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.protocol;
-import java.io.IOException;
-import java.net.Socket;
-import java.net.UnknownHostException;
- * A ProtocolSocketFactory that is secure.
- * @see org.apache.commons.httpclient.protocol.ProtocolSocketFactory
- * @author Michael Becke
- * @author
Mike Bowler
- * @since 2.0
-public interface SecureProtocolSocketFactory extends ProtocolSocketFactory {
- /**
- * Returns a socket connected to the given host that is layered over an
- * existing socket. Used primarily for creating secure sockets through
- * proxies.
- *
- * @param socket the existing socket
- * @param host the host name/IP
- * @param port the port on the host
- * @param autoClose a flag for closing the underling socket when the created
- * socket is closed
- *
- * @return Socket a new socket
- *
- * @throws IOException if an I/O error occurs while creating the socket
- * @throws UnknownHostException if the IP address of the host cannot be
- * determined
- */
- Socket createSocket(
- Socket socket,
- String host,
- int port,
- boolean autoClose
- ) throws IOException, UnknownHostException;
diff --git a/clients/java/src/org/apache/commons/httpclient/protocol/package.html b/clients/java/src/org/apache/commons/httpclient/protocol/package.html
deleted file mode 100644
index dd4b864..0000000
--- a/clients/java/src/org/apache/commons/httpclient/protocol/package.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
Package Documentation for org.apache.commons.httpclient.protocol
- Provides protocol specific socket factory handling.
- @since 2.0
diff --git a/clients/java/src/org/apache/commons/httpclient/util/DateParseException.java b/clients/java/src/org/apache/commons/httpclient/util/DateParseException.java
deleted file mode 100644
index ecabd83..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/DateParseException.java
+++ /dev/null
@@ -1,57 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateParseException.java,v 1.5 2004/11/06 19:15:42 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
- * An exception to indicate an error parsing a date string.
- * @see DateUtil
- * @author Michael Becke
-public class DateParseException extends Exception {
- /**
- *
- */
- public DateParseException() {
- super();
- }
- /**
- * @param message the exception message
- */
- public DateParseException(String message) {
- super(message);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/DateParser.java b/clients/java/src/org/apache/commons/httpclient/util/DateParser.java
deleted file mode 100644
index 622e36d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/DateParser.java
+++ /dev/null
@@ -1,142 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateParser.java,v 1.11 2004/11/06 19:15:42 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.TimeZone;
- * A utility class for parsing HTTP dates as used in cookies and other headers.
- * This class handles dates as defined by RFC 2616 section 3.3.1 as well as
- * some other common non-standard formats.
- * @author Christopher Brown
- * @author Michael Becke
- * @deprecated Use {@link org.apache.commons.httpclient.util.DateUtil}
-public class DateParser {
- /**
- * Date format pattern used to parse HTTP date headers in RFC 1123 format.
- */
- public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
- /**
- * Date format pattern used to parse HTTP date headers in RFC 1036 format.
- */
- public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
- /**
- * Date format pattern used to parse HTTP date headers in ANSI C
- *
asctime()
format.
- */
- public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
- private static final Collection DEFAULT_PATTERNS = Arrays.asList(
- new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } );
- /**
- * Parses a date value. The formats used for parsing the date value are retrieved from
- * the default http params.
- *
- * @param dateValue the date value to parse
- *
- * @return the parsed date
- *
- * @throws DateParseException if the value could not be parsed using any of the
- * supported date formats
- */
- public static Date parseDate(String dateValue) throws DateParseException {
- return parseDate(dateValue, null);
- }
- /**
- * Parses the date value using the given date formats.
- *
- * @param dateValue the date value to parse
- * @param dateFormats the date formats to use
- *
- * @return the parsed date
- *
- * @throws DateParseException if none of the dataFormats could parse the dateValue
- */
- public static Date parseDate(
- String dateValue,
- Collection dateFormats
- ) throws DateParseException {
- if (dateValue == null) {
- throw new IllegalArgumentException("dateValue is null");
- }
- if (dateFormats == null) {
- dateFormats = DEFAULT_PATTERNS;
- }
- // trim single quotes around date if present
- // see issue #5279
- if (dateValue.length() > 1
- && dateValue.startsWith("'")
- && dateValue.endsWith("'")
- ) {
- dateValue = dateValue.substring (1, dateValue.length() - 1);
- }
- SimpleDateFormat dateParser = null;
- Iterator formatIter = dateFormats.iterator();
- while (formatIter.hasNext()) {
- String format = (String) formatIter.next();
- if (dateParser == null) {
- dateParser = new SimpleDateFormat(format, Locale.US);
- dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
- } else {
- dateParser.applyPattern(format);
- }
- try {
- return dateParser.parse(dateValue);
- } catch (ParseException pe) {
- // ignore this exception, we will try the next format
- }
- }
- // we were unable to parse the date
- throw new DateParseException("Unable to parse the date " + dateValue);
- }
- /** This class should not be instantiated. */
- private DateParser() { }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/DateUtil.java b/clients/java/src/org/apache/commons/httpclient/util/DateUtil.java
deleted file mode 100644
index f4436cf..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/DateUtil.java
+++ /dev/null
@@ -1,210 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/DateUtil.java,v 1.2 2004/12/24 20:36:13 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.TimeZone;
- * A utility class for parsing and formatting HTTP dates as used in cookies and
- * other headers. This class handles dates as defined by RFC 2616 section
- * 3.3.1 as well as some other common non-standard formats.
- * @author Christopher Brown
- * @author Michael Becke
-public class DateUtil {
- /**
- * Date format pattern used to parse HTTP date headers in RFC 1123 format.
- */
- public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
- /**
- * Date format pattern used to parse HTTP date headers in RFC 1036 format.
- */
- public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
- /**
- * Date format pattern used to parse HTTP date headers in ANSI C
- *
asctime()
format.
- */
- public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
- private static final Collection DEFAULT_PATTERNS = Arrays.asList(
- new String[] { PATTERN_ASCTIME, PATTERN_RFC1036, PATTERN_RFC1123 } );
- private static final Date DEFAULT_TWO_DIGIT_YEAR_START;
- static {
- Calendar calendar = Calendar.getInstance();
- calendar.set(2000, Calendar.JANUARY, 1, 0, 0);
- DEFAULT_TWO_DIGIT_YEAR_START = calendar.getTime();
- }
- private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
- /**
- * Parses a date value. The formats used for parsing the date value are retrieved from
- * the default http params.
- *
- * @param dateValue the date value to parse
- *
- * @return the parsed date
- *
- * @throws DateParseException if the value could not be parsed using any of the
- * supported date formats
- */
- public static Date parseDate(String dateValue) throws DateParseException {
- return parseDate(dateValue, null, null);
- }
- /**
- * Parses the date value using the given date formats.
- *
- * @param dateValue the date value to parse
- * @param dateFormats the date formats to use
- *
- * @return the parsed date
- *
- * @throws DateParseException if none of the dataFormats could parse the dateValue
- */
- public static Date parseDate(String dateValue, Collection dateFormats)
- throws DateParseException {
- return parseDate(dateValue, dateFormats, null);
- }
- /**
- * Parses the date value using the given date formats.
- *
- * @param dateValue the date value to parse
- * @param dateFormats the date formats to use
- * @param startDate During parsing, two digit years will be placed in the range
- *
startDate
to
startDate + 100 years
. This value may
- * be
null
. When
null
is given as a parameter, year
- *
2000
will be used.
- *
- * @return the parsed date
- *
- * @throws DateParseException if none of the dataFormats could parse the dateValue
- */
- public static Date parseDate(
- String dateValue,
- Collection dateFormats,
- Date startDate
- ) throws DateParseException {
- if (dateValue == null) {
- throw new IllegalArgumentException("dateValue is null");
- }
- if (dateFormats == null) {
- dateFormats = DEFAULT_PATTERNS;
- }
- if (startDate == null) {
- startDate = DEFAULT_TWO_DIGIT_YEAR_START;
- }
- // trim single quotes around date if present
- // see issue #5279
- if (dateValue.length() > 1
- && dateValue.startsWith("'")
- && dateValue.endsWith("'")
- ) {
- dateValue = dateValue.substring (1, dateValue.length() - 1);
- }
- SimpleDateFormat dateParser = null;
- Iterator formatIter = dateFormats.iterator();
- while (formatIter.hasNext()) {
- String format = (String) formatIter.next();
- if (dateParser == null) {
- dateParser = new SimpleDateFormat(format, Locale.US);
- dateParser.setTimeZone(TimeZone.getTimeZone("GMT"));
- dateParser.set2DigitYearStart(startDate);
- } else {
- dateParser.applyPattern(format);
- }
- try {
- return dateParser.parse(dateValue);
- } catch (ParseException pe) {
- // ignore this exception, we will try the next format
- }
- }
- // we were unable to parse the date
- throw new DateParseException("Unable to parse the date " + dateValue);
- }
- /**
- * Formats the given date according to the RFC 1123 pattern.
- *
- * @param date The date to format.
- * @return An RFC 1123 formatted date string.
- *
- * @see #PATTERN_RFC1123
- */
- public static String formatDate(Date date) {
- return formatDate(date, PATTERN_RFC1123);
- }
- /**
- * Formats the given date according to the specified pattern. The pattern
- * must conform to that used by the {@link SimpleDateFormat simple date
- * format} class.
- *
- * @param date The date to format.
- * @param pattern The pattern to use for formatting the date.
- * @return A formatted date string.
- *
- * @throws IllegalArgumentException If the given date pattern is invalid.
- *
- * @see SimpleDateFormat
- */
- public static String formatDate(Date date, String pattern) {
- if (date == null) throw new IllegalArgumentException("date is null");
- if (pattern == null) throw new IllegalArgumentException("pattern is null");
- SimpleDateFormat formatter = new SimpleDateFormat(pattern, Locale.US);
- formatter.setTimeZone(GMT);
- return formatter.format(date);
- }
- /** This class should not be instantiated. */
- private DateUtil() { }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/EncodingUtil.java b/clients/java/src/org/apache/commons/httpclient/util/EncodingUtil.java
deleted file mode 100644
index 31ae349..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/EncodingUtil.java
+++ /dev/null
@@ -1,288 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/EncodingUtil.java,v 1.8 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.io.UnsupportedEncodingException;
-import org.apache.commons.codec.net.URLCodec;
-import org.apache.commons.httpclient.HttpClientError;
-import org.apache.commons.httpclient.NameValuePair;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
- * The home for utility methods that handle various encoding tasks.
- * @author Michael Becke
- * @author
Oleg Kalnichevski
- * @since 2.0 final
-public class EncodingUtil {
- /** Default content encoding chatset */
- private static final String DEFAULT_CHARSET = "ISO-8859-1";
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(EncodingUtil.class);
- /**
- * Form-urlencoding routine.
- *
- * The default encoding for all forms is `application/x-www-form-urlencoded'.
- * A form data set is represented in this media type as follows:
- *
- * The form field names and values are escaped: space characters are replaced
- * by `+', and then reserved characters are escaped as per [URL]; that is,
- * non-alphanumeric characters are replaced by `%HH', a percent sign and two
- * hexadecimal digits representing the ASCII code of the character. Line breaks,
- * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
- *
- *
- * if the given charset is not supported, ISO-8859-1 is used instead.
- *
- *
- * @param pairs the values to be encoded
- * @param charset the character set of pairs to be encoded
- *
- * @return the urlencoded pairs
- *
- * @since 2.0 final
- */
- public static String formUrlEncode(NameValuePair[] pairs, String charset) {
- try {
- return doFormUrlEncode(pairs, charset);
- } catch (UnsupportedEncodingException e) {
- LOG.error("Encoding not supported: " + charset);
- try {
- return doFormUrlEncode(pairs, DEFAULT_CHARSET);
- } catch (UnsupportedEncodingException fatal) {
- // Should never happen. ISO-8859-1 must be supported on all JVMs
- throw new HttpClientError("Encoding not supported: " +
- DEFAULT_CHARSET);
- }
- }
- }
- /**
- * Form-urlencoding routine.
- *
- * The default encoding for all forms is `application/x-www-form-urlencoded'.
- * A form data set is represented in this media type as follows:
- *
- * The form field names and values are escaped: space characters are replaced
- * by `+', and then reserved characters are escaped as per [URL]; that is,
- * non-alphanumeric characters are replaced by `%HH', a percent sign and two
- * hexadecimal digits representing the ASCII code of the character. Line breaks,
- * as in multi-line text field values, are represented as CR LF pairs, i.e. `%0D%0A'.
- *
- * @param pairs the values to be encoded
- * @param charset the character set of pairs to be encoded
- *
- * @return the urlencoded pairs
- * @throws UnsupportedEncodingException if charset is not supported
- *
- * @since 2.0 final
- */
- private static String doFormUrlEncode(NameValuePair[] pairs, String charset)
- throws UnsupportedEncodingException
- {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < pairs.length; i++) {
- URLCodec codec = new URLCodec();
- NameValuePair pair = pairs[i];
- if (pair.getName() != null) {
- if (i > 0) {
- buf.append("&");
- }
- buf.append(codec.encode(pair.getName(), charset));
- buf.append("=");
- if (pair.getValue() != null) {
- buf.append(codec.encode(pair.getValue(), charset));
- }
- }
- }
- return buf.toString();
- }
- /**
- * 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.
- *
- * @since 3.0
- */
- 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) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unsupported encoding: " + charset + ". System encoding used");
- }
- 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.
- *
- * @since 3.0
- */
- public static String getString(final byte[] data, String charset) {
- 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.
- *
- * @since 3.0
- */
- public static byte[] getBytes(final String data, 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) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Unsupported encoding: " + charset + ". System encoding used.");
- }
- 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.
- *
- * @since 3.0
- */
- public static byte[] getAsciiBytes(final String data) {
- if (data == null) {
- throw new IllegalArgumentException("Parameter may not be null");
- }
- try {
- return data.getBytes("US-ASCII");
- } catch (UnsupportedEncodingException e) {
- throw new HttpClientError("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
- *
- * @since 3.0
- */
- 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, "US-ASCII");
- } catch (UnsupportedEncodingException e) {
- throw new HttpClientError("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
- *
- * @since 3.0
- */
- public static String getAsciiString(final byte[] data) {
- return getAsciiString(data, 0, data.length);
- }
- /**
- * This class should not be instantiated.
- */
- private EncodingUtil() {
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/ExceptionUtil.java b/clients/java/src/org/apache/commons/httpclient/util/ExceptionUtil.java
deleted file mode 100644
index 72f4db8..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/ExceptionUtil.java
+++ /dev/null
@@ -1,122 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/ExceptionUtil.java,v 1.5 2004/10/19 18:09:46 olegk Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.io.InterruptedIOException;
-import java.lang.reflect.Method;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
- * The home for utility methods that handle various exception-related tasks.
- * @author
Oleg Kalnichevski
- * @author
Laura Werner
- * @since 3.0
-public class ExceptionUtil {
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(ExceptionUtil.class);
- /** 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();
- /** A reference to SocketTimeoutExceptionClass class, or null if it's not there in this JVM */
- static private final Class SOCKET_TIMEOUT_CLASS = SocketTimeoutExceptionClass();
- /**
- * Returns a
Method
allowing access to
- * {@link Throwable.initCause(Throwable) initCause} method of {@link Throwable},
- * or
null
if the method
- * does not exist.
- *
- * @return A
Method
for
Throwable.initCause
, or
- *
null
if unavailable.
- */
- static private Method getInitCauseMethod() {
- try {
- Class[] paramsClasses = new Class[] { Throwable.class };
- return Throwable.class.getMethod("initCause", paramsClasses);
- } catch (NoSuchMethodException e) {
- return null;
- }
- }
- /**
- * Returns
SocketTimeoutExceptionClass
or
null
if the class
- * does not exist.
- *
- * @return
SocketTimeoutExceptionClass
, or
null
if unavailable.
- */
- static private Class SocketTimeoutExceptionClass() {
- try {
- return Class.forName("java.net.SocketTimeoutException");
- } catch (ClassNotFoundException 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) {
- LOG.warn("Exception invoking Throwable.initCause", e);
- }
- }
- }
- /**
- * If SocketTimeoutExceptionClass is defined, returns
true
only if the
- * exception is an instance of SocketTimeoutExceptionClass. If
- * SocketTimeoutExceptionClass is undefined, always returns
true
.
- *
- * @param e an instance of InterruptedIOException class.
- *
- * @return
true
if the exception signals socket timeout,
false
- * otherwise.
- */
- public static boolean isSocketTimeoutException(final InterruptedIOException e) {
- if (SOCKET_TIMEOUT_CLASS != null) {
- return SOCKET_TIMEOUT_CLASS.isInstance(e);
- } else {
- return true;
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/HttpURLConnection.java b/clients/java/src/org/apache/commons/httpclient/util/HttpURLConnection.java
deleted file mode 100644
index 5d84b1e..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/HttpURLConnection.java
+++ /dev/null
@@ -1,504 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/HttpURLConnection.java,v 1.15 2004/04/18 23:51:38 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.Header;
-import org.apache.commons.logging.LogFactory;
-import org.apache.commons.logging.Log;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.net.ProtocolException;
-import java.security.Permission;
- * Provides a
HttpURLConnection
wrapper around HttpClient's
- *
HttpMethod
. This allows existing code to easily switch to
- * HttpClieht without breaking existing interfaces using the JDK
- *
HttpURLConnection
.
- * Note 1: The current implementations wraps only a connected
- *
HttpMethod
, ie a method that has alreayd been used to connect
- * to an HTTP server.
- * Note 2: It is a best try effort as different version of the JDK have
- * different behaviours for
HttpURLConnection
(And I'm not even
- * including the numerous
HttpURLConnection
bugs!).
- * @author
Vincent Massol
- * @author
Jeff Dever
- * @author
Mike Bowler
- * @since 2.0
- * @version $Id: HttpURLConnection.java 480424 2006-11-29 05:56:49Z bayard $
-public class HttpURLConnection extends java.net.HttpURLConnection {
- // -------------------------------------------------------- Class Variables
- /** Log object for this class. */
- private static final Log LOG = LogFactory.getLog(HttpURLConnection.class);
- // ----------------------------------------------------- Instance Variables
- /**
- * The
HttpMethod
object that was used to connect to the
- * HTTP server. It contains all the returned data.
- */
- private HttpMethod method;
- /**
- * The URL to which we are connected
- */
- private URL url;
- // ----------------------------------------------------------- Constructors
- /**
- * Creates an
HttpURLConnection
from a
HttpMethod
.
- *
- * @param method the theMethod that was used to connect to the HTTP
- * server and which contains the returned data.
- * @param url the URL to which we are connected (includes query string)
- */
- public HttpURLConnection(HttpMethod method, URL url) {
- super(url);
- this.method = method;
- this.url = url;
- }
- /**
- * Create an instance.
- * @param url The URL.
- * @see java.net.HttpURLConnection#HttpURLConnection(URL)
- */
- protected HttpURLConnection(URL url) {
- super(url);
- throw new RuntimeException("An HTTP URL connection can only be "
- + "constructed from a HttpMethod class");
- }
- // --------------------------------------------------------- Public Methods
- /**
- * Gets an input stream for the HttpMethod response body.
- * @throws IOException If an IO problem occurs.
- * @return The input stream.
- * @see java.net.HttpURLConnection#getInputStream()
- * @see org.apache.commons.httpclient.HttpMethod#getResponseBodyAsStream()
- */
- public InputStream getInputStream() throws IOException {
- LOG.trace("enter HttpURLConnection.getInputStream()");
- return this.method.getResponseBodyAsStream();
- }
- /**
- * Not yet implemented.
- * Return the error stream.
- * @see java.net.HttpURLConnection#getErrorStream()
- */
- public InputStream getErrorStream() {
- LOG.trace("enter HttpURLConnection.getErrorStream()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#disconnect()
- */
- public void disconnect() {
- LOG.trace("enter HttpURLConnection.disconnect()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @throws IOException If an IO problem occurs.
- * @see java.net.HttpURLConnection#connect()
- */
- public void connect() throws IOException {
- LOG.trace("enter HttpURLConnection.connect()");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @return true if we are using a proxy.
- * @see java.net.HttpURLConnection#usingProxy()
- */
- public boolean usingProxy() {
- LOG.trace("enter HttpURLConnection.usingProxy()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Return the request method.
- * @return The request method.
- * @see java.net.HttpURLConnection#getRequestMethod()
- * @see org.apache.commons.httpclient.HttpMethod#getName()
- */
- public String getRequestMethod() {
- LOG.trace("enter HttpURLConnection.getRequestMethod()");
- return this.method.getName();
- }
- /**
- * Return the response code.
- * @return The response code.
- * @throws IOException If an IO problem occurs.
- * @see java.net.HttpURLConnection#getResponseCode()
- * @see org.apache.commons.httpclient.HttpMethod#getStatusCode()
- */
- public int getResponseCode() throws IOException {
- LOG.trace("enter HttpURLConnection.getResponseCode()");
- return this.method.getStatusCode();
- }
- /**
- * Return the response message
- * @return The response message
- * @throws IOException If an IO problem occurs.
- * @see java.net.HttpURLConnection#getResponseMessage()
- * @see org.apache.commons.httpclient.HttpMethod#getStatusText()
- */
- public String getResponseMessage() throws IOException {
- LOG.trace("enter HttpURLConnection.getResponseMessage()");
- return this.method.getStatusText();
- }
- /**
- * Return the header field
- * @param name the name of the header
- * @return the header field.
- * @see java.net.HttpURLConnection#getHeaderField(String)
- * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()
- */
- public String getHeaderField(String name) {
- LOG.trace("enter HttpURLConnection.getHeaderField(String)");
- // Note: Return the last matching header in the Header[] array, as in
- // the JDK implementation.
- Header[] headers = this.method.getResponseHeaders();
- for (int i = headers.length - 1; i >= 0; i--) {
- if (headers[i].getName().equalsIgnoreCase(name)) {
- return headers[i].getValue();
- }
- }
- return null;
- }
- /**
- * Return the header field key
- * @param keyPosition The key position
- * @return The header field key.
- * @see java.net.HttpURLConnection#getHeaderFieldKey(int)
- * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()
- */
- public String getHeaderFieldKey(int keyPosition) {
- LOG.trace("enter HttpURLConnection.getHeaderFieldKey(int)");
- // Note: HttpClient does not consider the returned Status Line as
- // a response header. However, getHeaderFieldKey(0) is supposed to
- // return null. Hence the special case below ...
- if (keyPosition == 0) {
- return null;
- }
- // Note: HttpClient does not currently keep headers in the same order
- // that they are read from the HTTP server.
- Header[] headers = this.method.getResponseHeaders();
- if (keyPosition < 0 || keyPosition > headers.length) {
- return null;
- }
- return headers[keyPosition - 1].getName();
- }
- /**
- * Return the header field at the specified position
- * @param position The position
- * @return The header field.
- * @see java.net.HttpURLConnection#getHeaderField(int)
- * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders()
- */
- public String getHeaderField(int position) {
- LOG.trace("enter HttpURLConnection.getHeaderField(int)");
- // Note: HttpClient does not consider the returned Status Line as
- // a response header. However, getHeaderField(0) is supposed to
- // return the status line. Hence the special case below ...
- if (position == 0) {
- return this.method.getStatusLine().toString();
- }
- // Note: HttpClient does not currently keep headers in the same order
- // that they are read from the HTTP server.
- Header[] headers = this.method.getResponseHeaders();
- if (position < 0 || position > headers.length) {
- return null;
- }
- return headers[position - 1].getValue();
- }
- /**
- * Return the URL
- * @return The URL.
- * @see java.net.HttpURLConnection#getURL()
- */
- public URL getURL() {
- LOG.trace("enter HttpURLConnection.getURL()");
- return this.url;
- }
- // Note: We don't implement the following methods so that they default to
- // the JDK implementation. They will all call
- //
getHeaderField(String)
which we have overridden.
- // java.net.HttpURLConnection#getHeaderFieldDate(String, long)
- // java.net.HttpURLConnection#getContentLength()
- // java.net.HttpURLConnection#getContentType()
- // java.net.HttpURLConnection#getContentEncoding()
- // java.net.HttpURLConnection#getDate()
- // java.net.HttpURLConnection#getHeaderFieldInt(String, int)
- // java.net.HttpURLConnection#getExpiration()
- // java.net.HttpURLConnection#getLastModified()
- /**
- * Not available: the data must have already been retrieved.
- */
- public void setInstanceFollowRedirects(boolean isFollowingRedirects) {
- LOG.trace("enter HttpURLConnection.setInstanceFollowRedirects(boolean)");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- */
- public boolean getInstanceFollowRedirects() {
- LOG.trace("enter HttpURLConnection.getInstanceFollowRedirects()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setRequestMethod(String)
- */
- public void setRequestMethod(String method) throws ProtocolException {
- LOG.trace("enter HttpURLConnection.setRequestMethod(String)");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getPermission()
- */
- public Permission getPermission() throws IOException {
- LOG.trace("enter HttpURLConnection.getPermission()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getContent()
- */
- public Object getContent() throws IOException {
- LOG.trace("enter HttpURLConnection.getContent()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not yet implemented.
- */
- public Object getContent(Class[] classes) throws IOException {
- LOG.trace("enter HttpURLConnection.getContent(Class[])");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * @see java.net.HttpURLConnection#getOutputStream()
- */
- public OutputStream getOutputStream() throws IOException {
- LOG.trace("enter HttpURLConnection.getOutputStream()");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setDoInput(boolean)
- */
- public void setDoInput(boolean isInput) {
- LOG.trace("enter HttpURLConnection.setDoInput()");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getDoInput()
- */
- public boolean getDoInput() {
- LOG.trace("enter HttpURLConnection.getDoInput()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setDoOutput(boolean)
- */
- public void setDoOutput(boolean isOutput) {
- LOG.trace("enter HttpURLConnection.setDoOutput()");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getDoOutput()
- */
- public boolean getDoOutput() {
- LOG.trace("enter HttpURLConnection.getDoOutput()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setAllowUserInteraction(boolean)
- */
- public void setAllowUserInteraction(boolean isAllowInteraction) {
- LOG.trace("enter HttpURLConnection.setAllowUserInteraction(boolean)");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getAllowUserInteraction()
- */
- public boolean getAllowUserInteraction() {
- LOG.trace("enter HttpURLConnection.getAllowUserInteraction()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setUseCaches(boolean)
- */
- public void setUseCaches(boolean isUsingCaches) {
- LOG.trace("enter HttpURLConnection.setUseCaches(boolean)");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getUseCaches()
- */
- public boolean getUseCaches() {
- LOG.trace("enter HttpURLConnection.getUseCaches()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setIfModifiedSince(long)
- */
- public void setIfModifiedSince(long modificationDate) {
- LOG.trace("enter HttpURLConnection.setIfModifiedSince(long)");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getIfModifiedSince()
- */
- public long getIfModifiedSince() {
- LOG.trace("enter HttpURLConnection.getIfmodifiedSince()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#getDefaultUseCaches()
- */
- public boolean getDefaultUseCaches() {
- LOG.trace("enter HttpURLConnection.getDefaultUseCaches()");
- throw new RuntimeException("Not implemented yet");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setDefaultUseCaches(boolean)
- */
- public void setDefaultUseCaches(boolean isUsingCaches) {
- LOG.trace("enter HttpURLConnection.setDefaultUseCaches(boolean)");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not available: the data must have already been retrieved.
- * @see java.net.HttpURLConnection#setRequestProperty(String,String)
- */
- public void setRequestProperty(String key, String value) {
- LOG.trace("enter HttpURLConnection.setRequestProperty()");
- throw new RuntimeException("This class can only be used with already"
- + "retrieved data");
- }
- /**
- * Not yet implemented.
- * @see java.net.HttpURLConnection#getRequestProperty(String)
- */
- public String getRequestProperty(String key) {
- LOG.trace("enter HttpURLConnection.getRequestProperty()");
- throw new RuntimeException("Not implemented yet");
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/IdleConnectionHandler.java b/clients/java/src/org/apache/commons/httpclient/util/IdleConnectionHandler.java
deleted file mode 100644
index 7e3f8b4..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/IdleConnectionHandler.java
+++ /dev/null
@@ -1,125 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/IdleConnectionHandler.java,v 1.2 2004/05/13 02:40:36 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import org.apache.commons.httpclient.HttpConnection;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
- * A helper class for connection managers to track idle connections.
- *
This class is not synchronized.
- * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long)
- * @since 3.0
-public class IdleConnectionHandler {
- private static final Log LOG = LogFactory.getLog(IdleConnectionHandler.class);
- /** Holds connections and the time they were added. */
- private Map connectionToAdded = new HashMap();
- /**
- *
- */
- public IdleConnectionHandler() {
- super();
- }
- /**
- * Registers the given connection with this handler. The connection will be held until
- * {@link #remove(HttpConnection)} or {@link #closeIdleConnections(long)} is called.
- *
- * @param connection the connection to add
- *
- * @see #remove(HttpConnection)
- */
- public void add(HttpConnection connection) {
- Long timeAdded = new Long(System.currentTimeMillis());
- if (LOG.isDebugEnabled()) {
- LOG.debug("Adding connection at: " + timeAdded);
- }
- connectionToAdded.put(connection, timeAdded);
- }
- /**
- * Removes the given connection from the list of connections to be closed when idle.
- * @param connection
- */
- public void remove(HttpConnection connection) {
- connectionToAdded.remove(connection);
- }
- /**
- * Removes all connections referenced by this handler.
- */
- public void removeAll() {
- this.connectionToAdded.clear();
- }
- /**
- * Closes connections that have been idle for at least the given amount of time.
- *
- * @param idleTime the minimum idle time, in milliseconds, for connections to be closed
- */
- public void closeIdleConnections(long idleTime) {
- // the latest time for which connections will be closed
- long idleTimeout = System.currentTimeMillis() - idleTime;
- if (LOG.isDebugEnabled()) {
- LOG.debug("Checking for connections, idleTimeout: " + idleTimeout);
- }
- Iterator connectionIter = connectionToAdded.keySet().iterator();
- while (connectionIter.hasNext()) {
- HttpConnection conn = (HttpConnection) connectionIter.next();
- Long connectionTime = (Long) connectionToAdded.get(conn);
- if (connectionTime.longValue() <= idleTimeout) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Closing connection, connection time: " + connectionTime);
- }
- connectionIter.remove();
- conn.close();
- }
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java b/clients/java/src/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java
deleted file mode 100644
index 1790ab7..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java
+++ /dev/null
@@ -1,150 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/IdleConnectionTimeoutThread.java,v 1.2 2004/05/13 02:40:36 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import org.apache.commons.httpclient.HttpConnectionManager;
- * A utility class for periodically closing idle connections.
- * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long)
- * @since 3.0
-public class IdleConnectionTimeoutThread extends Thread {
- private List connectionManagers = new ArrayList();
- private boolean shutdown = false;
- private long timeoutInterval = 1000;
- private long connectionTimeout = 3000;
- public IdleConnectionTimeoutThread() {
- setDaemon(true);
- }
- /**
- * Adds a connection manager to be handled by this class.
- * {@link HttpConnectionManager#closeIdleConnections(long)} will be called on the connection
- * manager every {@link #setTimeoutInterval(long) timeoutInterval} milliseconds.
- *
- * @param connectionManager The connection manager to add
- */
- public synchronized void addConnectionManager(HttpConnectionManager connectionManager) {
- if (shutdown) {
- throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
- }
- this.connectionManagers.add(connectionManager);
- }
- /**
- * Removes the connection manager from this class. The idle connections from the connection
- * manager will no longer be automatically closed by this class.
- *
- * @param connectionManager The connection manager to remove
- */
- public synchronized void removeConnectionManager(HttpConnectionManager connectionManager) {
- if (shutdown) {
- throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
- }
- this.connectionManagers.remove(connectionManager);
- }
- /**
- * Handles calling {@link HttpConnectionManager#closeIdleConnections(long) closeIdleConnections()}
- * and doing any other cleanup work on the given connection mangaer.
- * @param connectionManager The connection manager to close idle connections for
- */
- protected void handleCloseIdleConnections(HttpConnectionManager connectionManager) {
- connectionManager.closeIdleConnections(connectionTimeout);
- }
- /**
- * Closes idle connections.
- */
- public synchronized void run() {
- while (!shutdown) {
- Iterator iter = connectionManagers.iterator();
- while (iter.hasNext()) {
- HttpConnectionManager connectionManager = (HttpConnectionManager) iter.next();
- handleCloseIdleConnections(connectionManager);
- }
- try {
- this.wait(timeoutInterval);
- } catch (InterruptedException e) {
- }
- }
- // clear out the connection managers now that we're shutdown
- this.connectionManagers.clear();
- }
- /**
- * Stops the thread used to close idle connections. This class cannot be used once shutdown.
- */
- public synchronized void shutdown() {
- this.shutdown = true;
- this.notifyAll();
- }
- /**
- * Sets the timeout value to use when testing for idle connections.
- *
- * @param connectionTimeout The connection timeout in milliseconds
- *
- * @see HttpConnectionManager#closeIdleConnections(long)
- */
- public synchronized void setConnectionTimeout(long connectionTimeout) {
- if (shutdown) {
- throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
- }
- this.connectionTimeout = connectionTimeout;
- }
- /**
- * Sets the interval used by this class between closing idle connections. Idle
- * connections will be closed every
timeoutInterval
milliseconds.
- *
- * @param timeoutInterval The timeout interval in milliseconds
- */
- public synchronized void setTimeoutInterval(long timeoutInterval) {
- if (shutdown) {
- throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown");
- }
- this.timeoutInterval = timeoutInterval;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/LangUtils.java b/clients/java/src/org/apache/commons/httpclient/util/LangUtils.java
deleted file mode 100644
index 543be4d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/LangUtils.java
+++ /dev/null
@@ -1,66 +0,0 @@
- * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/util/LangUtils.java $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
- * A set of utility methods to help produce consistent Object#equals(Object) and
- * Object#hashCode methods.
- * @author
Oleg Kalnichevski
- * @since 3.0
-public class LangUtils {
- public static final int HASH_SEED = 17;
- public static final int HASH_OFFSET = 37;
- private LangUtils() {
- super();
- }
- public static int hashCode(final int seed, final int hashcode) {
- return seed * HASH_OFFSET + hashcode;
- }
- public static int hashCode(final int seed, final Object obj) {
- return hashCode(seed, obj != null ? obj.hashCode() : 0);
- }
- public static int hashCode(final int seed, final boolean b) {
- return hashCode(seed, b ? 1 : 0);
- }
- public static boolean equals(final Object obj1, final Object obj2) {
- return obj1 == null ? obj2 == null : obj1.equals(obj2);
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/ParameterFormatter.java b/clients/java/src/org/apache/commons/httpclient/util/ParameterFormatter.java
deleted file mode 100644
index 21bfa06..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/ParameterFormatter.java
+++ /dev/null
@@ -1,242 +0,0 @@
- * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/oac.hc3x/tags/HTTPCLIENT_3_1/src/java/org/apache/commons/httpclient/util/ParameterFormatter.java $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import org.apache.commons.httpclient.NameValuePair;
- * This formatter produces a textual representation of attribute/value pairs. It
- * comforms to the generic grammar and formatting rules outlined in the
- *
Section 2.1
- * and
- *
Section 3.6
- * of
RFC 2616
- *
2.1 Augmented BNF
- * Many HTTP/1.1 header field values consist of words separated by LWS or special
- * characters. These special characters MUST be in a quoted string to be used within
- * a parameter value (as defined in section 3.6).
- * token = 1*
- * separators = "(" | ")" | "" | "@"
- * | "," | ";" | ":" | "\" |
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- * A string of text is parsed as a single word if it is quoted using double-quote marks.
- * quoted-string = ( *(qdtext | quoted-pair ) )
- * qdtext =
>
- * The backslash character ("\") MAY be used as a single-character quoting mechanism only
- * within quoted-string and comment constructs.
- * quoted-pair = "\" CHAR
- *
3.6 Transfer Codings
- * Parameters are in the form of attribute/value pairs.
- * parameter = attribute "=" value
- * attribute = token
- * value = token | quoted-string
- * @author
Oleg Kalnichevski
- * @since 3.0
-public class ParameterFormatter {
- /**
- * 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
- */
- private static final char[] SEPARATORS = {
- '(', ')', '', '@',
- ',', ';', ':', '\\', '"',
- '/', '[', ']', '?', '=',
- '{', '}', ' ', '\t'
- };
- /**
- * Unsafe special characters that must be escaped using the backslash
- * character
- */
- private static final char[] UNSAFE_CHARS = {
- '"', '\\'
- };
- /**
- * This flag determines whether all parameter values must be enclosed in
- * quotation marks, even if they do not contain any special characters
- */
- private boolean alwaysUseQuotes = true;
- /** Default ParameterFormatter constructor */
- public ParameterFormatter() {
- super();
- }
- private static boolean isOneOf(char[] chars, char ch) {
- for (int i = 0; i < chars.length; i++) {
- if (ch == chars[i]) {
- return true;
- }
- }
- return false;
- }
- private static boolean isUnsafeChar(char ch) {
- return isOneOf(UNSAFE_CHARS, ch);
- }
- private static boolean isSeparator(char ch) {
- return isOneOf(SEPARATORS, ch);
- }
- /**
- * Determines whether all parameter values must be enclosed in quotation
- * marks, even if they do not contain any special characters
- *
- * @return
true
if all parameter values must be enclosed in
- * quotation marks,
false
otherwise
- */
- public boolean isAlwaysUseQuotes() {
- return alwaysUseQuotes;
- }
- /**
- * Defines whether all parameter values must be enclosed in quotation
- * marks, even if they do not contain any special characters
- *
- * @param alwaysUseQuotes
- */
- public void setAlwaysUseQuotes(boolean alwaysUseQuotes) {
- this.alwaysUseQuotes = alwaysUseQuotes;
- }
- /**
- * Formats the given parameter value using formatting rules defined
- * in RFC 2616
- *
- * @param buffer output buffer
- * @param value the parameter value to be formatted
- * @param alwaysUseQuotes
true
if the parameter value must
- * be enclosed in quotation marks, even if it does not contain any special
- * characters
, false
only if the parameter value contains
- * potentially unsafe special characters
- */
- public static void formatValue(
- final StringBuffer buffer, final String value, boolean alwaysUseQuotes) {
- if (buffer == null) {
- throw new IllegalArgumentException("String buffer may not be null");
- }
- if (value == null) {
- throw new IllegalArgumentException("Value buffer may not be null");
- }
- if (alwaysUseQuotes) {
- buffer.append('"');
- for (int i = 0; i < value.length(); i++) {
- char ch = value.charAt(i);
- if (isUnsafeChar(ch)) {
- buffer.append('\\');
- }
- buffer.append(ch);
- }
- buffer.append('"');
- } else {
- int offset = buffer.length();
- boolean unsafe = false;
- for (int i = 0; i < value.length(); i++) {
- char ch = value.charAt(i);
- if (isSeparator(ch)) {
- unsafe = true;
- }
- if (isUnsafeChar(ch)) {
- buffer.append('\\');
- }
- buffer.append(ch);
- }
- if (unsafe) {
- buffer.insert(offset, '"');
- buffer.append('"');
- }
- }
- }
- /**
- * Produces textual representaion of the attribute/value pair using
- * formatting rules defined in RFC 2616
- *
- * @param buffer output buffer
- * @param param the parameter to be formatted
- */
- public void format(final StringBuffer buffer, final NameValuePair param) {
- if (buffer == null) {
- throw new IllegalArgumentException("String buffer may not be null");
- }
- if (param == null) {
- throw new IllegalArgumentException("Parameter may not be null");
- }
- buffer.append(param.getName());
- String value = param.getValue();
- if (value != null) {
- buffer.append("=");
- formatValue(buffer, value, this.alwaysUseQuotes);
- }
- }
- /**
- * Produces textual representaion of the attribute/value pair using
- * formatting rules defined in RFC 2616
- *
- * @param param the parameter to be formatted
- *
- * @return RFC 2616 conformant textual representaion of the
- * attribute/value pair
- */
- public String format(final NameValuePair param) {
- StringBuffer buffer = new StringBuffer();
- format(buffer, param);
- return buffer.toString();
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/ParameterParser.java b/clients/java/src/org/apache/commons/httpclient/util/ParameterParser.java
deleted file mode 100644
index 1484029..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/ParameterParser.java
+++ /dev/null
@@ -1,235 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/ParameterParser.java,v 1.5 2004/05/13 04:01:22 mbecke Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.commons.httpclient.NameValuePair;
- * A simple parser intended to parse sequences of name/value pairs.
- * Parameter values are exptected to be enclosed in quotes if they
- * contain unsafe characters, such as '=' characters or separators.
- * Parameter values are optional and can be omitted.
- *
param1 = value; param2 = "anything goes; really"; param3
- * @author
Oleg Kalnichevski
- * @since 3.0
-public class ParameterParser {
- /** String to be parsed */
- private char[] chars = null;
- /** Current position in the string */
- private int pos = 0;
- /** Maximum position in the string */
- private int len = 0;
- /** Start of a token */
- private int i1 = 0;
- /** End of a token */
- private int i2 = 0;
- /** Default ParameterParser constructor */
- public ParameterParser() {
- super();
- }
- /** Are there any characters left to parse? */
- private boolean hasChar() {
- return this.pos < this.len;
- }
- /** A helper method to process the parsed token. */
- private String getToken(boolean quoted) {
- // Trim leading white spaces
- while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) {
- i1++;
- }
- // Trim trailing white spaces
- while ((i2 > i1) && (Character.isWhitespace(chars[i2 - 1]))) {
- i2--;
- }
- // Strip away quotes if necessary
- if (quoted) {
- if (((i2 - i1) >= 2)
- && (chars[i1] == '"')
- && (chars[i2 - 1] == '"')) {
- i1++;
- i2--;
- }
- }
- String result = null;
- if (i2 >= i1) {
- result = new String(chars, i1, i2 - i1);
- }
- return result;
- }
- /** Is given character present in the array of characters? */
- private boolean isOneOf(char ch, char[] charray) {
- boolean result = false;
- for (int i = 0; i < charray.length; i++) {
- if (ch == charray[i]) {
- result = true;
- break;
- }
- }
- return result;
- }
- /** Parse out a token until any of the given terminators
- * is encountered. */
- private String parseToken(final char[] terminators) {
- char ch;
- i1 = pos;
- i2 = pos;
- while (hasChar()) {
- ch = chars[pos];
- if (isOneOf(ch, terminators)) {
- break;
- }
- i2++;
- pos++;
- }
- return getToken(false);
- }
- /** Parse out a token until any of the given terminators
- * is encountered. Special characters in quoted tokens
- * are escaped. */
- private String parseQuotedToken(final char[] terminators) {
- char ch;
- i1 = pos;
- i2 = pos;
- boolean quoted = false;
- boolean charEscaped = false;
- while (hasChar()) {
- ch = chars[pos];
- if (!quoted && isOneOf(ch, terminators)) {
- break;
- }
- if (!charEscaped && ch == '"') {
- quoted = !quoted;
- }
- charEscaped = (!charEscaped && ch == '\\');
- i2++;
- pos++;
- }
- return getToken(true);
- }
- /**
- * Extracts a list of {@link NameValuePair}s from the given string.
- *
- * @param str the string that contains a sequence of name/value pairs
- * @return a list of {@link NameValuePair}s
- *
- */
- public List parse(final String str, char separator) {
- if (str == null) {
- return new ArrayList();
- }
- return parse(str.toCharArray(), separator);
- }
- /**
- * Extracts a list of {@link NameValuePair}s from the given array of
- * characters.
- *
- * @param chars the array of characters that contains a sequence of
- * name/value pairs
- *
- * @return a list of {@link NameValuePair}s
- */
- public List parse(final char[] chars, char separator) {
- if (chars == null) {
- return new ArrayList();
- }
- return parse(chars, 0, chars.length, separator);
- }
- /**
- * Extracts a list of {@link NameValuePair}s from the given array of
- * characters.
- *
- * @param chars the array of characters that contains a sequence of
- * name/value pairs
- * @param offset - the initial offset.
- * @param length - the length.
- *
- * @return a list of {@link NameValuePair}s
- */
- public List parse(final char[] chars, int offset, int length, char separator) {
- if (chars == null) {
- return new ArrayList();
- }
- List params = new ArrayList();
- this.chars = chars;
- this.pos = offset;
- this.len = length;
- String paramName = null;
- String paramValue = null;
- while (hasChar()) {
- paramName = parseToken(new char[] {'=', separator});
- paramValue = null;
- if (hasChar() && (chars[pos] == '=')) {
- pos++; // skip '='
- paramValue = parseQuotedToken(new char[] {separator});
- }
- if (hasChar() && (chars[pos] == separator)) {
- pos++; // skip separator
- }
- if (paramName != null && !(paramName.equals("") && paramValue == null)) {
- params.add(new NameValuePair(paramName, paramValue));
- }
- }
- return params;
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/TimeoutController.java b/clients/java/src/org/apache/commons/httpclient/util/TimeoutController.java
deleted file mode 100644
index 8fb6632..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/TimeoutController.java
+++ /dev/null
@@ -1,93 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/TimeoutController.java,v 1.6 2004/04/18 23:51:38 jsdever Exp $
- * $Revision: 480424 $
- * $Date: 2006-11-29 06:56:49 +0100 (Wed, 29 Nov 2006) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
- * Executes a task with a specified timeout.
- * @author Ortwin Glueck
- * @author
Mike Bowler
- * @version $Revision: 480424 $
- * @since 2.0
-public final class TimeoutController {
- /**
- * Do not instantiate objects of this class. Methods are static.
- */
- private TimeoutController() {
- }
- /**
- * Executes
task
. Waits for
timeout
- * milliseconds for the task to end and returns. If the task does not return
- * in time, the thread is interrupted and an Exception is thrown.
- * The caller should override the Thread.interrupt() method to something that
- * quickly makes the thread die or use Thread.isInterrupted().
- * @param task The thread to execute
- * @param timeout The timeout in milliseconds. 0 means to wait forever.
- * @throws TimeoutException if the timeout passes and the thread does not return.
- */
- public static void execute(Thread task, long timeout) throws TimeoutException {
- task.start();
- try {
- task.join(timeout);
- } catch (InterruptedException e) {
- /* if somebody interrupts us he knows what he is doing */
- }
- if (task.isAlive()) {
- task.interrupt();
- throw new TimeoutException();
- }
- }
- /**
- * Executes
task
in a new deamon Thread and waits for the timeout.
- * @param task The task to execute
- * @param timeout The timeout in milliseconds. 0 means to wait forever.
- * @throws TimeoutException if the timeout passes and the thread does not return.
- */
- public static void execute(Runnable task, long timeout) throws TimeoutException {
- Thread t = new Thread(task, "Timeout guard");
- t.setDaemon(true);
- execute(t, timeout);
- }
- /**
- * Signals that the task timed out.
- */
- public static class TimeoutException extends Exception {
- /** Create an instance */
- public TimeoutException() {
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/URIUtil.java b/clients/java/src/org/apache/commons/httpclient/util/URIUtil.java
deleted file mode 100644
index 4fb5a1d..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/URIUtil.java
+++ /dev/null
@@ -1,658 +0,0 @@
- * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/util/URIUtil.java,v 1.27 2004/05/05 20:34:01 olegk Exp $
- * $Revision: 507321 $
- * $Date: 2007-02-14 01:10:51 +0100 (Wed, 14 Feb 2007) $
- * ====================================================================
- * 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
- *
.
-package org.apache.commons.httpclient.util;
-import java.util.BitSet;
-import org.apache.commons.codec.DecoderException;
-import org.apache.commons.codec.net.URLCodec;
-import org.apache.commons.httpclient.URI;
-import org.apache.commons.httpclient.URIException;
- * The URI escape and character encoding and decoding utility.
- * It's compatible with {@link org.apache.commons.httpclient.HttpURL} rather
- * than {@link org.apache.commons.httpclient.URI}.
- * @author
Sung-Gu
- * @version $Revision: 507321 $ $Date: 2002/03/14 15:14:01
-public class URIUtil {
- // ----------------------------------------------------- Instance variables
- protected static final BitSet empty = new BitSet(1);
- // ---------------------------------------------------------- URI utilities
- /**
- * Get the basename of an URI. It's possibly an empty string.
- *
- * @param uri a string regarded an URI
- * @return the basename string; an empty string if the path ends with slash
- */
- public static String getName(String uri) {
- if (uri == null || uri.length() == 0) { return uri; }
- String path = URIUtil.getPath(uri);
- int at = path.lastIndexOf("/");
- int to = path.length();
- return (at >= 0) ? path.substring(at + 1, to) : path;
- }
- /**
- * Get the query of an URI.
- *
- * @param uri a string regarded an URI
- * @return the query string;
null
if empty or undefined
- */
- public static String getQuery(String uri) {
- if (uri == null || uri.length() == 0) { return null; }
- // consider of net_path
- int at = uri.indexOf("//");
- int from = uri.indexOf(
- "/",
- at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
- );
- // the authority part of URI ignored
- int to = uri.length();
- // reuse the at and from variables to consider the query
- at = uri.indexOf("?", from);
- if (at >= 0) {
- from = at + 1;
- } else {
- return null;
- }
- // check the fragment
- if (uri.lastIndexOf("#") > from) {
- to = uri.lastIndexOf("#");
- }
- // get the path and query.
- return (from < 0 || from == to) ? null : uri.substring(from, to);
- }
- /**
- * Get the path of an URI.
- *
- * @param uri a string regarded an URI
- * @return the path string
- */
- public static String getPath(String uri) {
- if (uri == null) {
- return null;
- }
- // consider of net_path
- int at = uri.indexOf("//");
- int from = uri.indexOf(
- "/",
- at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
- );
- // the authority part of URI ignored
- int to = uri.length();
- // check the query
- if (uri.indexOf('?', from) != -1) {
- to = uri.indexOf('?', from);
- }
- // check the fragment
- if (uri.lastIndexOf("#") > from && uri.lastIndexOf("#") < to) {
- to = uri.lastIndexOf("#");
- }
- // get only the path.
- return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from, to);
- }
- /**
- * Get the path and query of an URI.
- *
- * @param uri a string regarded an URI
- * @return the path and query string
- */
- public static String getPathQuery(String uri) {
- if (uri == null) {
- return null;
- }
- // consider of net_path
- int at = uri.indexOf("//");
- int from = uri.indexOf(
- "/",
- at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
- );
- // the authority part of URI ignored
- int to = uri.length();
- // Ignore the '?' mark so to ignore the query.
- // check the fragment
- if (uri.lastIndexOf("#") > from) {
- to = uri.lastIndexOf("#");
- }
- // get the path and query.
- return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from, to);
- }
- /**
- * Get the path of an URI and its rest part.
- *
- * @param uri a string regarded an URI
- * @return the string from the path part
- */
- public static String getFromPath(String uri) {
- if (uri == null) {
- return null;
- }
- // consider of net_path
- int at = uri.indexOf("//");
- int from = uri.indexOf(
- "/",
- at >= 0 ? (uri.lastIndexOf("/", at - 1) >= 0 ? 0 : at + 2) : 0
- );
- // get the path and its rest.
- return (from < 0) ? (at >= 0 ? "/" : uri) : uri.substring(from);
- }
- // ----------------------------------------------------- Encoding utilities
- /**
- * Get the all escaped and encoded string with the default protocl charset.
- * It's the same function to use
encode(String unescaped, Bitset
- * empty, URI.getDefaultProtocolCharset())
.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodeAll(String unescaped) throws URIException {
- return encodeAll(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Get the all escaped and encoded string with a given charset.
- * It's the same function to use
encode(String unescaped, Bitset
- * empty, String charset)
.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodeAll(String unescaped, String charset)
- throws URIException {
- return encode(unescaped, empty, charset);
- }
- /**
- * Escape and encode a string regarded as within the authority component of
- * an URI with the default protocol charset.
- * Within the authority component, the characters ";", ":", "@", "?", and
- * "/" are reserved.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodeWithinAuthority(String unescaped)
- throws URIException {
- return encodeWithinAuthority(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a string regarded as within the authority component of
- * an URI with a given charset.
- * Within the authority component, the characters ";", ":", "@", "?", and
- * "/" are reserved.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodeWithinAuthority(String unescaped, String charset)
- throws URIException {
- return encode(unescaped, URI.allowed_within_authority, charset);
- }
- /**
- * Escape and encode a string regarded as the path and query components of
- * an URI with the default protocol charset.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodePathQuery(String unescaped) throws URIException {
- return encodePathQuery(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a string regarded as the path and query components of
- * an URI with a given charset.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodePathQuery(String unescaped, String charset)
- throws URIException {
- int at = unescaped.indexOf('?');
- if (at < 0) {
- return encode(unescaped, URI.allowed_abs_path, charset);
- }
- // else
- return encode(unescaped.substring(0, at), URI.allowed_abs_path, charset)
- + '?' + encode(unescaped.substring(at + 1), URI.allowed_query, charset);
- }
- /**
- * Escape and encode a string regarded as within the path component of an
- * URI with the default protocol charset.
- * The path may consist of a sequence of path segments separated by a
- * single slash "/" character. Within a path segment, the characters
- * "/", ";", "=", and "?" are reserved.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodeWithinPath(String unescaped)
- throws URIException {
- return encodeWithinPath(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a string regarded as within the path component of an
- * URI with a given charset.
- * The path may consist of a sequence of path segments separated by a
- * single slash "/" character. Within a path segment, the characters
- * "/", ";", "=", and "?" are reserved.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodeWithinPath(String unescaped, String charset)
- throws URIException {
- return encode(unescaped, URI.allowed_within_path, charset);
- }
- /**
- * Escape and encode a string regarded as the path component of an URI with
- * the default protocol charset.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodePath(String unescaped) throws URIException {
- return encodePath(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a string regarded as the path component of an URI with
- * a given charset.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodePath(String unescaped, String charset)
- throws URIException {
- return encode(unescaped, URI.allowed_abs_path, charset);
- }
- /**
- * Escape and encode a string regarded as within the query component of an
- * URI with the default protocol charset.
- * When a query comprise the name and value pairs, it is used in order
- * to encode each name and value string. The reserved special characters
- * within a query component are being included in encoding the query.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodeWithinQuery(String unescaped)
- throws URIException {
- return encodeWithinQuery(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a string regarded as within the query component of an
- * URI with a given charset.
- * When a query comprise the name and value pairs, it is used in order
- * to encode each name and value string. The reserved special characters
- * within a query component are being included in encoding the query.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodeWithinQuery(String unescaped, String charset)
- throws URIException {
- return encode(unescaped, URI.allowed_within_query, charset);
- }
- /**
- * Escape and encode a string regarded as the query component of an URI with
- * the default protocol charset.
- * When a query string is not misunderstood the reserved special characters
- * ("&", "=", "+", ",", and "$") within a query component, this method
- * is recommended to use in encoding the whole query.
- *
- * @param unescaped an unescaped string
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- * @see #encode
- */
- public static String encodeQuery(String unescaped) throws URIException {
- return encodeQuery(unescaped, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a string regarded as the query component of an URI with
- * a given charset.
- * When a query string is not misunderstood the reserved special characters
- * ("&", "=", "+", ",", and "$") within a query component, this method
- * is recommended to use in encoding the whole query.
- *
- * @param unescaped an unescaped string
- * @param charset the charset
- * @return the escaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see #encode
- */
- public static String encodeQuery(String unescaped, String charset)
- throws URIException {
- return encode(unescaped, URI.allowed_query, charset);
- }
- /**
- * Escape and encode a given string with allowed characters not to be
- * escaped and the default protocol charset.
- *
- * @param unescaped a string
- * @param allowed allowed characters not to be escaped
- * @return the escaped string
- *
- * @throws URIException if the default protocol charset is not supported
- *
- * @see URI#getDefaultProtocolCharset
- */
- public static String encode(String unescaped, BitSet allowed)
- throws URIException {
- return encode(unescaped, allowed, URI.getDefaultProtocolCharset());
- }
- /**
- * Escape and encode a given string with allowed characters not to be
- * escaped and a given charset.
- *
- * @param unescaped a string
- * @param allowed allowed characters not to be escaped
- * @param charset the charset
- * @return the escaped string
- */
- public static String encode(String unescaped, BitSet allowed,
- String charset) throws URIException {
- byte[] rawdata = URLCodec.encodeUrl(allowed,
- EncodingUtil.getBytes(unescaped, charset));
- return EncodingUtil.getAsciiString(rawdata);
- }
- /**
- * Unescape and decode a given string regarded as an escaped string with the
- * default protocol charset.
- *
- * @param escaped a string
- * @return the unescaped string
- *
- * @throws URIException if the string cannot be decoded (invalid)
- *
- * @see URI#getDefaultProtocolCharset
- */
- public static String decode(String escaped) throws URIException {
- try {
- byte[] rawdata = URLCodec.decodeUrl(EncodingUtil.getAsciiBytes(escaped));
- return EncodingUtil.getString(rawdata, URI.getDefaultProtocolCharset());
- } catch (DecoderException e) {
- throw new URIException(e.getMessage());
- }
- }
- /**
- * Unescape and decode a given string regarded as an escaped string.
- *
- * @param escaped a string
- * @param charset the charset
- * @return the unescaped string
- *
- * @throws URIException if the charset is not supported
- *
- * @see Coder#decode
- */
- public static String decode(String escaped, String charset)
- throws URIException {
- return Coder.decode(escaped.toCharArray(), charset);
- }
- // ---------------------------------------------------------- Inner classes
- /**
- * The basic and internal utility for URI escape and character encoding and
- * decoding.
- *
- * @deprecated use org.apache.commons.codec.net.URLCodec
- */
- protected static class Coder extends URI {
- /**
- * Escape and encode a given string with allowed characters not to be
- * escaped.
- *
- * @param unescapedComponent an unescaped component
- * @param allowed allowed characters not to be escaped
- * @param charset the charset to encode
- * @return the escaped and encoded string
- *
- * @throws URIException if the charset is not supported
- *
- * @deprecated use org.apache.commons.codec.net.URLCodec
- */
- public static char[] encode(String unescapedComponent, BitSet allowed, String charset)
- throws URIException {
- return URI.encode(unescapedComponent, allowed, charset);
- }
- /**
- * Unescape and decode a given string.
- *
- * @param escapedComponent an being-unescaped component
- * @param charset the charset to decode
- * @return the escaped and encoded string
- *
- * @throws URIException if the charset is not supported
- *
- * @deprecated use org.apache.commons.codec.net.URLCodec
- */
- public static String decode(char[] escapedComponent, String charset)
- throws URIException {
- return URI.decode(escapedComponent, charset);
- }
- /**
- * Verify whether a given string is escaped or not
- *
- * @param original given characters
- * @return true if the given character array is 7 bit ASCII-compatible.
- */
- public static boolean verifyEscaped(char[] original) {
- for (int i = 0; i < original.length; i++) {
- int c = original[i];
- if (c > 128) {
- return false;
- } else if (c == '%') {
- if (Character.digit(original[++i], 16) == -1
- || Character.digit(original[++i], 16) == -1) {
- return false;
- }
- }
- }
- return true;
- }
- /**
- * Replace from a given character to given character in an array order
- * for a given string.
- *
- * @param original a given string
- * @param from a replacing character array
- * @param to a replaced character array
- * @return the replaced string
- */
- public static String replace(String original, char[] from, char[] to) {
- for (int i = from.length; i > 0; --i) {
- original = replace(original, from[i], to[i]);
- }
- return original;
- }
- /**
- * Replace from a given character to given character for a given string.
- *
- * @param original a given string
- * @param from a replacing character array
- * @param to a replaced character array
- * @return the replaced string
- */
- public static String replace(String original, char from, char to) {
- StringBuffer result = new StringBuffer(original.length());
- int at, saved = 0;
- do {
- at = original.indexOf(from);
- if (at >= 0) {
- result.append(original.substring(0, at));
- result.append(to);
- } else {
- result.append(original.substring(saved));
- }
- saved = at;
- } while (at >= 0);
- return result.toString();
- }
- }
diff --git a/clients/java/src/org/apache/commons/httpclient/util/package.html b/clients/java/src/org/apache/commons/httpclient/util/package.html
deleted file mode 100644
index a96b54f..0000000
--- a/clients/java/src/org/apache/commons/httpclient/util/package.html
+++ /dev/null
@@ -1,11 +0,0 @@
-
Package Documentation for org.apache.commons.httpclient.util
- Provides some utility classes for use by HttpClient.
- @since 2.0
diff --git a/clients/java/src/org/apache/commons/logging/Log.java b/clients/java/src/org/apache/commons/logging/Log.java
deleted file mode 100644
index bf80bad..0000000
--- a/clients/java/src/org/apache/commons/logging/Log.java
+++ /dev/null
@@ -1,246 +0,0 @@
- * 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.
-package org.apache.commons.logging;
- *
A simple logging interface abstracting logging APIs. In order to be
- * instantiated successfully by {@link LogFactory}, classes that implement
- * this interface must have a constructor that takes a single String
- * parameter representing the "name" of this Log.
- *
The six logging levels used by
Log
are (in order):
- *
-
trace (the least serious)
- *
-
debug
- *
-
info
- *
-
warn
- *
-
error
- *
-
fatal (the most serious)
- * The mapping of these log levels to the concepts used by the underlying
- * logging system is implementation dependent.
- * The implemention should ensure, though, that this ordering behaves
- * as expected.
- *
Performance is often a logging concern.
- * By examining the appropriate property,
- * a component can avoid expensive operations (producing information
- * to be logged).
- *
For example,
- * if (log.isDebugEnabled()) {
- * ... do something expensive ...
- * log.debug(theResult);
- * }
- *
Configuration of the underlying logging system will generally be done
- * external to the Logging APIs, through whatever mechanism is supported by
- * that system.
- * @author
Scott Sanders
- * @author Rod Waldhoff
- * @version $Id: Log.java 424107 2006-07-20 23:15:42Z skitching $
-public interface Log {
- // ----------------------------------------------------- Logging Properties
- /**
- *
Is debug logging currently enabled?
- *
- *
Call this method to prevent having to perform expensive operations
- * (for example,
String
concatenation)
- * when the log level is more than debug.
- *
- * @return true if debug is enabled in the underlying logger.
- */
- public boolean isDebugEnabled();
- /**
- *
Is error logging currently enabled?
- *
- *
Call this method to prevent having to perform expensive operations
- * (for example,
String
concatenation)
- * when the log level is more than error.
- *
- * @return true if error is enabled in the underlying logger.
- */
- public boolean isErrorEnabled();
- /**
- *
Is fatal logging currently enabled?
- *
- *
Call this method to prevent having to perform expensive operations
- * (for example,
String
concatenation)
- * when the log level is more than fatal.
- *
- * @return true if fatal is enabled in the underlying logger.
- */
- public boolean isFatalEnabled();
- /**
- *
Is info logging currently enabled?
- *
- *
Call this method to prevent having to perform expensive operations
- * (for example,
String
concatenation)
- * when the log level is more than info.
- *
- * @return true if info is enabled in the underlying logger.
- */
- public boolean isInfoEnabled();
- /**
- *
Is trace logging currently enabled?
- *
- *
Call this method to prevent having to perform expensive operations
- * (for example,
String
concatenation)
- * when the log level is more than trace.
- *
- * @return true if trace is enabled in the underlying logger.
- */
- public boolean isTraceEnabled();
- /**
- *
Is warn logging currently enabled?
- *
- *
Call this method to prevent having to perform expensive operations
- * (for example,
String
concatenation)
- * when the log level is more than warn.
- *
- * @return true if warn is enabled in the underlying logger.
- */
- public boolean isWarnEnabled();
- // -------------------------------------------------------- Logging Methods
- /**
- *
Log a message with trace log level.
- *
- * @param message log this message
- */
- public void trace(Object message);
- /**
- *
Log an error with trace log level.
- *
- * @param message log this message
- * @param t log this cause
- */
- public void trace(Object message, Throwable t);
- /**
- *
Log a message with debug log level.
- *
- * @param message log this message
- */
- public void debug(Object message);
- /**
- *
Log an error with debug log level.
- *
- * @param message log this message
- * @param t log this cause
- */
- public void debug(Object message, Throwable t);
- /**
- *
Log a message with info log level.
- *
- * @param message log this message
- */
- public void info(Object message);
- /**
- *
Log an error with info log level.
- *
- * @param message log this message
- * @param t log this cause
- */
- public void info(Object message, Throwable t);
- /**
- *
Log a message with warn log level.
- *
- * @param message log this message
- */
- public void warn(Object message);
- /**
- *
Log an error with warn log level.
- *
- * @param message log this message
- * @param t log this cause
- */
- public void warn(Object message, Throwable t);
- /**
- *
Log a message with error log level.
- *
- * @param message log this message
- */
- public void error(Object message);
- /**
- *
Log an error with error log level.
- *
- * @param message log this message
- * @param t log this cause
- */
- public void error(Object message, Throwable t);
- /**
- *
Log a message with fatal log level.
- *
- * @param message log this message
- */
- public void fatal(Object message);
- /**
- *
Log an error with fatal log level.
- *
- * @param message log this message
- * @param t log this cause
- */
- public void fatal(Object message, Throwable t);
diff --git a/clients/java/src/org/apache/commons/logging/LogConfigurationException.java b/clients/java/src/org/apache/commons/logging/LogConfigurationException.java
deleted file mode 100644
index aae0708..0000000
--- a/clients/java/src/org/apache/commons/logging/LogConfigurationException.java
+++ /dev/null
@@ -1,98 +0,0 @@
- * 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.
-package org.apache.commons.logging;
- *
An exception that is thrown only if a suitable
LogFactory
- * or
Log
instance cannot be created by the corresponding
- * factory methods.
- * @author Craig R. McClanahan
- * @version $Revision: 424107 $ $Date: 2006-07-21 01:15:42 +0200 (fr, 21 jul 2006) $
-public class LogConfigurationException extends RuntimeException {
- /**
- * Construct a new exception with
null
as its detail message.
- */
- public LogConfigurationException() {
- super();
- }
- /**
- * Construct a new exception with the specified detail message.
- *
- * @param message The detail message
- */
- public LogConfigurationException(String message) {
- super(message);
- }
- /**
- * Construct a new exception with the specified cause and a derived
- * detail message.
- *
- * @param cause The underlying cause
- */
- public LogConfigurationException(Throwable cause) {
- this((cause == null) ? null : cause.toString(), cause);
- }
- /**
- * Construct a new exception with the specified detail message and cause.
- *
- * @param message The detail message
- * @param cause The underlying cause
- */
- public LogConfigurationException(String message, Throwable cause) {
- super(message + " (Caused by " + cause + ")");
- this.cause = cause; // Two-argument version requires JDK 1.4 or later
- }
- /**
- * The underlying cause of this exception.
- */
- protected Throwable cause = null;
- /**
- * Return the underlying cause of this exception (if any).
- */
- public Throwable getCause() {
- return (this.cause);
- }
diff --git a/clients/java/src/org/apache/commons/logging/LogFactory.java b/clients/java/src/org/apache/commons/logging/LogFactory.java
deleted file mode 100644
index 526137e..0000000
--- a/clients/java/src/org/apache/commons/logging/LogFactory.java
+++ /dev/null
@@ -1,1824 +0,0 @@
- * 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.
-package org.apache.commons.logging;
-import java.io.BufferedReader;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Properties;
- *
Factory for creating {@link Log} instances, with discovery and
- * configuration features similar to that employed by standard Java APIs
- * such as JAXP.
- *
IMPLEMENTATION NOTE
- This implementation is heavily
- * based on the SAXParserFactory and DocumentBuilderFactory implementations
- * (corresponding to the JAXP pluggability APIs) found in Apache Xerces.
- * @author Craig R. McClanahan
- * @author Costin Manolache
- * @author Richard A. Sitze
- * @version $Revision: 593798 $ $Date: 2007-11-10 18:40:43 +0100 $
-public abstract class LogFactory {
- // Implementation note re AccessController usage
- //
- // It is important to keep code invoked via an AccessController to small
- // auditable blocks. Such code must carefully evaluate all user input
- // (parameters, system properties, config file contents, etc). As an
- // example, a Log implementation should not write to its logfile
- // with an AccessController anywhere in the call stack, otherwise an
- // insecure application could configure the log implementation to write
- // to a protected file using the privileges granted to JCL rather than
- // to the calling application.
- //
- // Under no circumstance should a non-private method return data that is
- // retrieved via an AccessController. That would allow an insecure app
- // to invoke that method and obtain data that it is not permitted to have.
- //
- // Invoking user-supplied code with an AccessController set is not a major
- // issue (eg invoking the constructor of the class specified by
- // HASHTABLE_IMPLEMENTATION_PROPERTY). That class will be in a different
- // trust domain, and therefore must have permissions to do whatever it
- // is trying to do regardless of the permissions granted to JCL. There is
- // a slight issue in that untrusted code may point that environment var
- // to another trusted library, in which case the code runs if both that
- // lib and JCL have the necessary permissions even when the untrusted
- // caller does not. That's a pretty hard route to exploit though.
- // ----------------------------------------------------- Manifest Constants
- /**
- * The name (
priority
) of the key in the config file used to
- * specify the priority of that particular config file. The associated value
- * is a floating-point number; higher values take priority over lower values.
- */
- public static final String PRIORITY_KEY = "priority";
- /**
- * The name (
use_tccl
) of the key in the config file used
- * to specify whether logging classes should be loaded via the thread
- * context class loader (TCCL), or not. By default, the TCCL is used.
- */
- public static final String TCCL_KEY = "use_tccl";
- /**
- * The name (
org.apache.commons.logging.LogFactory
) of the property
- * used to identify the LogFactory implementation
- * class name. This can be used as a system property, or as an entry in a
- * configuration properties file.
- */
- public static final String FACTORY_PROPERTY =
- "org.apache.commons.logging.LogFactory";
- /**
- * The fully qualified class name of the fallback
LogFactory
- * implementation class to use, if no other can be found.
- */
- public static final String FACTORY_DEFAULT =
- "org.apache.commons.logging.impl.LogFactoryImpl";
- /**
- * The name (
commons-logging.properties
) of the properties file to search for.
- */
- public static final String FACTORY_PROPERTIES =
- "commons-logging.properties";
- /**
- * JDK1.3+
- * 'Service Provider' specification
.
- *
- */
- protected static final String SERVICE_ID =
- "META-INF/services/org.apache.commons.logging.LogFactory";
- /**
- * The name (
org.apache.commons.logging.diagnostics.dest
)
- * of the property used to enable internal commons-logging
- * diagnostic output, in order to get information on what logging
- * implementations are being discovered, what classloaders they
- * are loaded through, etc.
- *
- * If a system property of this name is set then the value is
- * assumed to be the name of a file. The special strings
- * STDOUT or STDERR (case-sensitive) indicate output to
- * System.out and System.err respectively.
- *
- * Diagnostic logging should be used only to debug problematic
- * configurations and should not be set in normal production use.
- */
- public static final String DIAGNOSTICS_DEST_PROPERTY =
- "org.apache.commons.logging.diagnostics.dest";
- /**
- * When null (the usual case), no diagnostic output will be
- * generated by LogFactory or LogFactoryImpl. When non-null,
- * interesting events will be written to the specified object.
- */
- private static PrintStream diagnosticsStream = null;
- /**
- * A string that gets prefixed to every message output by the
- * logDiagnostic method, so that users can clearly see which
- * LogFactory class is generating the output.
- */
- private static String diagnosticPrefix;
- /**
- *
Setting this system property
- * (
org.apache.commons.logging.LogFactory.HashtableImpl
)
- * value allows the
Hashtable
used to store
- * classloaders to be substituted by an alternative implementation.
- *
- *
- *
Note:
LogFactory
will print:
- *
- * [ERROR] LogFactory: Load of custom hashtable failed
- *
- * to system error and then continue using a standard Hashtable.
- *
- *
- *
Usage:
Set this property when Java is invoked
- * and
LogFactory
will attempt to load a new instance
- * of the given implementation class.
- * For example, running the following ant scriplet:
- *
- * <java classname="${test.runner}" fork="yes" failonerror="${test.failonerror}">
- * ...
- * <sysproperty
- * key="org.apache.commons.logging.LogFactory.HashtableImpl"
- * value="org.apache.commons.logging.AltHashtable"/>
- * </java>
- *
- * will mean that
LogFactory
will load an instance of
- *
org.apache.commons.logging.AltHashtable
.
- *
- *
- * A typical use case is to allow a custom
- * Hashtable implementation using weak references to be substituted.
- * This will allow classloaders to be garbage collected without
- * the need to release them (on 1.3+ JVMs only, of course ;)
- *
- */
- public static final String HASHTABLE_IMPLEMENTATION_PROPERTY =
- "org.apache.commons.logging.LogFactory.HashtableImpl";
- /** Name used to load the weak hashtable implementation by names */
- private static final String WEAK_HASHTABLE_CLASSNAME =
- "org.apache.commons.logging.impl.WeakHashtable";
- /**
- * A reference to the classloader that loaded this class. This is the
- * same as LogFactory.class.getClassLoader(). However computing this
- * value isn't quite as simple as that, as we potentially need to use
- * AccessControllers etc. It's more efficient to compute it once and
- * cache it here.
- */
- private static ClassLoader thisClassLoader;
- // ----------------------------------------------------------- Constructors
- /**
- * Protected constructor that is not available for public use.
- */
- protected LogFactory() {
- }
- // --------------------------------------------------------- Public Methods
- /**
- * Return the configuration attribute with the specified name (if any),
- * or
null
if there is no such attribute.
- *
- * @param name Name of the attribute to return
- */
- public abstract Object getAttribute(String name);
- /**
- * Return an array containing the names of all currently defined
- * configuration attributes. If there are no such attributes, a zero
- * length array is returned.
- */
- public abstract String[] getAttributeNames();
- /**
- * Convenience method to derive a name from the specified class and
- * call
getInstance(String)
with it.
- *
- * @param clazz Class for which a suitable Log name will be derived
- *
- * @exception LogConfigurationException if a suitable
Log
- * instance cannot be returned
- */
- public abstract Log getInstance(Class clazz)
- throws LogConfigurationException;
- /**
- *
Construct (if necessary) and return a
Log
instance,
- * using the factory's current set of configuration attributes.
- *
- *
NOTE
- Depending upon the implementation of
- * the
LogFactory
you are using, the
Log
- * instance you are returned may or may not be local to the current
- * application, and may or may not be returned again on a subsequent
- * call with the same name argument.
- *
- * @param name Logical name of the
Log
instance to be
- * returned (the meaning of this name is only known to the underlying
- * logging implementation that is being wrapped)
- *
- * @exception LogConfigurationException if a suitable
Log
- * instance cannot be returned
- */
- public abstract Log getInstance(String name)
- throws LogConfigurationException;
- /**
- * Release any internal references to previously created {@link Log}
- * instances returned by this factory. This is useful in environments
- * like servlet containers, which implement application reloading by
- * throwing away a ClassLoader. Dangling references to objects in that
- * class loader would prevent garbage collection.
- */
- public abstract void release();
- /**
- * Remove any configuration attribute associated with the specified name.
- * If there is no such attribute, no action is taken.
- *
- * @param name Name of the attribute to remove
- */
- public abstract void removeAttribute(String name);
- /**
- * Set the configuration attribute with the specified name. Calling
- * this with a
null
value is equivalent to calling
- *
removeAttribute(name)
.
- *
- * @param name Name of the attribute to set
- * @param value Value of the attribute to set, or
null
- * to remove any setting for this attribute
- */
- public abstract void setAttribute(String name, Object value);
- // ------------------------------------------------------- Static Variables
- /**
- * The previously constructed
LogFactory
instances, keyed by
- * the
ClassLoader
with which it was created.
- */
- protected static Hashtable factories = null;
- /**
- * Prevously constructed
LogFactory
instance as in the
- *
factories
map, but for the case where
- *
getClassLoader
returns
null
.
- * This can happen when:
- *
- *
-
using JDK1.1 and the calling code is loaded via the system
- * classloader (very common)
- *
-
using JDK1.2+ and the calling code is loaded via the boot
- * classloader (only likely for embedded systems work).
- *
- * Note that
factories
is a
Hashtable
(not a HashMap),
- * and hashtables don't allow null as a key.
- */
- protected static LogFactory nullClassLoaderFactory = null;
- /**
- * Create the hashtable which will be used to store a map of
- * (context-classloader -> logfactory-object). Version 1.2+ of Java
- * supports "weak references", allowing a custom Hashtable class
- * to be used which uses only weak references to its keys. Using weak
- * references can fix memory leaks on webapp unload in some cases (though
- * not all). Version 1.1 of Java does not support weak references, so we
- * must dynamically determine which we are using. And just for fun, this
- * code also supports the ability for a system property to specify an
- * arbitrary Hashtable implementation name.
- *
- * Note that the correct way to ensure no memory leaks occur is to ensure
- * that LogFactory.release(contextClassLoader) is called whenever a
- * webapp is undeployed.
- */
- private static final Hashtable createFactoryStore() {
- Hashtable result = null;
- String storeImplementationClass;
- try {
- storeImplementationClass = getSystemProperty(HASHTABLE_IMPLEMENTATION_PROPERTY, null);
- } catch(SecurityException ex) {
- // Permissions don't allow this to be accessed. Default to the "modern"
- // weak hashtable implementation if it is available.
- storeImplementationClass = null;
- }
- if (storeImplementationClass == null) {
- storeImplementationClass = WEAK_HASHTABLE_CLASSNAME;
- }
- try {
- Class implementationClass = Class.forName(storeImplementationClass);
- result = (Hashtable) implementationClass.newInstance();
- } catch (Throwable t) {
- // ignore
- if (!WEAK_HASHTABLE_CLASSNAME.equals(storeImplementationClass)) {
- // if the user's trying to set up a custom implementation, give a clue
- if (isDiagnosticsEnabled()) {
- // use internal logging to issue the warning
- logDiagnostic("[ERROR] LogFactory: Load of custom hashtable failed");
- } else {
- // we *really* want this output, even if diagnostics weren't
- // explicitly enabled by the user.
- System.err.println("[ERROR] LogFactory: Load of custom hashtable failed");
- }
- }
- }
- if (result == null) {
- result = new Hashtable();
- }
- return result;
- }
- // --------------------------------------------------------- Static Methods
- /** Utility method to safely trim a string. */
- private static String trim(String src) {
- if (src == null) {
- return null;
- }
- return src.trim();
- }
- /**
- *
Construct (if necessary) and return a
LogFactory
- * instance, using the following ordered lookup procedure to determine
- * the name of the implementation class to be loaded.
- *
- *
-
The
org.apache.commons.logging.LogFactory
system
- * property.
- *
-
The JDK 1.3 Service Discovery mechanism
- *
-
Use the properties file
commons-logging.properties
- * file, if found in the class path of this class. The configuration
- * file is in standard
java.util.Properties
format and
- * contains the fully qualified name of the implementation class
- * with the key being the system property defined above.
- *
-
Fall back to a default implementation class
- * (
org.apache.commons.logging.impl.LogFactoryImpl
).
- *
- *
- *
NOTE
- If the properties file method of identifying the
- *
LogFactory
implementation class is utilized, all of the
- * properties defined in this file will be set as configuration attributes
- * on the corresponding
LogFactory
instance.
- *
- *
NOTE
- In a multithreaded environment it is possible
- * that two different instances will be returned for the same
- * classloader environment.
- *
- *
- * @exception LogConfigurationException if the implementation class is not
- * available or cannot be instantiated.
- */
- public static LogFactory getFactory() throws LogConfigurationException {
- // Identify the class loader we will be using
- ClassLoader contextClassLoader = getContextClassLoaderInternal();
- if (contextClassLoader == null) {
- // This is an odd enough situation to report about. This
- // output will be a nuisance on JDK1.1, as the system
- // classloader is null in that environment.
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Context classloader is null.");
- }
- }
- // Return any previously registered factory for this class loader
- LogFactory factory = getCachedFactory(contextClassLoader);
- if (factory != null) {
- return factory;
- }
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] LogFactory implementation requested for the first time for context classloader "
- + objectId(contextClassLoader));
- logHierarchy("[LOOKUP] ", contextClassLoader);
- }
- // Load properties file.
- //
- // If the properties file exists, then its contents are used as
- // "attributes" on the LogFactory implementation class. One particular
- // property may also control which LogFactory concrete subclass is
- // used, but only if other discovery mechanisms fail..
- //
- // As the properties file (if it exists) will be used one way or
- // another in the end we may as well look for it first.
- Properties props = getConfigurationFile(contextClassLoader, FACTORY_PROPERTIES);
- // Determine whether we will be using the thread context class loader to
- // load logging classes or not by checking the loaded properties file (if any).
- ClassLoader baseClassLoader = contextClassLoader;
- if (props != null) {
- String useTCCLStr = props.getProperty(TCCL_KEY);
- if (useTCCLStr != null) {
- // The Boolean.valueOf(useTCCLStr).booleanValue() formulation
- // is required for Java 1.2 compatability.
- if (Boolean.valueOf(useTCCLStr).booleanValue() == false) {
- // Don't use current context classloader when locating any
- // LogFactory or Log classes, just use the class that loaded
- // this abstract class. When this class is deployed in a shared
- // classpath of a container, it means webapps cannot deploy their
- // own logging implementations. It also means that it is up to the
- // implementation whether to load library-specific config files
- // from the TCCL or not.
- baseClassLoader = thisClassLoader;
- }
- }
- }
- // Determine which concrete LogFactory subclass to use.
- // First, try a global system property
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Looking for system property [" + FACTORY_PROPERTY
- + "] to define the LogFactory subclass to use...");
- }
- try {
- String factoryClass = getSystemProperty(FACTORY_PROPERTY, null);
- if (factoryClass != null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Creating an instance of LogFactory class '" + factoryClass
- + "' as specified by system property " + FACTORY_PROPERTY);
- }
- factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
- } else {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] No system property [" + FACTORY_PROPERTY
- + "] defined.");
- }
- }
- } catch (SecurityException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] A security exception occurred while trying to create an"
- + " instance of the custom factory class"
- + ": [" + trim(e.getMessage())
- + "]. Trying alternative implementations...");
- }
- ; // ignore
- } catch(RuntimeException e) {
- // This is not consistent with the behaviour when a bad LogFactory class is
- // specified in a services file.
- //
- // One possible exception that can occur here is a ClassCastException when
- // the specified class wasn't castable to this LogFactory type.
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] An exception occurred while trying to create an"
- + " instance of the custom factory class"
- + ": [" + trim(e.getMessage())
- + "] as specified by a system property.");
- }
- throw e;
- }
- // Second, try to find a service by using the JDK1.3 class
- // discovery mechanism, which involves putting a file with the name
- // of an interface class in the META-INF/services directory, where the
- // contents of the file is a single line specifying a concrete class
- // that implements the desired interface.
- if (factory == null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Looking for a resource file of name [" + SERVICE_ID
- + "] to define the LogFactory subclass to use...");
- }
- try {
- InputStream is = getResourceAsStream(contextClassLoader,
- SERVICE_ID);
- if( is != null ) {
- // This code is needed by EBCDIC and other strange systems.
- // It's a fix for bugs reported in xerces
- BufferedReader rd;
- try {
- rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- } catch (java.io.UnsupportedEncodingException e) {
- rd = new BufferedReader(new InputStreamReader(is));
- }
- String factoryClassName = rd.readLine();
- rd.close();
- if (factoryClassName != null &&
- ! "".equals(factoryClassName)) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Creating an instance of LogFactory class " + factoryClassName
- + " as specified by file '" + SERVICE_ID
- + "' which was present in the path of the context"
- + " classloader.");
- }
- factory = newFactory(factoryClassName, baseClassLoader, contextClassLoader );
- }
- } else {
- // is == null
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] No resource file with name '" + SERVICE_ID
- + "' found.");
- }
- }
- } catch( Exception ex ) {
- // note: if the specified LogFactory class wasn't compatible with LogFactory
- // for some reason, a ClassCastException will be caught here, and attempts will
- // continue to find a compatible class.
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] A security exception occurred while trying to create an"
- + " instance of the custom factory class"
- + ": [" + trim(ex.getMessage())
- + "]. Trying alternative implementations...");
- }
- ; // ignore
- }
- }
- // Third try looking into the properties file read earlier (if found)
- if (factory == null) {
- if (props != null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Looking in properties file for entry with key '"
- + FACTORY_PROPERTY
- + "' to define the LogFactory subclass to use...");
- }
- String factoryClass = props.getProperty(FACTORY_PROPERTY);
- if (factoryClass != null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Properties file specifies LogFactory subclass '"
- + factoryClass + "'");
- }
- factory = newFactory(factoryClass, baseClassLoader, contextClassLoader);
- // TODO: think about whether we need to handle exceptions from newFactory
- } else {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Properties file has no entry specifying LogFactory subclass.");
- }
- }
- } else {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] No properties file available to determine"
- + " LogFactory subclass from..");
- }
- }
- }
- // Fourth, try the fallback implementation class
- if (factory == null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Loading the default LogFactory implementation '" + FACTORY_DEFAULT
- + "' via the same classloader that loaded this LogFactory"
- + " class (ie not looking in the context classloader).");
- }
- // Note: unlike the above code which can try to load custom LogFactory
- // implementations via the TCCL, we don't try to load the default LogFactory
- // implementation via the context classloader because:
- // * that can cause problems (see comments in newFactory method)
- // * no-one should be customising the code of the default class
- // Yes, we do give up the ability for the child to ship a newer
- // version of the LogFactoryImpl class and have it used dynamically
- // by an old LogFactory class in the parent, but that isn't
- // necessarily a good idea anyway.
- factory = newFactory(FACTORY_DEFAULT, thisClassLoader, contextClassLoader);
- }
- if (factory != null) {
- /**
- * Always cache using context class loader.
- */
- cacheFactory(contextClassLoader, factory);
- if( props!=null ) {
- Enumeration names = props.propertyNames();
- while (names.hasMoreElements()) {
- String name = (String) names.nextElement();
- String value = props.getProperty(name);
- factory.setAttribute(name, value);
- }
- }
- }
- return factory;
- }
- /**
- * Convenience method to return a named logger, without the application
- * having to care about factories.
- *
- * @param clazz Class from which a log name will be derived
- *
- * @exception LogConfigurationException if a suitable
Log
- * instance cannot be returned
- */
- public static Log getLog(Class clazz)
- throws LogConfigurationException {
- return (getFactory().getInstance(clazz));
- }
- /**
- * Convenience method to return a named logger, without the application
- * having to care about factories.
- *
- * @param name Logical name of the
Log
instance to be
- * returned (the meaning of this name is only known to the underlying
- * logging implementation that is being wrapped)
- *
- * @exception LogConfigurationException if a suitable
Log
- * instance cannot be returned
- */
- public static Log getLog(String name)
- throws LogConfigurationException {
- return (getFactory().getInstance(name));
- }
- /**
- * Release any internal references to previously created {@link LogFactory}
- * instances that have been associated with the specified class loader
- * (if any), after calling the instance method
release()
on
- * each of them.
- *
- * @param classLoader ClassLoader for which to release the LogFactory
- */
- public static void release(ClassLoader classLoader) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Releasing factory for classloader " + objectId(classLoader));
- }
- synchronized (factories) {
- if (classLoader == null) {
- if (nullClassLoaderFactory != null) {
- nullClassLoaderFactory.release();
- nullClassLoaderFactory = null;
- }
- } else {
- LogFactory factory = (LogFactory) factories.get(classLoader);
- if (factory != null) {
- factory.release();
- factories.remove(classLoader);
- }
- }
- }
- }
- /**
- * Release any internal references to previously created {@link LogFactory}
- * instances, after calling the instance method
release()
on
- * each of them. This is useful in environments like servlet containers,
- * which implement application reloading by throwing away a ClassLoader.
- * Dangling references to objects in that class loader would prevent
- * garbage collection.
- */
- public static void releaseAll() {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Releasing factory for all classloaders.");
- }
- synchronized (factories) {
- Enumeration elements = factories.elements();
- while (elements.hasMoreElements()) {
- LogFactory element = (LogFactory) elements.nextElement();
- element.release();
- }
- factories.clear();
- if (nullClassLoaderFactory != null) {
- nullClassLoaderFactory.release();
- nullClassLoaderFactory = null;
- }
- }
- }
- // ------------------------------------------------------ Protected Methods
- /**
- * Safely get access to the classloader for the specified class.
- *
- * Theoretically, calling getClassLoader can throw a security exception,
- * and so should be done under an AccessController in order to provide
- * maximum flexibility. However in practice people don't appear to use
- * security policies that forbid getClassLoader calls. So for the moment
- * all code is written to call this method rather than Class.getClassLoader,
- * so that we could put AccessController stuff in this method without any
- * disruption later if we need to.
- *
- * Even when using an AccessController, however, this method can still
- * throw SecurityException. Commons-logging basically relies on the
- * ability to access classloaders, ie a policy that forbids all
- * classloader access will also prevent commons-logging from working:
- * currently this method will throw an exception preventing the entire app
- * from starting up. Maybe it would be good to detect this situation and
- * just disable all commons-logging? Not high priority though - as stated
- * above, security policies that prevent classloader access aren't common.
- *
- * Note that returning an object fetched via an AccessController would
- * technically be a security flaw anyway; untrusted code that has access
- * to a trusted JCL library could use it to fetch the classloader for
- * a class even when forbidden to do so directly.
- *
- * @since 1.1
- */
- protected static ClassLoader getClassLoader(Class clazz) {
- try {
- return clazz.getClassLoader();
- } catch(SecurityException ex) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Unable to get classloader for class '" + clazz
- + "' due to security restrictions - " + ex.getMessage());
- }
- throw ex;
- }
- }
- /**
- * Returns the current context classloader.
- *
- * In versions prior to 1.1, this method did not use an AccessController.
- * In version 1.1, an AccessController wrapper was incorrectly added to
- * this method, causing a minor security flaw.
- *
- * In version 1.1.1 this change was reverted; this method no longer uses
- * an AccessController. User code wishing to obtain the context classloader
- * must invoke this method via AccessController.doPrivileged if it needs
- * support for that.
- *
- * @return the context classloader associated with the current thread,
- * or null if security doesn't allow it.
- *
- * @throws LogConfigurationException if there was some weird error while
- * attempting to get the context classloader.
- *
- * @throws SecurityException if the current java security policy doesn't
- * allow this class to access the context classloader.
- */
- protected static ClassLoader getContextClassLoader()
- throws LogConfigurationException {
- return directGetContextClassLoader();
- }
- /**
- * Calls LogFactory.directGetContextClassLoader under the control of an
- * AccessController class. This means that java code running under a
- * security manager that forbids access to ClassLoaders will still work
- * if this class is given appropriate privileges, even when the caller
- * doesn't have such privileges. Without using an AccessController, the
- * the entire call stack must have the privilege before the call is
- * allowed.
- *
- * @return the context classloader associated with the current thread,
- * or null if security doesn't allow it.
- *
- * @throws LogConfigurationException if there was some weird error while
- * attempting to get the context classloader.
- *
- * @throws SecurityException if the current java security policy doesn't
- * allow this class to access the context classloader.
- */
- private static ClassLoader getContextClassLoaderInternal()
- throws LogConfigurationException {
- return (ClassLoader)AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return directGetContextClassLoader();
- }
- });
- }
- /**
- * Return the thread context class loader if available; otherwise return
- * null.
- *
- * Most/all code should call getContextClassLoaderInternal rather than
- * calling this method directly.
- *
- * The thread context class loader is available for JDK 1.2
- * or later, if certain security conditions are met.
- *
- * Note that no internal logging is done within this method because
- * this method is called every time LogFactory.getLogger() is called,
- * and we don't want too much output generated here.
- *
- * @exception LogConfigurationException if a suitable class loader
- * cannot be identified.
- *
- * @exception SecurityException if the java security policy forbids
- * access to the context classloader from one of the classes in the
- * current call stack.
- * @since 1.1
- */
- protected static ClassLoader directGetContextClassLoader()
- throws LogConfigurationException
- {
- ClassLoader classLoader = null;
- try {
- // Are we running on a JDK 1.2 or later system?
- Method method = Thread.class.getMethod("getContextClassLoader",
- (Class[]) null);
- // Get the thread context class loader (if there is one)
- try {
- classLoader = (ClassLoader)method.invoke(Thread.currentThread(),
- (Object[]) null);
- } catch (IllegalAccessException e) {
- throw new LogConfigurationException
- ("Unexpected IllegalAccessException", e);
- } catch (InvocationTargetException e) {
- /**
- * InvocationTargetException is thrown by 'invoke' when
- * the method being invoked (getContextClassLoader) throws
- * an exception.
- *
- * getContextClassLoader() throws SecurityException when
- * the context class loader isn't an ancestor of the
- * calling class's class loader, or if security
- * permissions are restricted.
- *
- * In the first case (not related), we want to ignore and
- * keep going. We cannot help but also ignore the second
- * with the logic below, but other calls elsewhere (to
- * obtain a class loader) will trigger this exception where
- * we can make a distinction.
- */
- if (e.getTargetException() instanceof SecurityException) {
- ; // ignore
- } else {
- // Capture 'e.getTargetException()' exception for details
- // alternate: log 'e.getTargetException()', and pass back 'e'.
- throw new LogConfigurationException
- ("Unexpected InvocationTargetException", e.getTargetException());
- }
- }
- } catch (NoSuchMethodException e) {
- // Assume we are running on JDK 1.1
- classLoader = getClassLoader(LogFactory.class);
- // We deliberately don't log a message here to outputStream;
- // this message would be output for every call to LogFactory.getLog()
- // when running on JDK1.1
- //
- // if (outputStream != null) {
- // outputStream.println(
- // "Method Thread.getContextClassLoader does not exist;"
- // + " assuming this is JDK 1.1, and that the context"
- // + " classloader is the same as the class that loaded"
- // + " the concrete LogFactory class.");
- // }
- }
- // Return the selected class loader
- return classLoader;
- }
- /**
- * Check cached factories (keyed by contextClassLoader)
- *
- * @param contextClassLoader is the context classloader associated
- * with the current thread. This allows separate LogFactory objects
- * per component within a container, provided each component has
- * a distinct context classloader set. This parameter may be null
- * in JDK1.1, and in embedded systems where jcl-using code is
- * placed in the bootclasspath.
- *
- * @return the factory associated with the specified classloader if
- * one has previously been created, or null if this is the first time
- * we have seen this particular classloader.
- */
- private static LogFactory getCachedFactory(ClassLoader contextClassLoader)
- {
- LogFactory factory = null;
- if (contextClassLoader == null) {
- // We have to handle this specially, as factories is a Hashtable
- // and those don't accept null as a key value.
- //
- // nb: nullClassLoaderFactory might be null. That's ok.
- factory = nullClassLoaderFactory;
- } else {
- factory = (LogFactory) factories.get(contextClassLoader);
- }
- return factory;
- }
- /**
- * Remember this factory, so later calls to LogFactory.getCachedFactory
- * can return the previously created object (together with all its
- * cached Log objects).
- *
- * @param classLoader should be the current context classloader. Note that
- * this can be null under some circumstances; this is ok.
- *
- * @param factory should be the factory to cache. This should never be null.
- */
- private static void cacheFactory(ClassLoader classLoader, LogFactory factory)
- {
- // Ideally we would assert(factory != null) here. However reporting
- // errors from within a logging implementation is a little tricky!
- if (factory != null) {
- if (classLoader == null) {
- nullClassLoaderFactory = factory;
- } else {
- factories.put(classLoader, factory);
- }
- }
- }
- /**
- * Return a new instance of the specified
LogFactory
- * implementation class, loaded by the specified class loader.
- * If that fails, try the class loader used to load this
- * (abstract) LogFactory.
- *
- *
ClassLoader conflicts
- * Note that there can be problems if the specified ClassLoader is not the
- * same as the classloader that loaded this class, ie when loading a
- * concrete LogFactory subclass via a context classloader.
- *
- * The problem is the same one that can occur when loading a concrete Log
- * subclass via a context classloader.
- *
- * The problem occurs when code running in the context classloader calls
- * class X which was loaded via a parent classloader, and class X then calls
- * LogFactory.getFactory (either directly or via LogFactory.getLog). Because
- * class X was loaded via the parent, it binds to LogFactory loaded via
- * the parent. When the code in this method finds some LogFactoryYYYY
- * class in the child (context) classloader, and there also happens to be a
- * LogFactory class defined in the child classloader, then LogFactoryYYYY
- * will be bound to LogFactory@childloader. It cannot be cast to
- * LogFactory@parentloader, ie this method cannot return the object as
- * the desired type. Note that it doesn't matter if the LogFactory class
- * in the child classloader is identical to the LogFactory class in the
- * parent classloader, they are not compatible.
- *
- * The solution taken here is to simply print out an error message when
- * this occurs then throw an exception. The deployer of the application
- * must ensure they remove all occurrences of the LogFactory class from
- * the child classloader in order to resolve the issue. Note that they
- * do not have to move the custom LogFactory subclass; that is ok as
- * long as the only LogFactory class it can find to bind to is in the
- * parent classloader.
- *
- * @param factoryClass Fully qualified name of the
LogFactory
- * implementation class
- * @param classLoader ClassLoader from which to load this class
- * @param contextClassLoader is the context that this new factory will
- * manage logging for.
- *
- * @exception LogConfigurationException if a suitable instance
- * cannot be created
- * @since 1.1
- */
- protected static LogFactory newFactory(final String factoryClass,
- final ClassLoader classLoader,
- final ClassLoader contextClassLoader)
- throws LogConfigurationException
- {
- // Note that any unchecked exceptions thrown by the createFactory
- // method will propagate out of this method; in particular a
- // ClassCastException can be thrown.
- Object result = AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return createFactory(factoryClass, classLoader);
- }
- });
- if (result instanceof LogConfigurationException) {
- LogConfigurationException ex = (LogConfigurationException) result;
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "An error occurred while loading the factory class:"
- + ex.getMessage());
- }
- throw ex;
- }
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Created object " + objectId(result)
- + " to manage classloader " + objectId(contextClassLoader));
- }
- return (LogFactory)result;
- }
- /**
- * Method provided for backwards compatibility; see newFactory version that
- * takes 3 parameters.
- *
- * This method would only ever be called in some rather odd situation.
- * Note that this method is static, so overriding in a subclass doesn't
- * have any effect unless this method is called from a method in that
- * subclass. However this method only makes sense to use from the
- * getFactory method, and as that is almost always invoked via
- * LogFactory.getFactory, any custom definition in a subclass would be
- * pointless. Only a class with a custom getFactory method, then invoked
- * directly via CustomFactoryImpl.getFactory or similar would ever call
- * this. Anyway, it's here just in case, though the "managed class loader"
- * value output to the diagnostics will not report the correct value.
- */
- protected static LogFactory newFactory(final String factoryClass,
- final ClassLoader classLoader) {
- return newFactory(factoryClass, classLoader, null);
- }
- /**
- * Implements the operations described in the javadoc for newFactory.
- *
- * @param factoryClass
- *
- * @param classLoader used to load the specified factory class. This is
- * expected to be either the TCCL or the classloader which loaded this
- * class. Note that the classloader which loaded this class might be
- * "null" (ie the bootloader) for embedded systems.
- *
- * @return either a LogFactory object or a LogConfigurationException object.
- * @since 1.1
- */
- protected static Object createFactory(String factoryClass, ClassLoader classLoader) {
- // This will be used to diagnose bad configurations
- // and allow a useful message to be sent to the user
- Class logFactoryClass = null;
- try {
- if (classLoader != null) {
- try {
- // First the given class loader param (thread class loader)
- // Warning: must typecast here & allow exception
- // to be generated/caught & recast properly.
- logFactoryClass = classLoader.loadClass(factoryClass);
- if (LogFactory.class.isAssignableFrom(logFactoryClass)) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Loaded class " + logFactoryClass.getName()
- + " from classloader " + objectId(classLoader));
- }
- } else {
- //
- // This indicates a problem with the ClassLoader tree.
- // An incompatible ClassLoader was used to load the
- // implementation.
- // As the same classes
- // must be available in multiple class loaders,
- // it is very likely that multiple JCL jars are present.
- // The most likely fix for this
- // problem is to remove the extra JCL jars from the
- // ClassLoader hierarchy.
- //
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Factory class " + logFactoryClass.getName()
- + " loaded from classloader " + objectId(logFactoryClass.getClassLoader())
- + " does not extend '" + LogFactory.class.getName()
- + "' as loaded by this classloader.");
- logHierarchy("[BAD CL TREE] ", classLoader);
- }
- }
- return (LogFactory) logFactoryClass.newInstance();
- } catch (ClassNotFoundException ex) {
- if (classLoader == thisClassLoader) {
- // Nothing more to try, onwards.
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Unable to locate any class called '" + factoryClass
- + "' via classloader " + objectId(classLoader));
- }
- throw ex;
- }
- // ignore exception, continue
- } catch (NoClassDefFoundError e) {
- if (classLoader == thisClassLoader) {
- // Nothing more to try, onwards.
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Class '" + factoryClass + "' cannot be loaded"
- + " via classloader " + objectId(classLoader)
- + " - it depends on some other class that cannot"
- + " be found.");
- }
- throw e;
- }
- // ignore exception, continue
- } catch(ClassCastException e) {
- if (classLoader == thisClassLoader) {
- // There's no point in falling through to the code below that
- // tries again with thisClassLoader, because we've just tried
- // loading with that loader (not the TCCL). Just throw an
- // appropriate exception here.
- final boolean implementsLogFactory = implementsLogFactory(logFactoryClass);
- //
- // Construct a good message: users may not actual expect that a custom implementation
- // has been specified. Several well known containers use this mechanism to adapt JCL
- // to their native logging system.
- //
- String msg =
- "The application has specified that a custom LogFactory implementation should be used but " +
- "Class '" + factoryClass + "' cannot be converted to '"
- + LogFactory.class.getName() + "'. ";
- if (implementsLogFactory) {
- msg = msg + "The conflict is caused by the presence of multiple LogFactory classes in incompatible classloaders. " +
- "Background can be found in http://commons.apache.org/logging/tech.html. " +
- "If you have not explicitly specified a custom LogFactory then it is likely that " +
- "the container has set one without your knowledge. " +
- "In this case, consider using the commons-logging-adapters.jar file or " +
- "specifying the standard LogFactory from the command line. ";
- } else {
- msg = msg + "Please check the custom implementation. ";
- }
- msg = msg + "Help can be found @http://commons.apache.org/logging/troubleshooting.html.";
- if (isDiagnosticsEnabled()) {
- logDiagnostic(msg);
- }
- ClassCastException ex = new ClassCastException(msg);
- throw ex;
- }
- // Ignore exception, continue. Presumably the classloader was the
- // TCCL; the code below will try to load the class via thisClassLoader.
- // This will handle the case where the original calling class is in
- // a shared classpath but the TCCL has a copy of LogFactory and the
- // specified LogFactory implementation; we will fall back to using the
- // LogFactory implementation from the same classloader as this class.
- //
- // Issue: this doesn't handle the reverse case, where this LogFactory
- // is in the webapp, and the specified LogFactory implementation is
- // in a shared classpath. In that case:
- // (a) the class really does implement LogFactory (bad log msg above)
- // (b) the fallback code will result in exactly the same problem.
- }
- }
- /* At this point, either classLoader == null, OR
- * classLoader was unable to load factoryClass.
- *
- * In either case, we call Class.forName, which is equivalent
- * to LogFactory.class.getClassLoader().load(name), ie we ignore
- * the classloader parameter the caller passed, and fall back
- * to trying the classloader associated with this class. See the
- * javadoc for the newFactory method for more info on the
- * consequences of this.
- *
- * Notes:
- * * LogFactory.class.getClassLoader() may return 'null'
- * if LogFactory is loaded by the bootstrap classloader.
- */
- // Warning: must typecast here & allow exception
- // to be generated/caught & recast properly.
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Unable to load factory class via classloader "
- + objectId(classLoader)
- + " - trying the classloader associated with this LogFactory.");
- }
- logFactoryClass = Class.forName(factoryClass);
- return (LogFactory) logFactoryClass.newInstance();
- } catch (Exception e) {
- // Check to see if we've got a bad configuration
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Unable to create LogFactory instance.");
- }
- if (logFactoryClass != null
- && !LogFactory.class.isAssignableFrom(logFactoryClass)) {
- return new LogConfigurationException(
- "The chosen LogFactory implementation does not extend LogFactory."
- + " Please check your configuration.",
- e);
- }
- return new LogConfigurationException(e);
- }
- }
- /**
- * Determines whether the given class actually implements
LogFactory
.
- * Diagnostic information is also logged.
- *
- *
Usage:
to diagnose whether a classloader conflict is the cause
- * of incompatibility. The test used is whether the class is assignable from
- * the
LogFactory
class loaded by the class's classloader.
- * @param logFactoryClass
Class
which may implement
LogFactory
- * @return true if the
logFactoryClass
does extend
- *
LogFactory
when that class is loaded via the same
- * classloader that loaded the
logFactoryClass
.
- */
- private static boolean implementsLogFactory(Class logFactoryClass) {
- boolean implementsLogFactory = false;
- if (logFactoryClass != null) {
- try {
- ClassLoader logFactoryClassLoader = logFactoryClass.getClassLoader();
- if (logFactoryClassLoader == null) {
- logDiagnostic("[CUSTOM LOG FACTORY] was loaded by the boot classloader");
- } else {
- logHierarchy("[CUSTOM LOG FACTORY] ", logFactoryClassLoader);
- Class factoryFromCustomLoader
- = Class.forName("org.apache.commons.logging.LogFactory", false, logFactoryClassLoader);
- implementsLogFactory = factoryFromCustomLoader.isAssignableFrom(logFactoryClass);
- if (implementsLogFactory) {
- logDiagnostic("[CUSTOM LOG FACTORY] " + logFactoryClass.getName()
- + " implements LogFactory but was loaded by an incompatible classloader.");
- } else {
- logDiagnostic("[CUSTOM LOG FACTORY] " + logFactoryClass.getName()
- + " does not implement LogFactory.");
- }
- }
- } catch (SecurityException e) {
- //
- // The application is running within a hostile security environment.
- // This will make it very hard to diagnose issues with JCL.
- // Consider running less securely whilst debugging this issue.
- //
- logDiagnostic("[CUSTOM LOG FACTORY] SecurityException thrown whilst trying to determine whether " +
- "the compatibility was caused by a classloader conflict: "
- + e.getMessage());
- } catch (LinkageError e) {
- //
- // This should be an unusual circumstance.
- // LinkageError's usually indicate that a dependent class has incompatibly changed.
- // Another possibility may be an exception thrown by an initializer.
- // Time for a clean rebuild?
- //
- logDiagnostic("[CUSTOM LOG FACTORY] LinkageError thrown whilst trying to determine whether " +
- "the compatibility was caused by a classloader conflict: "
- + e.getMessage());
- } catch (ClassNotFoundException e) {
- //
- // LogFactory cannot be loaded by the classloader which loaded the custom factory implementation.
- // The custom implementation is not viable until this is corrected.
- // Ensure that the JCL jar and the custom class are available from the same classloader.
- // Running with diagnostics on should give information about the classloaders used
- // to load the custom factory.
- //
- logDiagnostic("[CUSTOM LOG FACTORY] LogFactory class cannot be loaded by classloader which loaded the " +
- "custom LogFactory implementation. Is the custom factory in the right classloader?");
- }
- }
- return implementsLogFactory;
- }
- /**
- * Applets may run in an environment where accessing resources of a loader is
- * a secure operation, but where the commons-logging library has explicitly
- * been granted permission for that operation. In this case, we need to
- * run the operation using an AccessController.
- */
- private static InputStream getResourceAsStream(final ClassLoader loader,
- final String name)
- {
- return (InputStream)AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- if (loader != null) {
- return loader.getResourceAsStream(name);
- } else {
- return ClassLoader.getSystemResourceAsStream(name);
- }
- }
- });
- }
- /**
- * Given a filename, return an enumeration of URLs pointing to
- * all the occurrences of that filename in the classpath.
- *
- * This is just like ClassLoader.getResources except that the
- * operation is done under an AccessController so that this method will
- * succeed when this jarfile is privileged but the caller is not.
- * This method must therefore remain private to avoid security issues.
- *
- * If no instances are found, an Enumeration is returned whose
- * hasMoreElements method returns false (ie an "empty" enumeration).
- * If resources could not be listed for some reason, null is returned.
- */
- private static Enumeration getResources(final ClassLoader loader,
- final String name)
- {
- PrivilegedAction action =
- new PrivilegedAction() {
- public Object run() {
- try {
- if (loader != null) {
- return loader.getResources(name);
- } else {
- return ClassLoader.getSystemResources(name);
- }
- } catch(IOException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Exception while trying to find configuration file "
- + name + ":" + e.getMessage());
- }
- return null;
- } catch(NoSuchMethodError e) {
- // we must be running on a 1.1 JVM which doesn't support
- // ClassLoader.getSystemResources; just return null in
- // this case.
- return null;
- }
- }
- };
- Object result = AccessController.doPrivileged(action);
- return (Enumeration) result;
- }
- /**
- * Given a URL that refers to a .properties file, load that file.
- * This is done under an AccessController so that this method will
- * succeed when this jarfile is privileged but the caller is not.
- * This method must therefore remain private to avoid security issues.
- *
- * Null is returned if the URL cannot be opened.
- */
- private static Properties getProperties(final URL url) {
- PrivilegedAction action =
- new PrivilegedAction() {
- public Object run() {
- try {
- InputStream stream = url.openStream();
- if (stream != null) {
- Properties props = new Properties();
- props.load(stream);
- stream.close();
- return props;
- }
- } catch(IOException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Unable to read URL " + url);
- }
- }
- return null;
- }
- };
- return (Properties) AccessController.doPrivileged(action);
- }
- /**
- * Locate a user-provided configuration file.
- *
- * The classpath of the specified classLoader (usually the context classloader)
- * is searched for properties files of the specified name. If none is found,
- * null is returned. If more than one is found, then the file with the greatest
- * value for its PRIORITY property is returned. If multiple files have the
- * same PRIORITY value then the first in the classpath is returned.
- *
- * This differs from the 1.0.x releases; those always use the first one found.
- * However as the priority is a new field, this change is backwards compatible.
- *
- * The purpose of the priority field is to allow a webserver administrator to
- * override logging settings in all webapps by placing a commons-logging.properties
- * file in a shared classpath location with a priority > 0; this overrides any
- * commons-logging.properties files without priorities which are in the
- * webapps. Webapps can also use explicit priorities to override a configuration
- * file in the shared classpath if needed.
- */
- private static final Properties getConfigurationFile(
- ClassLoader classLoader, String fileName) {
- Properties props = null;
- double priority = 0.0;
- URL propsUrl = null;
- try {
- Enumeration urls = getResources(classLoader, fileName);
- if (urls == null) {
- return null;
- }
- while (urls.hasMoreElements()) {
- URL url = (URL) urls.nextElement();
- Properties newProps = getProperties(url);
- if (newProps != null) {
- if (props == null) {
- propsUrl = url;
- props = newProps;
- String priorityStr = props.getProperty(PRIORITY_KEY);
- priority = 0.0;
- if (priorityStr != null) {
- priority = Double.parseDouble(priorityStr);
- }
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Properties file found at '" + url + "'"
- + " with priority " + priority);
- }
- } else {
- String newPriorityStr = newProps.getProperty(PRIORITY_KEY);
- double newPriority = 0.0;
- if (newPriorityStr != null) {
- newPriority = Double.parseDouble(newPriorityStr);
- }
- if (newPriority > priority) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Properties file at '" + url + "'"
- + " with priority " + newPriority
- + " overrides file at '" + propsUrl + "'"
- + " with priority " + priority);
- }
- propsUrl = url;
- props = newProps;
- priority = newPriority;
- } else {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[LOOKUP] Properties file at '" + url + "'"
- + " with priority " + newPriority
- + " does not override file at '" + propsUrl + "'"
- + " with priority " + priority);
- }
- }
- }
- }
- }
- } catch (SecurityException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("SecurityException thrown while trying to find/read config files.");
- }
- }
- if (isDiagnosticsEnabled()) {
- if (props == null) {
- logDiagnostic(
- "[LOOKUP] No properties file of name '" + fileName
- + "' found.");
- } else {
- logDiagnostic(
- "[LOOKUP] Properties file of name '" + fileName
- + "' found at '" + propsUrl + '"');
- }
- }
- return props;
- }
- /**
- * Read the specified system property, using an AccessController so that
- * the property can be read if JCL has been granted the appropriate
- * security rights even if the calling code has not.
- *
- * Take care not to expose the value returned by this method to the
- * calling application in any way; otherwise the calling app can use that
- * info to access data that should not be available to it.
- */
- private static String getSystemProperty(final String key, final String def)
- throws SecurityException {
- return (String) AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return System.getProperty(key, def);
- }
- });
- }
- /**
- * Determines whether the user wants internal diagnostic output. If so,
- * returns an appropriate writer object. Users can enable diagnostic
- * output by setting the system property named {@link #DIAGNOSTICS_DEST_PROPERTY} to
- * a filename, or the special values STDOUT or STDERR.
- */
- private static void initDiagnostics() {
- String dest;
- try {
- dest = getSystemProperty(DIAGNOSTICS_DEST_PROPERTY, null);
- if (dest == null) {
- return;
- }
- } catch(SecurityException ex) {
- // We must be running in some very secure environment.
- // We just have to assume output is not wanted..
- return;
- }
- if (dest.equals("STDOUT")) {
- diagnosticsStream = System.out;
- } else if (dest.equals("STDERR")) {
- diagnosticsStream = System.err;
- } else {
- try {
- // open the file in append mode
- FileOutputStream fos = new FileOutputStream(dest, true);
- diagnosticsStream = new PrintStream(fos);
- } catch(IOException ex) {
- // We should report this to the user - but how?
- return;
- }
- }
- // In order to avoid confusion where multiple instances of JCL are
- // being used via different classloaders within the same app, we
- // ensure each logged message has a prefix of form
- // [LogFactory from classloader OID]
- //
- // Note that this prefix should be kept consistent with that
- // in LogFactoryImpl. However here we don't need to output info
- // about the actual *instance* of LogFactory, as all methods that
- // output diagnostics from this class are static.
- String classLoaderName;
- try {
- ClassLoader classLoader = thisClassLoader;
- if (thisClassLoader == null) {
- classLoaderName = "BOOTLOADER";
- } else {
- classLoaderName = objectId(classLoader);
- }
- } catch(SecurityException e) {
- classLoaderName = "UNKNOWN";
- }
- diagnosticPrefix = "[LogFactory from " + classLoaderName + "] ";
- }
- /**
- * Indicates true if the user has enabled internal logging.
- *
- * By the way, sorry for the incorrect grammar, but calling this method
- * areDiagnosticsEnabled just isn't java beans style.
- *
- * @return true if calls to logDiagnostic will have any effect.
- * @since 1.1
- */
- protected static boolean isDiagnosticsEnabled() {
- return diagnosticsStream != null;
- }
- /**
- * Write the specified message to the internal logging destination.
- *
- * Note that this method is private; concrete subclasses of this class
- * should not call it because the diagnosticPrefix string this
- * method puts in front of all its messages is LogFactory@....,
- * while subclasses should put SomeSubClass@...
- *
- * Subclasses should instead compute their own prefix, then call
- * logRawDiagnostic. Note that calling isDiagnosticsEnabled is
- * fine for subclasses.
- *
- * Note that it is safe to call this method before initDiagnostics
- * is called; any output will just be ignored (as isDiagnosticsEnabled
- * will return false).
- *
- * @param msg is the diagnostic message to be output.
- */
- private static final void logDiagnostic(String msg) {
- if (diagnosticsStream != null) {
- diagnosticsStream.print(diagnosticPrefix);
- diagnosticsStream.println(msg);
- diagnosticsStream.flush();
- }
- }
- /**
- * Write the specified message to the internal logging destination.
- *
- * @param msg is the diagnostic message to be output.
- * @since 1.1
- */
- protected static final void logRawDiagnostic(String msg) {
- if (diagnosticsStream != null) {
- diagnosticsStream.println(msg);
- diagnosticsStream.flush();
- }
- }
- /**
- * Generate useful diagnostics regarding the classloader tree for
- * the specified class.
- *
- * As an example, if the specified class was loaded via a webapp's
- * classloader, then you may get the following output:
- *
- * Class com.acme.Foo was loaded via classloader 11111
- * ClassLoader tree: 11111 -> 22222 (SYSTEM) -> 33333 -> BOOT
- *
- *
- * This method returns immediately if isDiagnosticsEnabled()
- * returns false.
- *
- * @param clazz is the class whose classloader + tree are to be
- * output.
- */
- private static void logClassLoaderEnvironment(Class clazz) {
- if (!isDiagnosticsEnabled()) {
- return;
- }
- try {
- // Deliberately use System.getProperty here instead of getSystemProperty; if
- // the overall security policy for the calling application forbids access to
- // these variables then we do not want to output them to the diagnostic stream.
- logDiagnostic("[ENV] Extension directories (java.ext.dir): " + System.getProperty("java.ext.dir"));
- logDiagnostic("[ENV] Application classpath (java.class.path): " + System.getProperty("java.class.path"));
- } catch(SecurityException ex) {
- logDiagnostic("[ENV] Security setting prevent interrogation of system classpaths.");
- }
- String className = clazz.getName();
- ClassLoader classLoader;
- try {
- classLoader = getClassLoader(clazz);
- } catch(SecurityException ex) {
- // not much useful diagnostics we can print here!
- logDiagnostic(
- "[ENV] Security forbids determining the classloader for " + className);
- return;
- }
- logDiagnostic(
- "[ENV] Class " + className + " was loaded via classloader "
- + objectId(classLoader));
- logHierarchy("[ENV] Ancestry of classloader which loaded " + className + " is ", classLoader);
- }
- /**
- * Logs diagnostic messages about the given classloader
- * and it's hierarchy. The prefix is prepended to the message
- * and is intended to make it easier to understand the logs.
- * @param prefix
- * @param classLoader
- */
- private static void logHierarchy(String prefix, ClassLoader classLoader) {
- if (!isDiagnosticsEnabled()) {
- return;
- }
- ClassLoader systemClassLoader;
- if (classLoader != null) {
- final String classLoaderString = classLoader.toString();
- logDiagnostic(prefix + objectId(classLoader) + " == '" + classLoaderString + "'");
- }
- try {
- systemClassLoader = ClassLoader.getSystemClassLoader();
- } catch(SecurityException ex) {
- logDiagnostic(
- prefix + "Security forbids determining the system classloader.");
- return;
- }
- if (classLoader != null) {
- StringBuffer buf = new StringBuffer(prefix + "ClassLoader tree:");
- for(;;) {
- buf.append(objectId(classLoader));
- if (classLoader == systemClassLoader) {
- buf.append(" (SYSTEM) ");
- }
- try {
- classLoader = classLoader.getParent();
- } catch(SecurityException ex) {
- buf.append(" --> SECRET");
- break;
- }
- buf.append(" --> ");
- if (classLoader == null) {
- buf.append("BOOT");
- break;
- }
- }
- logDiagnostic(buf.toString());
- }
- }
- /**
- * Returns a string that uniquely identifies the specified object, including
- * its class.
- *
- * The returned string is of form "classname@hashcode", ie is the same as
- * the return value of the Object.toString() method, but works even when
- * the specified object's class has overidden the toString method.
- *
- * @param o may be null.
- * @return a string of form classname@hashcode, or "null" if param o is null.
- * @since 1.1
- */
- public static String objectId(Object o) {
- if (o == null) {
- return "null";
- } else {
- return o.getClass().getName() + "@" + System.identityHashCode(o);
- }
- }
- // ----------------------------------------------------------------------
- // Static initialiser block to perform initialisation at class load time.
- //
- // We can't do this in the class constructor, as there are many
- // static methods on this class that can be called before any
- // LogFactory instances are created, and they depend upon this
- // stuff having been set up.
- //
- // Note that this block must come after any variable declarations used
- // by any methods called from this block, as we want any static initialiser
- // associated with the variable to run first. If static initialisers for
- // variables run after this code, then (a) their value might be needed
- // by methods called from here, and (b) they might *override* any value
- // computed here!
- //
- // So the wisest thing to do is just to place this code at the very end
- // of the class file.
- // ----------------------------------------------------------------------
- static {
- // note: it's safe to call methods before initDiagnostics (though
- // diagnostic output gets discarded).
- thisClassLoader = getClassLoader(LogFactory.class);
- initDiagnostics();
- logClassLoaderEnvironment(LogFactory.class);
- factories = createFactoryStore();
- if (isDiagnosticsEnabled()) {
- logDiagnostic("BOOTSTRAP COMPLETED");
- }
- }
diff --git a/clients/java/src/org/apache/commons/logging/LogSource.java b/clients/java/src/org/apache/commons/logging/LogSource.java
deleted file mode 100644
index 9cb5f11..0000000
--- a/clients/java/src/org/apache/commons/logging/LogSource.java
+++ /dev/null
@@ -1,262 +0,0 @@
- * 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.
-package org.apache.commons.logging;
-import java.lang.reflect.Constructor;
-import java.util.Hashtable;
-import org.apache.commons.logging.impl.NoOpLog;
- *
Factory for creating {@link Log} instances. Applications should call
- * the
makeNewLogInstance()
method to instantiate new instances
- * of the configured {@link Log} implementation class.
- *
By default, calling
getInstance()
will use the following
- * algorithm:
- *
-
If Log4J is available, return an instance of
- *
org.apache.commons.logging.impl.Log4JLogger
.
- *
-
If JDK 1.4 or later is available, return an instance of
- *
org.apache.commons.logging.impl.Jdk14Logger
.
- *
-
Otherwise, return an instance of
- *
org.apache.commons.logging.impl.NoOpLog
.
- *
You can change the default behavior in one of two ways:
- *
-
On the startup command line, set the system property
- *
org.apache.commons.logging.log
to the name of the
- *
org.apache.commons.logging.Log
implementation class
- * you want to use.
- *
-
At runtime, call
LogSource.setLogImplementation()
.
- * @deprecated Use {@link LogFactory} instead - The default factory
- * implementation performs exactly the same algorithm as this class did
- * @author Rod Waldhoff
- * @version $Id: LogSource.java 424107 2006-07-20 23:15:42Z skitching $
-public class LogSource {
- // ------------------------------------------------------- Class Attributes
- static protected Hashtable logs = new Hashtable();
- /** Is log4j available (in the current classpath) */
- static protected boolean log4jIsAvailable = false;
- /** Is JDK 1.4 logging available */
- static protected boolean jdk14IsAvailable = false;
- /** Constructor for current log class */
- static protected Constructor logImplctor = null;
- // ----------------------------------------------------- Class Initializers
- static {
- // Is Log4J Available?
- try {
- if (null != Class.forName("org.apache.log4j.Logger")) {
- log4jIsAvailable = true;
- } else {
- log4jIsAvailable = false;
- }
- } catch (Throwable t) {
- log4jIsAvailable = false;
- }
- // Is JDK 1.4 Logging Available?
- try {
- if ((null != Class.forName("java.util.logging.Logger")) &&
- (null != Class.forName("org.apache.commons.logging.impl.Jdk14Logger"))) {
- jdk14IsAvailable = true;
- } else {
- jdk14IsAvailable = false;
- }
- } catch (Throwable t) {
- jdk14IsAvailable = false;
- }
- // Set the default Log implementation
- String name = null;
- try {
- name = System.getProperty("org.apache.commons.logging.log");
- if (name == null) {
- name = System.getProperty("org.apache.commons.logging.Log");
- }
- } catch (Throwable t) {
- }
- if (name != null) {
- try {
- setLogImplementation(name);
- } catch (Throwable t) {
- try {
- setLogImplementation
- ("org.apache.commons.logging.impl.NoOpLog");
- } catch (Throwable u) {
- ;
- }
- }
- } else {
- try {
- if (log4jIsAvailable) {
- setLogImplementation
- ("org.apache.commons.logging.impl.Log4JLogger");
- } else if (jdk14IsAvailable) {
- setLogImplementation
- ("org.apache.commons.logging.impl.Jdk14Logger");
- } else {
- setLogImplementation
- ("org.apache.commons.logging.impl.NoOpLog");
- }
- } catch (Throwable t) {
- try {
- setLogImplementation
- ("org.apache.commons.logging.impl.NoOpLog");
- } catch (Throwable u) {
- ;
- }
- }
- }
- }
- // ------------------------------------------------------------ Constructor
- /** Don't allow others to create instances */
- private LogSource() {
- }
- // ---------------------------------------------------------- Class Methods
- /**
- * Set the log implementation/log implementation factory
- * by the name of the class. The given class
- * must implement {@link Log}, and provide a constructor that
- * takes a single {@link String} argument (containing the name
- * of the log).
- */
- static public void setLogImplementation(String classname) throws
- LinkageError, ExceptionInInitializerError,
- NoSuchMethodException, SecurityException,
- ClassNotFoundException {
- try {
- Class logclass = Class.forName(classname);
- Class[] argtypes = new Class[1];
- argtypes[0] = "".getClass();
- logImplctor = logclass.getConstructor(argtypes);
- } catch (Throwable t) {
- logImplctor = null;
- }
- }
- /**
- * Set the log implementation/log implementation factory
- * by class. The given class must implement {@link Log},
- * and provide a constructor that takes a single {@link String}
- * argument (containing the name of the log).
- */
- static public void setLogImplementation(Class logclass) throws
- LinkageError, ExceptionInInitializerError,
- NoSuchMethodException, SecurityException {
- Class[] argtypes = new Class[1];
- argtypes[0] = "".getClass();
- logImplctor = logclass.getConstructor(argtypes);
- }
- /** Get a
Log
instance by class name */
- static public Log getInstance(String name) {
- Log log = (Log) (logs.get(name));
- if (null == log) {
- log = makeNewLogInstance(name);
- logs.put(name, log);
- }
- return log;
- }
- /** Get a
Log
instance by class */
- static public Log getInstance(Class clazz) {
- return getInstance(clazz.getName());
- }
- /**
- * Create a new {@link Log} implementation, based
- * on the given
name
.
- *
- * The specific {@link Log} implementation returned
- * is determined by the value of the
- *
org.apache.commons.logging.log
property.
- * The value of
org.apache.commons.logging.log
may be set to
- * the fully specified name of a class that implements
- * the {@link Log} interface. This class must also
- * have a public constructor that takes a single
- * {@link String} argument (containing the
name
- * of the {@link Log} to be constructed.
- *
- * When
org.apache.commons.logging.log
is not set,
- * or when no corresponding class can be found,
- * this method will return a Log4JLogger
- * if the log4j Logger class is
- * available in the {@link LogSource}'s classpath, or a
- * Jdk14Logger if we are on a JDK 1.4 or later system, or
- * NoOpLog if neither of the above conditions is true.
- *
- * @param name the log name (or category)
- */
- static public Log makeNewLogInstance(String name) {
- Log log = null;
- try {
- Object[] args = new Object[1];
- args[0] = name;
- log = (Log) (logImplctor.newInstance(args));
- } catch (Throwable t) {
- log = null;
- }
- if (null == log) {
- log = new NoOpLog(name);
- }
- return log;
- }
- /**
- * Returns a {@link String} array containing the names of
- * all logs known to me.
- */
- static public String[] getLogNames() {
- return (String[]) (logs.keySet().toArray(new String[logs.size()]));
- }
diff --git a/clients/java/src/org/apache/commons/logging/impl/AvalonLogger.java b/clients/java/src/org/apache/commons/logging/impl/AvalonLogger.java
deleted file mode 100644
index df8398c..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/AvalonLogger.java
+++ /dev/null
@@ -1,292 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import org.apache.avalon.framework.logger.Logger;
-import org.apache.commons.logging.Log;
- *
Implementation of commons-logging Log interface that delegates all
- * logging calls to the Avalon logging abstraction: the Logger interface.
- * There are two ways in which this class can be used:
- *
-
the instance can be constructed with an Avalon logger
- * (by calling {@link #AvalonLogger(Logger)}). In this case, it acts
- * as a simple thin wrapping implementation over the logger. This is
- * particularly useful when using a property setter.
- *
-
the {@link #setDefaultLogger} class property can be called which
- * sets the ancesteral Avalon logger for this class. Any
AvalonLogger
- * instances created through the
LogFactory
mechanisms will output
- * to child loggers of this
Logger
.
- *
Note:
AvalonLogger
does not implement Serializable
- * because the constructors available for it make this impossible to achieve in all
- * circumstances; there is no way to "reconnect" to an underlying Logger object on
- * deserialization if one was just passed in to the constructor of the original
- * object. This class
was
marked Serializable in the 1.0.4 release of
- * commons-logging, but this never actually worked (a NullPointerException would
- * be thrown as soon as the deserialized object was used), so removing this marker
- * is not considered to be an incompatible change.
- * @author
Neeme Praks
- * @version $Revision: 424107 $ $Date: 2006-07-21 01:15:42 +0200 (fr, 21 jul 2006) $
-public class AvalonLogger implements Log {
- /** Ancesteral avalon logger */
- private static Logger defaultLogger = null;
- /** Avalon logger used to perform log */
- private transient Logger logger = null;
- /**
- * Constructs an
AvalonLogger
that outputs to the given
- *
Logger
instance.
- * @param logger the avalon logger implementation to delegate to
- */
- public AvalonLogger(Logger logger) {
- this.logger = logger;
- }
- /**
- * Constructs an
AvalonLogger
that will log to a child
- * of the
Logger
set by calling {@link #setDefaultLogger}.
- * @param name the name of the avalon logger implementation to delegate to
- */
- public AvalonLogger(String name) {
- if (defaultLogger == null)
- throw new NullPointerException("default logger has to be specified if this constructor is used!");
- this.logger = defaultLogger.getChildLogger(name);
- }
- /**
- * Gets the Avalon logger implementation used to perform logging.
- * @return avalon logger implementation
- */
- public Logger getLogger() {
- return logger;
- }
- /**
- * Sets the ancesteral Avalon logger from which the delegating loggers
- * will descend.
- * @param logger the default avalon logger,
- * in case there is no logger instance supplied in constructor
- */
- public static void setDefaultLogger(Logger logger) {
- defaultLogger = logger;
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.debug
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#debug(Object, Throwable)
- */
- public void debug(Object message, Throwable t) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message), t);
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.debug
.
- *
- * @param message to log.
- * @see org.apache.commons.logging.Log#debug(Object)
- */
- public void debug(Object message) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message));
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.error
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#error(Object, Throwable)
- */
- public void error(Object message, Throwable t) {
- if (getLogger().isErrorEnabled()) getLogger().error(String.valueOf(message), t);
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.error
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#error(Object)
- */
- public void error(Object message) {
- if (getLogger().isErrorEnabled()) getLogger().error(String.valueOf(message));
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.fatalError
.
- *
- * @param message to log.
- * @param t log this cause.
- * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
- */
- public void fatal(Object message, Throwable t) {
- if (getLogger().isFatalErrorEnabled()) getLogger().fatalError(String.valueOf(message), t);
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.fatalError
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#fatal(Object)
- */
- public void fatal(Object message) {
- if (getLogger().isFatalErrorEnabled()) getLogger().fatalError(String.valueOf(message));
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.info
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#info(Object, Throwable)
- */
- public void info(Object message, Throwable t) {
- if (getLogger().isInfoEnabled()) getLogger().info(String.valueOf(message), t);
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.info
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#info(Object)
- */
- public void info(Object message) {
- if (getLogger().isInfoEnabled()) getLogger().info(String.valueOf(message));
- }
- /**
- * Is logging to
- *
org.apache.avalon.framework.logger.Logger.debug
enabled?
- * @see org.apache.commons.logging.Log#isDebugEnabled()
- */
- public boolean isDebugEnabled() {
- return getLogger().isDebugEnabled();
- }
- /**
- * Is logging to
- *
org.apache.avalon.framework.logger.Logger.error
enabled?
- * @see org.apache.commons.logging.Log#isErrorEnabled()
- */
- public boolean isErrorEnabled() {
- return getLogger().isErrorEnabled();
- }
- /**
- * Is logging to
- *
org.apache.avalon.framework.logger.Logger.fatalError
enabled?
- * @see org.apache.commons.logging.Log#isFatalEnabled()
- */
- public boolean isFatalEnabled() {
- return getLogger().isFatalErrorEnabled();
- }
- /**
- * Is logging to
- *
org.apache.avalon.framework.logger.Logger.info
enabled?
- * @see org.apache.commons.logging.Log#isInfoEnabled()
- */
- public boolean isInfoEnabled() {
- return getLogger().isInfoEnabled();
- }
- /**
- * Is logging to
- *
org.apache.avalon.framework.logger.Logger.debug
enabled?
- * @see org.apache.commons.logging.Log#isTraceEnabled()
- */
- public boolean isTraceEnabled() {
- return getLogger().isDebugEnabled();
- }
- /**
- * Is logging to
- *
org.apache.avalon.framework.logger.Logger.warn
enabled?
- * @see org.apache.commons.logging.Log#isWarnEnabled()
- */
- public boolean isWarnEnabled() {
- return getLogger().isWarnEnabled();
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.debug
.
- *
- * @param message to log.
- * @param t log this cause.
- * @see org.apache.commons.logging.Log#trace(Object, Throwable)
- */
- public void trace(Object message, Throwable t) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message), t);
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.debug
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#trace(Object)
- */
- public void trace(Object message) {
- if (getLogger().isDebugEnabled()) getLogger().debug(String.valueOf(message));
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.warn
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#warn(Object, Throwable)
- */
- public void warn(Object message, Throwable t) {
- if (getLogger().isWarnEnabled()) getLogger().warn(String.valueOf(message), t);
- }
- /**
- * Logs a message with
- *
org.apache.avalon.framework.logger.Logger.warn
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#warn(Object)
- */
- public void warn(Object message) {
- if (getLogger().isWarnEnabled()) getLogger().warn(String.valueOf(message));
- }
diff --git a/clients/java/src/org/apache/commons/logging/impl/Jdk13LumberjackLogger.java b/clients/java/src/org/apache/commons/logging/impl/Jdk13LumberjackLogger.java
deleted file mode 100644
index 2188bdc..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/Jdk13LumberjackLogger.java
+++ /dev/null
@@ -1,335 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import java.io.Serializable;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.logging.LogRecord;
-import java.util.StringTokenizer;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import org.apache.commons.logging.Log;
- *
Implementation of the
org.apache.commons.logging.Log
- * interface that wraps the standard JDK logging mechanisms that are
- * available in SourceForge's Lumberjack for JDKs prior to 1.4.
- * @author
Scott Sanders
- * @author
Berin Loritsch
- * @author
Peter Donald
- * @author
Vince Eagen
- * @version $Revision: 424107 $ $Date: 2006-07-21 01:15:42 +0200 (fr, 21 jul 2006) $
- * @since 1.1
-public class Jdk13LumberjackLogger implements Log, Serializable {
- // ----------------------------------------------------- Instance Variables
- /**
- * The underlying Logger implementation we are using.
- */
- protected transient Logger logger = null;
- protected String name = null;
- private String sourceClassName = "unknown";
- private String sourceMethodName = "unknown";
- private boolean classAndMethodFound = false;
- /**
- * This member variable simply ensures that any attempt to initialise
- * this class in a pre-1.4 JVM will result in an ExceptionInInitializerError.
- * It must not be private, as an optimising compiler could detect that it
- * is not used and optimise it away.
- */
- protected static final Level dummyLevel = Level.FINE;
- // ----------------------------------------------------------- Constructors
- /**
- * Construct a named instance of this Logger.
- *
- * @param name Name of the logger to be constructed
- */
- public Jdk13LumberjackLogger(String name) {
- this.name = name;
- logger = getLogger();
- }
- // --------------------------------------------------------- Public Methods
- private void log( Level level, String msg, Throwable ex ) {
- if( getLogger().isLoggable(level) ) {
- LogRecord record = new LogRecord(level, msg);
- if( !classAndMethodFound ) {
- getClassAndMethod();
- }
- record.setSourceClassName(sourceClassName);
- record.setSourceMethodName(sourceMethodName);
- if( ex != null ) {
- record.setThrown(ex);
- }
- getLogger().log(record);
- }
- }
- /**
- *
Gets the class and method by looking at the stack trace for the
- * first entry that is not this class.
- */
- private void getClassAndMethod() {
- try {
- Throwable throwable = new Throwable();
- throwable.fillInStackTrace();
- StringWriter stringWriter = new StringWriter();
- PrintWriter printWriter = new PrintWriter( stringWriter );
- throwable.printStackTrace( printWriter );
- String traceString = stringWriter.getBuffer().toString();
- StringTokenizer tokenizer =
- new StringTokenizer( traceString, "\n" );
- tokenizer.nextToken();
- String line = tokenizer.nextToken();
- while ( line.indexOf( this.getClass().getName() ) == -1 ) {
- line = tokenizer.nextToken();
- }
- while ( line.indexOf( this.getClass().getName() ) >= 0 ) {
- line = tokenizer.nextToken();
- }
- int start = line.indexOf( "at " ) + 3;
- int end = line.indexOf( '(' );
- String temp = line.substring( start, end );
- int lastPeriod = temp.lastIndexOf( '.' );
- sourceClassName = temp.substring( 0, lastPeriod );
- sourceMethodName = temp.substring( lastPeriod + 1 );
- } catch ( Exception ex ) {
- // ignore - leave class and methodname unknown
- }
- classAndMethodFound = true;
- }
- /**
- * Logs a message with
java.util.logging.Level.FINE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#debug(Object)
- */
- public void debug(Object message) {
- log(Level.FINE, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.FINE
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#debug(Object, Throwable)
- */
- public void debug(Object message, Throwable exception) {
- log(Level.FINE, String.valueOf(message), exception);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#error(Object)
- */
- public void error(Object message) {
- log(Level.SEVERE, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#error(Object, Throwable)
- */
- public void error(Object message, Throwable exception) {
- log(Level.SEVERE, String.valueOf(message), exception);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#fatal(Object)
- */
- public void fatal(Object message) {
- log(Level.SEVERE, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
- */
- public void fatal(Object message, Throwable exception) {
- log(Level.SEVERE, String.valueOf(message), exception);
- }
- /**
- * Return the native Logger instance we are using.
- */
- public Logger getLogger() {
- if (logger == null) {
- logger = Logger.getLogger(name);
- }
- return (logger);
- }
- /**
- * Logs a message with
java.util.logging.Level.INFO
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#info(Object)
- */
- public void info(Object message) {
- log(Level.INFO, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.INFO
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#info(Object, Throwable)
- */
- public void info(Object message, Throwable exception) {
- log(Level.INFO, String.valueOf(message), exception);
- }
- /**
- * Is debug logging currently enabled?
- */
- public boolean isDebugEnabled() {
- return (getLogger().isLoggable(Level.FINE));
- }
- /**
- * Is error logging currently enabled?
- */
- public boolean isErrorEnabled() {
- return (getLogger().isLoggable(Level.SEVERE));
- }
- /**
- * Is fatal logging currently enabled?
- */
- public boolean isFatalEnabled() {
- return (getLogger().isLoggable(Level.SEVERE));
- }
- /**
- * Is info logging currently enabled?
- */
- public boolean isInfoEnabled() {
- return (getLogger().isLoggable(Level.INFO));
- }
- /**
- * Is trace logging currently enabled?
- */
- public boolean isTraceEnabled() {
- return (getLogger().isLoggable(Level.FINEST));
- }
- /**
- * Is warn logging currently enabled?
- */
- public boolean isWarnEnabled() {
- return (getLogger().isLoggable(Level.WARNING));
- }
- /**
- * Logs a message with
java.util.logging.Level.FINEST
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#trace(Object)
- */
- public void trace(Object message) {
- log(Level.FINEST, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.FINEST
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#trace(Object, Throwable)
- */
- public void trace(Object message, Throwable exception) {
- log(Level.FINEST, String.valueOf(message), exception);
- }
- /**
- * Logs a message with
java.util.logging.Level.WARNING
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#warn(Object)
- */
- public void warn(Object message) {
- log(Level.WARNING, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.WARNING
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#warn(Object, Throwable)
- */
- public void warn(Object message, Throwable exception) {
- log(Level.WARNING, String.valueOf(message), exception);
- }
diff --git a/clients/java/src/org/apache/commons/logging/impl/Jdk14Logger.java b/clients/java/src/org/apache/commons/logging/impl/Jdk14Logger.java
deleted file mode 100644
index b8cb510..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/Jdk14Logger.java
+++ /dev/null
@@ -1,304 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import java.io.Serializable;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import org.apache.commons.logging.Log;
- *
Implementation of the
org.apache.commons.logging.Log
- * interface that wraps the standard JDK logging mechanisms that were
- * introduced in the Merlin release (JDK 1.4).
- * @author
Scott Sanders
- * @author
Berin Loritsch
- * @author
Peter Donald
- * @version $Revision: 424107 $ $Date: 2006-07-21 01:15:42 +0200 (fr, 21 jul 2006) $
-public class Jdk14Logger implements Log, Serializable {
- /**
- * This member variable simply ensures that any attempt to initialise
- * this class in a pre-1.4 JVM will result in an ExceptionInInitializerError.
- * It must not be private, as an optimising compiler could detect that it
- * is not used and optimise it away.
- */
- protected static final Level dummyLevel = Level.FINE;
- // ----------------------------------------------------------- Constructors
- /**
- * Construct a named instance of this Logger.
- *
- * @param name Name of the logger to be constructed
- */
- public Jdk14Logger(String name) {
- this.name = name;
- logger = getLogger();
- }
- // ----------------------------------------------------- Instance Variables
- /**
- * The underlying Logger implementation we are using.
- */
- protected transient Logger logger = null;
- /**
- * The name of the logger we are wrapping.
- */
- protected String name = null;
- // --------------------------------------------------------- Public Methods
- private void log( Level level, String msg, Throwable ex ) {
- Logger logger = getLogger();
- if (logger.isLoggable(level)) {
- // Hack (?) to get the stack trace.
- Throwable dummyException=new Throwable();
- StackTraceElement locations[]=dummyException.getStackTrace();
- // Caller will be the third element
- String cname="unknown";
- String method="unknown";
- if( locations!=null && locations.length >2 ) {
- StackTraceElement caller=locations[2];
- cname=caller.getClassName();
- method=caller.getMethodName();
- }
- if( ex==null ) {
- logger.logp( level, cname, method, msg );
- } else {
- logger.logp( level, cname, method, msg, ex );
- }
- }
- }
- /**
- * Logs a message with
java.util.logging.Level.FINE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#debug(Object)
- */
- public void debug(Object message) {
- log(Level.FINE, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.FINE
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#debug(Object, Throwable)
- */
- public void debug(Object message, Throwable exception) {
- log(Level.FINE, String.valueOf(message), exception);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#error(Object)
- */
- public void error(Object message) {
- log(Level.SEVERE, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#error(Object, Throwable)
- */
- public void error(Object message, Throwable exception) {
- log(Level.SEVERE, String.valueOf(message), exception);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#fatal(Object)
- */
- public void fatal(Object message) {
- log(Level.SEVERE, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.SEVERE
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
- */
- public void fatal(Object message, Throwable exception) {
- log(Level.SEVERE, String.valueOf(message), exception);
- }
- /**
- * Return the native Logger instance we are using.
- */
- public Logger getLogger() {
- if (logger == null) {
- logger = Logger.getLogger(name);
- }
- return (logger);
- }
- /**
- * Logs a message with
java.util.logging.Level.INFO
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#info(Object)
- */
- public void info(Object message) {
- log(Level.INFO, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.INFO
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#info(Object, Throwable)
- */
- public void info(Object message, Throwable exception) {
- log(Level.INFO, String.valueOf(message), exception);
- }
- /**
- * Is debug logging currently enabled?
- */
- public boolean isDebugEnabled() {
- return (getLogger().isLoggable(Level.FINE));
- }
- /**
- * Is error logging currently enabled?
- */
- public boolean isErrorEnabled() {
- return (getLogger().isLoggable(Level.SEVERE));
- }
- /**
- * Is fatal logging currently enabled?
- */
- public boolean isFatalEnabled() {
- return (getLogger().isLoggable(Level.SEVERE));
- }
- /**
- * Is info logging currently enabled?
- */
- public boolean isInfoEnabled() {
- return (getLogger().isLoggable(Level.INFO));
- }
- /**
- * Is trace logging currently enabled?
- */
- public boolean isTraceEnabled() {
- return (getLogger().isLoggable(Level.FINEST));
- }
- /**
- * Is warn logging currently enabled?
- */
- public boolean isWarnEnabled() {
- return (getLogger().isLoggable(Level.WARNING));
- }
- /**
- * Logs a message with
java.util.logging.Level.FINEST
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#trace(Object)
- */
- public void trace(Object message) {
- log(Level.FINEST, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.FINEST
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#trace(Object, Throwable)
- */
- public void trace(Object message, Throwable exception) {
- log(Level.FINEST, String.valueOf(message), exception);
- }
- /**
- * Logs a message with
java.util.logging.Level.WARNING
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#warn(Object)
- */
- public void warn(Object message) {
- log(Level.WARNING, String.valueOf(message), null);
- }
- /**
- * Logs a message with
java.util.logging.Level.WARNING
.
- *
- * @param message to log
- * @param exception log this cause
- * @see org.apache.commons.logging.Log#warn(Object, Throwable)
- */
- public void warn(Object message, Throwable exception) {
- log(Level.WARNING, String.valueOf(message), exception);
- }
diff --git a/clients/java/src/org/apache/commons/logging/impl/LogFactoryImpl.java b/clients/java/src/org/apache/commons/logging/impl/LogFactoryImpl.java
deleted file mode 100644
index 20c8a36..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/LogFactoryImpl.java
+++ /dev/null
@@ -1,1500 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Vector;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogConfigurationException;
-import org.apache.commons.logging.LogFactory;
- *
Concrete subclass of {@link LogFactory} that implements the
- * following algorithm to dynamically select a logging implementation
- * class to instantiate a wrapper for.
- *
-
Use a factory configuration attribute named
- *
org.apache.commons.logging.Log
to identify the
- * requested implementation class.
- *
-
Use the
org.apache.commons.logging.Log
system property
- * to identify the requested implementation class.
- *
-
If
Log4J
is available, return an instance of
- *
org.apache.commons.logging.impl.Log4JLogger
.
- *
-
If
JDK 1.4 or later
is available, return an instance of
- *
org.apache.commons.logging.impl.Jdk14Logger
.
- *
-
Otherwise, return an instance of
- *
org.apache.commons.logging.impl.SimpleLog
.
- *
If the selected {@link Log} implementation class has a
- *
setLogFactory()
method that accepts a {@link LogFactory}
- * parameter, this method will be called on each newly created instance
- * to identify the associated factory. This makes factory configuration
- * attributes available to the Log instance, if it so desires.
- *
This factory will remember previously created
Log
instances
- * for the same name, and will return them on repeated requests to the
- *
getInstance()
method.
- * @author Rod Waldhoff
- * @author Craig R. McClanahan
- * @author Richard A. Sitze
- * @author Brian Stansberry
- * @version $Revision: 581090 $ $Date: 2007-10-02 00:01:06 +0200 (ti, 02 okt 2007) $
-public class LogFactoryImpl extends LogFactory {
- /** Log4JLogger class name */
- private static final String LOGGING_IMPL_LOG4J_LOGGER = "org.apache.commons.logging.impl.Log4JLogger";
- /** Jdk14Logger class name */
- private static final String LOGGING_IMPL_JDK14_LOGGER = "org.apache.commons.logging.impl.Jdk14Logger";
- /** Jdk13LumberjackLogger class name */
- private static final String LOGGING_IMPL_LUMBERJACK_LOGGER = "org.apache.commons.logging.impl.Jdk13LumberjackLogger";
- /** SimpleLog class name */
- private static final String LOGGING_IMPL_SIMPLE_LOGGER = "org.apache.commons.logging.impl.SimpleLog";
- private static final String PKG_IMPL="org.apache.commons.logging.impl.";
- private static final int PKG_LEN = PKG_IMPL.length();
- // ----------------------------------------------------------- Constructors
- /**
- * Public no-arguments constructor required by the lookup mechanism.
- */
- public LogFactoryImpl() {
- super();
- initDiagnostics(); // method on this object
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Instance created.");
- }
- }
- // ----------------------------------------------------- Manifest Constants
- /**
- * The name (
org.apache.commons.logging.Log
) of the system
- * property identifying our {@link Log} implementation class.
- */
- public static final String LOG_PROPERTY =
- "org.apache.commons.logging.Log";
- /**
- * The deprecated system property used for backwards compatibility with
- * old versions of JCL.
- */
- protected static final String LOG_PROPERTY_OLD =
- "org.apache.commons.logging.log";
- /**
- * The name (
org.apache.commons.logging.Log.allowFlawedContext
)
- * of the system property which can be set true/false to
- * determine system behaviour when a bad context-classloader is encountered.
- * When set to false, a LogConfigurationException is thrown if
- * LogFactoryImpl is loaded via a child classloader of the TCCL (this
- * should never happen in sane systems).
- *
- * Default behaviour: true (tolerates bad context classloaders)
- *
- * See also method setAttribute.
- */
- public static final String ALLOW_FLAWED_CONTEXT_PROPERTY =
- "org.apache.commons.logging.Log.allowFlawedContext";
- /**
- * The name (
org.apache.commons.logging.Log.allowFlawedDiscovery
)
- * of the system property which can be set true/false to
- * determine system behaviour when a bad logging adapter class is
- * encountered during logging discovery. When set to false, an
- * exception will be thrown and the app will fail to start. When set
- * to true, discovery will continue (though the user might end up
- * with a different logging implementation than they expected).
- *
- * Default behaviour: true (tolerates bad logging adapters)
- *
- * See also method setAttribute.
- */
- public static final String ALLOW_FLAWED_DISCOVERY_PROPERTY =
- "org.apache.commons.logging.Log.allowFlawedDiscovery";
- /**
- * The name (
org.apache.commons.logging.Log.allowFlawedHierarchy
)
- * of the system property which can be set true/false to
- * determine system behaviour when a logging adapter class is
- * encountered which has bound to the wrong Log class implementation.
- * When set to false, an exception will be thrown and the app will fail
- * to start. When set to true, discovery will continue (though the user
- * might end up with a different logging implementation than they expected).
- *
- * Default behaviour: true (tolerates bad Log class hierarchy)
- *
- * See also method setAttribute.
- */
- public static final String ALLOW_FLAWED_HIERARCHY_PROPERTY =
- "org.apache.commons.logging.Log.allowFlawedHierarchy";
- /**
- * The names of classes that will be tried (in order) as logging
- * adapters. Each class is expected to implement the Log interface,
- * and to throw NoClassDefFound or ExceptionInInitializerError when
- * loaded if the underlying logging library is not available. Any
- * other error indicates that the underlying logging library is available
- * but broken/unusable for some reason.
- */
- private static final String[] classesToDiscover = {
- LOGGING_IMPL_LOG4J_LOGGER,
- "org.apache.commons.logging.impl.Jdk14Logger",
- "org.apache.commons.logging.impl.Jdk13LumberjackLogger",
- "org.apache.commons.logging.impl.SimpleLog"
- };
- // ----------------------------------------------------- Instance Variables
- /**
- * Determines whether logging classes should be loaded using the thread-context
- * classloader, or via the classloader that loaded this LogFactoryImpl class.
- */
- private boolean useTCCL = true;
- /**
- * The string prefixed to every message output by the logDiagnostic method.
- */
- private String diagnosticPrefix;
- /**
- * Configuration attributes.
- */
- protected Hashtable attributes = new Hashtable();
- /**
- * The {@link org.apache.commons.logging.Log} instances that have
- * already been created, keyed by logger name.
- */
- protected Hashtable instances = new Hashtable();
- /**
- * Name of the class implementing the Log interface.
- */
- private String logClassName;
- /**
- * The one-argument constructor of the
- * {@link org.apache.commons.logging.Log}
- * implementation class that will be used to create new instances.
- * This value is initialized by
getLogConstructor()
,
- * and then returned repeatedly.
- */
- protected Constructor logConstructor = null;
- /**
- * The signature of the Constructor to be used.
- */
- protected Class logConstructorSignature[] =
- { java.lang.String.class };
- /**
- * The one-argument
setLogFactory
method of the selected
- * {@link org.apache.commons.logging.Log} method, if it exists.
- */
- protected Method logMethod = null;
- /**
- * The signature of the
setLogFactory
method to be used.
- */
- protected Class logMethodSignature[] =
- { LogFactory.class };
- /**
- * See getBaseClassLoader and initConfiguration.
- */
- private boolean allowFlawedContext;
- /**
- * See handleFlawedDiscovery and initConfiguration.
- */
- private boolean allowFlawedDiscovery;
- /**
- * See handleFlawedHierarchy and initConfiguration.
- */
- private boolean allowFlawedHierarchy;
- // --------------------------------------------------------- Public Methods
- /**
- * Return the configuration attribute with the specified name (if any),
- * or
null
if there is no such attribute.
- *
- * @param name Name of the attribute to return
- */
- public Object getAttribute(String name) {
- return (attributes.get(name));
- }
- /**
- * Return an array containing the names of all currently defined
- * configuration attributes. If there are no such attributes, a zero
- * length array is returned.
- */
- public String[] getAttributeNames() {
- Vector names = new Vector();
- Enumeration keys = attributes.keys();
- while (keys.hasMoreElements()) {
- names.addElement((String) keys.nextElement());
- }
- String results[] = new String[names.size()];
- for (int i = 0; i < results.length; i++) {
- results[i] = (String) names.elementAt(i);
- }
- return (results);
- }
- /**
- * Convenience method to derive a name from the specified class and
- * call
getInstance(String)
with it.
- *
- * @param clazz Class for which a suitable Log name will be derived
- *
- * @exception LogConfigurationException if a suitable
Log
- * instance cannot be returned
- */
- public Log getInstance(Class clazz) throws LogConfigurationException {
- return (getInstance(clazz.getName()));
- }
- /**
- *
Construct (if necessary) and return a
Log
instance,
- * using the factory's current set of configuration attributes.
- *
- *
NOTE
- Depending upon the implementation of
- * the
LogFactory
you are using, the
Log
- * instance you are returned may or may not be local to the current
- * application, and may or may not be returned again on a subsequent
- * call with the same name argument.
- *
- * @param name Logical name of the
Log
instance to be
- * returned (the meaning of this name is only known to the underlying
- * logging implementation that is being wrapped)
- *
- * @exception LogConfigurationException if a suitable
Log
- * instance cannot be returned
- */
- public Log getInstance(String name) throws LogConfigurationException {
- Log instance = (Log) instances.get(name);
- if (instance == null) {
- instance = newInstance(name);
- instances.put(name, instance);
- }
- return (instance);
- }
- /**
- * Release any internal references to previously created
- * {@link org.apache.commons.logging.Log}
- * instances returned by this factory. This is useful in environments
- * like servlet containers, which implement application reloading by
- * throwing away a ClassLoader. Dangling references to objects in that
- * class loader would prevent garbage collection.
- */
- public void release() {
- logDiagnostic("Releasing all known loggers");
- instances.clear();
- }
- /**
- * Remove any configuration attribute associated with the specified name.
- * If there is no such attribute, no action is taken.
- *
- * @param name Name of the attribute to remove
- */
- public void removeAttribute(String name) {
- attributes.remove(name);
- }
- /**
- * Set the configuration attribute with the specified name. Calling
- * this with a
null
value is equivalent to calling
- *
removeAttribute(name)
.
- *
- * This method can be used to set logging configuration programmatically
- * rather than via system properties. It can also be used in code running
- * within a container (such as a webapp) to configure behaviour on a
- * per-component level instead of globally as system properties would do.
- * To use this method instead of a system property, call
- *
- * LogFactory.getFactory().setAttribute(...)
- *
- * This must be done before the first Log object is created; configuration
- * changes after that point will be ignored.
- *
- * This method is also called automatically if LogFactory detects a
- * commons-logging.properties file; every entry in that file is set
- * automatically as an attribute here.
- *
- * @param name Name of the attribute to set
- * @param value Value of the attribute to set, or
null
- * to remove any setting for this attribute
- */
- public void setAttribute(String name, Object value) {
- if (logConstructor != null) {
- logDiagnostic("setAttribute: call too late; configuration already performed.");
- }
- if (value == null) {
- attributes.remove(name);
- } else {
- attributes.put(name, value);
- }
- if (name.equals(TCCL_KEY)) {
- useTCCL = Boolean.valueOf(value.toString()).booleanValue();
- }
- }
- // ------------------------------------------------------
- // Static Methods
- //
- // These methods only defined as workarounds for a java 1.2 bug;
- // theoretically none of these are needed.
- // ------------------------------------------------------
- /**
- * Gets the context classloader.
- * This method is a workaround for a java 1.2 compiler bug.
- * @since 1.1
- */
- protected static ClassLoader getContextClassLoader() throws LogConfigurationException {
- return LogFactory.getContextClassLoader();
- }
- /**
- * Workaround for bug in Java1.2; in theory this method is not needed.
- * See LogFactory.isDiagnosticsEnabled.
- */
- protected static boolean isDiagnosticsEnabled() {
- return LogFactory.isDiagnosticsEnabled();
- }
- /**
- * Workaround for bug in Java1.2; in theory this method is not needed.
- * See LogFactory.getClassLoader.
- * @since 1.1
- */
- protected static ClassLoader getClassLoader(Class clazz) {
- return LogFactory.getClassLoader(clazz);
- }
- // ------------------------------------------------------ Protected Methods
- /**
- * Calculate and cache a string that uniquely identifies this instance,
- * including which classloader the object was loaded from.
- *
- * This string will later be prefixed to each "internal logging" message
- * emitted, so that users can clearly see any unexpected behaviour.
- *
- * Note that this method does not detect whether internal logging is
- * enabled or not, nor where to output stuff if it is; that is all
- * handled by the parent LogFactory class. This method just computes
- * its own unique prefix for log messages.
- */
- private void initDiagnostics() {
- // It would be nice to include an identifier of the context classloader
- // that this LogFactoryImpl object is responsible for. However that
- // isn't possible as that information isn't available. It is possible
- // to figure this out by looking at the logging from LogFactory to
- // see the context & impl ids from when this object was instantiated,
- // in order to link the impl id output as this object's prefix back to
- // the context it is intended to manage.
- // Note that this prefix should be kept consistent with that
- // in LogFactory.
- Class clazz = this.getClass();
- ClassLoader classLoader = getClassLoader(clazz);
- String classLoaderName;
- try {
- if (classLoader == null) {
- classLoaderName = "BOOTLOADER";
- } else {
- classLoaderName = objectId(classLoader);
- }
- } catch(SecurityException e) {
- classLoaderName = "UNKNOWN";
- }
- diagnosticPrefix = "[LogFactoryImpl@" + System.identityHashCode(this) + " from " + classLoaderName + "] ";
- }
- /**
- * Output a diagnostic message to a user-specified destination (if the
- * user has enabled diagnostic logging).
- *
- * @param msg diagnostic message
- * @since 1.1
- */
- protected void logDiagnostic(String msg) {
- if (isDiagnosticsEnabled()) {
- logRawDiagnostic(diagnosticPrefix + msg);
- }
- }
- /**
- * Return the fully qualified Java classname of the {@link Log}
- * implementation we will be using.
- *
- * @deprecated Never invoked by this class; subclasses should not assume
- * it will be.
- */
- protected String getLogClassName() {
- if (logClassName == null) {
- discoverLogImplementation(getClass().getName());
- }
- return logClassName;
- }
- /**
- *
Return the
Constructor
that can be called to instantiate
- * new {@link org.apache.commons.logging.Log} instances.
- *
- *
IMPLEMENTATION NOTE
- Race conditions caused by
- * calling this method from more than one thread are ignored, because
- * the same
Constructor
instance will ultimately be derived
- * in all circumstances.
- *
- * @exception LogConfigurationException if a suitable constructor
- * cannot be returned
- *
- * @deprecated Never invoked by this class; subclasses should not assume
- * it will be.
- */
- protected Constructor getLogConstructor()
- throws LogConfigurationException {
- // Return the previously identified Constructor (if any)
- if (logConstructor == null) {
- discoverLogImplementation(getClass().getName());
- }
- return logConstructor;
- }
- /**
- * Is
JDK 1.3 with Lumberjack
logging available?
- *
- * @deprecated Never invoked by this class; subclasses should not assume
- * it will be.
- */
- protected boolean isJdk13LumberjackAvailable() {
- return isLogLibraryAvailable(
- "Jdk13Lumberjack",
- "org.apache.commons.logging.impl.Jdk13LumberjackLogger");
- }
- /**
- *
Return
true
if
JDK 1.4 or later
logging
- * is available. Also checks that the
Throwable
class
- * supports
getStackTrace()
, which is required by
- * Jdk14Logger.
- *
- * @deprecated Never invoked by this class; subclasses should not assume
- * it will be.
- */
- protected boolean isJdk14Available() {
- return isLogLibraryAvailable(
- "Jdk14",
- "org.apache.commons.logging.impl.Jdk14Logger");
- }
- /**
- * Is a
Log4J
implementation available?
- *
- * @deprecated Never invoked by this class; subclasses should not assume
- * it will be.
- */
- protected boolean isLog4JAvailable() {
- return isLogLibraryAvailable(
- "Log4J",
- LOGGING_IMPL_LOG4J_LOGGER);
- }
- /**
- * Create and return a new {@link org.apache.commons.logging.Log}
- * instance for the specified name.
- *
- * @param name Name of the new logger
- *
- * @exception LogConfigurationException if a new instance cannot
- * be created
- */
- protected Log newInstance(String name) throws LogConfigurationException {
- Log instance = null;
- try {
- if (logConstructor == null) {
- instance = discoverLogImplementation(name);
- }
- else {
- Object params[] = { name };
- instance = (Log) logConstructor.newInstance(params);
- }
- if (logMethod != null) {
- Object params[] = { this };
- logMethod.invoke(instance, params);
- }
- return (instance);
- } catch (LogConfigurationException lce) {
- // this type of exception means there was a problem in discovery
- // and we've already output diagnostics about the issue, etc.;
- // just pass it on
- throw (LogConfigurationException) lce;
- } catch (InvocationTargetException e) {
- // A problem occurred invoking the Constructor or Method
- // previously discovered
- Throwable c = e.getTargetException();
- if (c != null) {
- throw new LogConfigurationException(c);
- } else {
- throw new LogConfigurationException(e);
- }
- } catch (Throwable t) {
- // A problem occurred invoking the Constructor or Method
- // previously discovered
- throw new LogConfigurationException(t);
- }
- }
- // ------------------------------------------------------ Private Methods
- /**
- * Calls LogFactory.directGetContextClassLoader under the control of an
- * AccessController class. This means that java code running under a
- * security manager that forbids access to ClassLoaders will still work
- * if this class is given appropriate privileges, even when the caller
- * doesn't have such privileges. Without using an AccessController, the
- * the entire call stack must have the privilege before the call is
- * allowed.
- *
- * @return the context classloader associated with the current thread,
- * or null if security doesn't allow it.
- *
- * @throws LogConfigurationException if there was some weird error while
- * attempting to get the context classloader.
- *
- * @throws SecurityException if the current java security policy doesn't
- * allow this class to access the context classloader.
- */
- private static ClassLoader getContextClassLoaderInternal()
- throws LogConfigurationException {
- return (ClassLoader)AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return LogFactory.directGetContextClassLoader();
- }
- });
- }
- /**
- * Read the specified system property, using an AccessController so that
- * the property can be read if JCL has been granted the appropriate
- * security rights even if the calling code has not.
- *
- * Take care not to expose the value returned by this method to the
- * calling application in any way; otherwise the calling app can use that
- * info to access data that should not be available to it.
- */
- private static String getSystemProperty(final String key, final String def)
- throws SecurityException {
- return (String) AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return System.getProperty(key, def);
- }
- });
- }
- /**
- * Fetch the parent classloader of a specified classloader.
- *
- * If a SecurityException occurs, null is returned.
- *
- * Note that this method is non-static merely so logDiagnostic is available.
- */
- private ClassLoader getParentClassLoader(final ClassLoader cl) {
- try {
- return (ClassLoader)AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return cl.getParent();
- }
- });
- } catch(SecurityException ex) {
- logDiagnostic("[SECURITY] Unable to obtain parent classloader");
- return null;
- }
- }
- /**
- * Utility method to check whether a particular logging library is
- * present and available for use. Note that this does
not
- * affect the future behaviour of this class.
- */
- private boolean isLogLibraryAvailable(String name, String classname) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Checking for '" + name + "'.");
- }
- try {
- Log log = createLogFromClass(
- classname,
- this.getClass().getName(), // dummy category
- false);
- if (log == null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Did not find '" + name + "'.");
- }
- return false;
- } else {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Found '" + name + "'.");
- }
- return true;
- }
- } catch(LogConfigurationException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Logging system '" + name + "' is available but not useable.");
- }
- return false;
- }
- }
- /**
- * Attempt to find an attribute (see method setAttribute) or a
- * system property with the provided name and return its value.
- *
- * The attributes associated with this object are checked before
- * system properties in case someone has explicitly called setAttribute,
- * or a configuration property has been set in a commons-logging.properties
- * file.
- *
- * @return the value associated with the property, or null.
- */
- private String getConfigurationValue(String property) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] Trying to get configuration for item " + property);
- }
- Object valueObj = getAttribute(property);
- if (valueObj != null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] Found LogFactory attribute [" + valueObj + "] for " + property);
- }
- return valueObj.toString();
- }
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] No LogFactory attribute found for " + property);
- }
- try {
- // warning: minor security hole here, in that we potentially read a system
- // property that the caller cannot, then output it in readable form as a
- // diagnostic message. However it's only ever JCL-specific properties
- // involved here, so the harm is truly trivial.
- String value = getSystemProperty(property, null);
- if (value != null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] Found system property [" + value + "] for " + property);
- }
- return value;
- }
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] No system property found for property " + property);
- }
- } catch (SecurityException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] Security prevented reading system property " + property);
- }
- }
- if (isDiagnosticsEnabled()) {
- logDiagnostic("[ENV] No configuration defined for item " + property);
- }
- return null;
- }
- /**
- * Get the setting for the user-configurable behaviour specified by key.
- * If nothing has explicitly been set, then return dflt.
- */
- private boolean getBooleanConfiguration(String key, boolean dflt) {
- String val = getConfigurationValue(key);
- if (val == null)
- return dflt;
- return Boolean.valueOf(val).booleanValue();
- }
- /**
- * Initialize a number of variables that control the behaviour of this
- * class and that can be tweaked by the user. This is done when the first
- * logger is created, not in the constructor of this class, because we
- * need to give the user a chance to call method setAttribute in order to
- * configure this object.
- */
- private void initConfiguration() {
- allowFlawedContext = getBooleanConfiguration(ALLOW_FLAWED_CONTEXT_PROPERTY, true);
- allowFlawedDiscovery = getBooleanConfiguration(ALLOW_FLAWED_DISCOVERY_PROPERTY, true);
- allowFlawedHierarchy = getBooleanConfiguration(ALLOW_FLAWED_HIERARCHY_PROPERTY, true);
- }
- /**
- * Attempts to create a Log instance for the given category name.
- * Follows the discovery process described in the class javadoc.
- *
- * @param logCategory the name of the log category
- *
- * @throws LogConfigurationException if an error in discovery occurs,
- * or if no adapter at all can be instantiated
- */
- private Log discoverLogImplementation(String logCategory)
- throws LogConfigurationException
- {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Discovering a Log implementation...");
- }
- initConfiguration();
- Log result = null;
- // See if the user specified the Log implementation to use
- String specifiedLogClassName = findUserSpecifiedLogClassName();
- if (specifiedLogClassName != null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Attempting to load user-specified log class '" +
- specifiedLogClassName + "'...");
- }
- result = createLogFromClass(specifiedLogClassName,
- logCategory,
- true);
- if (result == null) {
- StringBuffer messageBuffer = new StringBuffer("User-specified log class '");
- messageBuffer.append(specifiedLogClassName);
- messageBuffer.append("' cannot be found or is not useable.");
- // Mistyping or misspelling names is a common fault.
- // Construct a good error message, if we can
- if (specifiedLogClassName != null) {
- informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LOG4J_LOGGER);
- informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_JDK14_LOGGER);
- informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_LUMBERJACK_LOGGER);
- informUponSimilarName(messageBuffer, specifiedLogClassName, LOGGING_IMPL_SIMPLE_LOGGER);
- }
- throw new LogConfigurationException(messageBuffer.toString());
- }
- return result;
- }
- // No user specified log; try to discover what's on the classpath
- //
- // Note that we deliberately loop here over classesToDiscover and
- // expect method createLogFromClass to loop over the possible source
- // classloaders. The effect is:
- // for each discoverable log adapter
- // for each possible classloader
- // see if it works
- //
- // It appears reasonable at first glance to do the opposite:
- // for each possible classloader
- // for each discoverable log adapter
- // see if it works
- //
- // The latter certainly has advantages for user-installable logging
- // libraries such as log4j; in a webapp for example this code should
- // first check whether the user has provided any of the possible
- // logging libraries before looking in the parent classloader.
- // Unfortunately, however, Jdk14Logger will always work in jvm>=1.4,
- // and SimpleLog will always work in any JVM. So the loop would never
- // ever look for logging libraries in the parent classpath. Yet many
- // users would expect that putting log4j there would cause it to be
- // detected (and this is the historical JCL behaviour). So we go with
- // the first approach. A user that has bundled a specific logging lib
- // in a webapp should use a commons-logging.properties file or a
- // service file in META-INF to force use of that logging lib anyway,
- // rather than relying on discovery.
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "No user-specified Log implementation; performing discovery" +
- " using the standard supported logging implementations...");
- }
- for(int i=0; (i
StringBuffer
the message should be appended to,
- * not null
- * @param name the (trimmed) name to be test against the candidate, not null
- * @param candidate the candidate name (not null)
- */
- private void informUponSimilarName(final StringBuffer messageBuffer, final String name,
- final String candidate) {
- if (name.equals(candidate)) {
- // Don't suggest a name that is exactly the same as the one the
- // user tried...
- return;
- }
- // If the user provides a name that is in the right package, and gets
- // the first 5 characters of the adapter class right (ignoring case),
- // then suggest the candidate adapter class name.
- if (name.regionMatches(true, 0, candidate, 0, PKG_LEN + 5)) {
- messageBuffer.append(" Did you mean '");
- messageBuffer.append(candidate);
- messageBuffer.append("'?");
- }
- }
- /**
- * Checks system properties and the attribute map for
- * a Log implementation specified by the user under the
- * property names {@link #LOG_PROPERTY} or {@link #LOG_PROPERTY_OLD}.
- *
- * @return classname specified by the user, or
null
- */
- private String findUserSpecifiedLogClassName()
- {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Trying to get log class from attribute '" + LOG_PROPERTY + "'");
- }
- String specifiedClass = (String) getAttribute(LOG_PROPERTY);
- if (specifiedClass == null) { // @deprecated
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Trying to get log class from attribute '" +
- LOG_PROPERTY_OLD + "'");
- }
- specifiedClass = (String) getAttribute(LOG_PROPERTY_OLD);
- }
- if (specifiedClass == null) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Trying to get log class from system property '" +
- LOG_PROPERTY + "'");
- }
- try {
- specifiedClass = getSystemProperty(LOG_PROPERTY, null);
- } catch (SecurityException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("No access allowed to system property '" +
- LOG_PROPERTY + "' - " + e.getMessage());
- }
- }
- }
- if (specifiedClass == null) { // @deprecated
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Trying to get log class from system property '" +
- LOG_PROPERTY_OLD + "'");
- }
- try {
- specifiedClass = getSystemProperty(LOG_PROPERTY_OLD, null);
- } catch (SecurityException e) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("No access allowed to system property '" +
- LOG_PROPERTY_OLD + "' - " + e.getMessage());
- }
- }
- }
- // Remove any whitespace; it's never valid in a classname so its
- // presence just means a user mistake. As we know what they meant,
- // we may as well strip the spaces.
- if (specifiedClass != null) {
- specifiedClass = specifiedClass.trim();
- }
- return specifiedClass;
- }
- /**
- * Attempts to load the given class, find a suitable constructor,
- * and instantiate an instance of Log.
- *
- * @param logAdapterClassName classname of the Log implementation
- *
- * @param logCategory argument to pass to the Log implementation's
- * constructor
- *
- * @param affectState
true
if this object's state should
- * be affected by this method call,
false
otherwise.
- *
- * @return an instance of the given class, or null if the logging
- * library associated with the specified adapter is not available.
- *
- * @throws LogConfigurationException if there was a serious error with
- * configuration and the handleFlawedDiscovery method decided this
- * problem was fatal.
- */
- private Log createLogFromClass(String logAdapterClassName,
- String logCategory,
- boolean affectState)
- throws LogConfigurationException {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Attempting to instantiate '" + logAdapterClassName + "'");
- }
- Object[] params = { logCategory };
- Log logAdapter = null;
- Constructor constructor = null;
- Class logAdapterClass = null;
- ClassLoader currentCL = getBaseClassLoader();
- for(;;) {
- // Loop through the classloader hierarchy trying to find
- // a viable classloader.
- logDiagnostic(
- "Trying to load '"
- + logAdapterClassName
- + "' from classloader "
- + objectId(currentCL));
- try {
- if (isDiagnosticsEnabled()) {
- // Show the location of the first occurrence of the .class file
- // in the classpath. This is the location that ClassLoader.loadClass
- // will load the class from -- unless the classloader is doing
- // something weird.
- URL url;
- String resourceName = logAdapterClassName.replace('.', '/') + ".class";
- if (currentCL != null) {
- url = currentCL.getResource(resourceName );
- } else {
- url = ClassLoader.getSystemResource(resourceName + ".class");
- }
- if (url == null) {
- logDiagnostic("Class '" + logAdapterClassName + "' [" + resourceName + "] cannot be found.");
- } else {
- logDiagnostic("Class '" + logAdapterClassName + "' was found at '" + url + "'");
- }
- }
- Class c = null;
- try {
- c = Class.forName(logAdapterClassName, true, currentCL);
- } catch (ClassNotFoundException originalClassNotFoundException) {
- // The current classloader was unable to find the log adapter
- // in this or any ancestor classloader. There's no point in
- // trying higher up in the hierarchy in this case..
- String msg = "" + originalClassNotFoundException.getMessage();
- logDiagnostic(
- "The log adapter '"
- + logAdapterClassName
- + "' is not available via classloader "
- + objectId(currentCL)
- + ": "
- + msg.trim());
- try {
- // Try the class classloader.
- // This may work in cases where the TCCL
- // does not contain the code executed or JCL.
- // This behaviour indicates that the application
- // classloading strategy is not consistent with the
- // Java 1.2 classloading guidelines but JCL can
- // and so should handle this case.
- c = Class.forName(logAdapterClassName);
- } catch (ClassNotFoundException secondaryClassNotFoundException) {
- // no point continuing: this adapter isn't available
- msg = "" + secondaryClassNotFoundException.getMessage();
- logDiagnostic(
- "The log adapter '"
- + logAdapterClassName
- + "' is not available via the LogFactoryImpl class classloader: "
- + msg.trim());
- break;
- }
- }
- constructor = c.getConstructor(logConstructorSignature);
- Object o = constructor.newInstance(params);
- // Note that we do this test after trying to create an instance
- // [rather than testing Log.class.isAssignableFrom(c)] so that
- // we don't complain about Log hierarchy problems when the
- // adapter couldn't be instantiated anyway.
- if (o instanceof Log) {
- logAdapterClass = c;
- logAdapter = (Log) o;
- break;
- }
- // Oops, we have a potential problem here. An adapter class
- // has been found and its underlying lib is present too, but
- // there are multiple Log interface classes available making it
- // impossible to cast to the type the caller wanted. We
- // certainly can't use this logger, but we need to know whether
- // to keep on discovering or terminate now.
- //
- // The handleFlawedHierarchy method will throw
- // LogConfigurationException if it regards this problem as
- // fatal, and just return if not.
- handleFlawedHierarchy(currentCL, c);
- } catch (NoClassDefFoundError e) {
- // We were able to load the adapter but it had references to
- // other classes that could not be found. This simply means that
- // the underlying logger library is not present in this or any
- // ancestor classloader. There's no point in trying higher up
- // in the hierarchy in this case..
- String msg = "" + e.getMessage();
- logDiagnostic(
- "The log adapter '"
- + logAdapterClassName
- + "' is missing dependencies when loaded via classloader "
- + objectId(currentCL)
- + ": "
- + msg.trim());
- break;
- } catch (ExceptionInInitializerError e) {
- // A static initializer block or the initializer code associated
- // with a static variable on the log adapter class has thrown
- // an exception.
- //
- // We treat this as meaning the adapter's underlying logging
- // library could not be found.
- String msg = "" + e.getMessage();
- logDiagnostic(
- "The log adapter '"
- + logAdapterClassName
- + "' is unable to initialize itself when loaded via classloader "
- + objectId(currentCL)
- + ": "
- + msg.trim());
- break;
- } catch(LogConfigurationException e) {
- // call to handleFlawedHierarchy above must have thrown
- // a LogConfigurationException, so just throw it on
- throw e;
- } catch(Throwable t) {
- // handleFlawedDiscovery will determine whether this is a fatal
- // problem or not. If it is fatal, then a LogConfigurationException
- // will be thrown.
- handleFlawedDiscovery(logAdapterClassName, currentCL, t);
- }
- if (currentCL == null) {
- break;
- }
- // try the parent classloader
- // currentCL = currentCL.getParent();
- currentCL = getParentClassLoader(currentCL);
- }
- if ((logAdapter != null) && affectState) {
- // We've succeeded, so set instance fields
- this.logClassName = logAdapterClassName;
- this.logConstructor = constructor;
- // Identify the
setLogFactory
method (if there is one)
- try {
- this.logMethod = logAdapterClass.getMethod("setLogFactory",
- logMethodSignature);
- logDiagnostic("Found method setLogFactory(LogFactory) in '"
- + logAdapterClassName + "'");
- } catch (Throwable t) {
- this.logMethod = null;
- logDiagnostic(
- "[INFO] '" + logAdapterClassName
- + "' from classloader " + objectId(currentCL)
- + " does not declare optional method "
- + "setLogFactory(LogFactory)");
- }
- logDiagnostic(
- "Log adapter '" + logAdapterClassName
- + "' from classloader " + objectId(logAdapterClass.getClassLoader())
- + " has been selected for use.");
- }
- return logAdapter;
- }
- /**
- * Return the classloader from which we should try to load the logging
- * adapter classes.
- *
- * This method usually returns the context classloader. However if it
- * is discovered that the classloader which loaded this class is a child
- * of the context classloader
and
the allowFlawedContext option
- * has been set then the classloader which loaded this class is returned
- * instead.
- *
- * The only time when the classloader which loaded this class is a
- * descendant (rather than the same as or an ancestor of the context
- * classloader) is when an app has created custom classloaders but
- * failed to correctly set the context classloader. This is a bug in
- * the calling application; however we provide the option for JCL to
- * simply generate a warning rather than fail outright.
- *
- */
- private ClassLoader getBaseClassLoader() throws LogConfigurationException {
- ClassLoader thisClassLoader = getClassLoader(LogFactoryImpl.class);
- if (useTCCL == false) {
- return thisClassLoader;
- }
- ClassLoader contextClassLoader = getContextClassLoaderInternal();
- ClassLoader baseClassLoader = getLowestClassLoader(
- contextClassLoader, thisClassLoader);
- if (baseClassLoader == null) {
- // The two classloaders are not part of a parent child relationship.
- // In some classloading setups (e.g. JBoss with its
- // UnifiedLoaderRepository) this can still work, so if user hasn't
- // forbidden it, just return the contextClassLoader.
- if (allowFlawedContext) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "[WARNING] the context classloader is not part of a"
- + " parent-child relationship with the classloader that"
- + " loaded LogFactoryImpl.");
- }
- // If contextClassLoader were null, getLowestClassLoader() would
- // have returned thisClassLoader. The fact we are here means
- // contextClassLoader is not null, so we can just return it.
- return contextClassLoader;
- }
- else {
- throw new LogConfigurationException(
- "Bad classloader hierarchy; LogFactoryImpl was loaded via"
- + " a classloader that is not related to the current context"
- + " classloader.");
- }
- }
- if (baseClassLoader != contextClassLoader) {
- // We really should just use the contextClassLoader as the starting
- // point for scanning for log adapter classes. However it is expected
- // that there are a number of broken systems out there which create
- // custom classloaders but fail to set the context classloader so
- // we handle those flawed systems anyway.
- if (allowFlawedContext) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic(
- "Warning: the context classloader is an ancestor of the"
- + " classloader that loaded LogFactoryImpl; it should be"
- + " the same or a descendant. The application using"
- + " commons-logging should ensure the context classloader"
- + " is used correctly.");
- }
- } else {
- throw new LogConfigurationException(
- "Bad classloader hierarchy; LogFactoryImpl was loaded via"
- + " a classloader that is not related to the current context"
- + " classloader.");
- }
- }
- return baseClassLoader;
- }
- /**
- * Given two related classloaders, return the one which is a child of
- * the other.
- *
- * @param c1 is a classloader (including the null classloader)
- * @param c2 is a classloader (including the null classloader)
- *
- * @return c1 if it has c2 as an ancestor, c2 if it has c1 as an ancestor,
- * and null if neither is an ancestor of the other.
- */
- private ClassLoader getLowestClassLoader(ClassLoader c1, ClassLoader c2) {
- // TODO: use AccessController when dealing with classloaders here
- if (c1 == null)
- return c2;
- if (c2 == null)
- return c1;
- ClassLoader current;
- // scan c1's ancestors to find c2
- current = c1;
- while (current != null) {
- if (current == c2)
- return c1;
- current = current.getParent();
- }
- // scan c2's ancestors to find c1
- current = c2;
- while (current != null) {
- if (current == c1)
- return c2;
- current = current.getParent();
- }
- return null;
- }
- /**
- * Generates an internal diagnostic logging of the discovery failure and
- * then throws a
LogConfigurationException
that wraps
- * the passed
Throwable
.
- *
- * @param logAdapterClassName is the class name of the Log implementation
- * that could not be instantiated. Cannot be
null
.
- *
- * @param classLoader is the classloader that we were trying to load the
- * logAdapterClassName from when the exception occurred.
- *
- * @param discoveryFlaw is the Throwable created by the classloader
- *
- * @throws LogConfigurationException ALWAYS
- */
- private void handleFlawedDiscovery(String logAdapterClassName,
- ClassLoader classLoader,
- Throwable discoveryFlaw) {
- if (isDiagnosticsEnabled()) {
- logDiagnostic("Could not instantiate Log '"
- + logAdapterClassName + "' -- "
- + discoveryFlaw.getClass().getName() + ": "
- + discoveryFlaw.getLocalizedMessage());
- if (discoveryFlaw instanceof InvocationTargetException ) {
- // Ok, the lib is there but while trying to create a real underlying
- // logger something failed in the underlying lib; display info about
- // that if possible.
- InvocationTargetException ite = (InvocationTargetException)discoveryFlaw;
- Throwable cause = ite.getTargetException();
- if (cause != null) {
- logDiagnostic("... InvocationTargetException: " +
- cause.getClass().getName() + ": " +
- cause.getLocalizedMessage());
- if (cause instanceof ExceptionInInitializerError) {
- ExceptionInInitializerError eiie = (ExceptionInInitializerError)cause;
- Throwable cause2 = eiie.getException();
- if (cause2 != null) {
- logDiagnostic("... ExceptionInInitializerError: " +
- cause2.getClass().getName() + ": " +
- cause2.getLocalizedMessage());
- }
- }
- }
- }
- }
- if (!allowFlawedDiscovery) {
- throw new LogConfigurationException(discoveryFlaw);
- }
- }
- /**
- * Report a problem loading the log adapter, then either return
- * (if the situation is considered recoverable) or throw a
- * LogConfigurationException.
- *
- * There are two possible reasons why we successfully loaded the
- * specified log adapter class then failed to cast it to a Log object:
- *
- *
-
the specific class just doesn't implement the Log interface
- * (user screwed up), or
- *
-
the specified class has bound to a Log class loaded by some other
- * classloader; Log@classloaderX cannot be cast to Log@classloaderY.
- *
- *
- * Here we try to figure out which case has occurred so we can give the
- * user some reasonable feedback.
- *
- * @param badClassLoader is the classloader we loaded the problem class from,
- * ie it is equivalent to badClass.getClassLoader().
- *
- * @param badClass is a Class object with the desired name, but which
- * does not implement Log correctly.
- *
- * @throws LogConfigurationException when the situation
- * should not be recovered from.
- */
- private void handleFlawedHierarchy(ClassLoader badClassLoader, Class badClass)
- throws LogConfigurationException {
- boolean implementsLog = false;
- String logInterfaceName = Log.class.getName();
- Class interfaces[] = badClass.getInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- if (logInterfaceName.equals(interfaces[i].getName())) {
- implementsLog = true;
- break;
- }
- }
- if (implementsLog) {
- // the class does implement an interface called Log, but
- // it is in the wrong classloader
- if (isDiagnosticsEnabled()) {
- try {
- ClassLoader logInterfaceClassLoader = getClassLoader(Log.class);
- logDiagnostic(
- "Class '" + badClass.getName()
- + "' was found in classloader "
- + objectId(badClassLoader)
- + ". It is bound to a Log interface which is not"
- + " the one loaded from classloader "
- + objectId(logInterfaceClassLoader));
- } catch (Throwable t) {
- logDiagnostic(
- "Error while trying to output diagnostics about"
- + " bad class '" + badClass + "'");
- }
- }
- if (!allowFlawedHierarchy) {
- StringBuffer msg = new StringBuffer();
- msg.append("Terminating logging for this context ");
- msg.append("due to bad log hierarchy. ");
- msg.append("You have more than one version of '");
- msg.append(Log.class.getName());
- msg.append("' visible.");
- if (isDiagnosticsEnabled()) {
- logDiagnostic(msg.toString());
- }
- throw new LogConfigurationException(msg.toString());
- }
- if (isDiagnosticsEnabled()) {
- StringBuffer msg = new StringBuffer();
- msg.append("Warning: bad log hierarchy. ");
- msg.append("You have more than one version of '");
- msg.append(Log.class.getName());
- msg.append("' visible.");
- logDiagnostic(msg.toString());
- }
- } else {
- // this is just a bad adapter class
- if (!allowFlawedDiscovery) {
- StringBuffer msg = new StringBuffer();
- msg.append("Terminating logging for this context. ");
- msg.append("Log class '");
- msg.append(badClass.getName());
- msg.append("' does not implement the Log interface.");
- if (isDiagnosticsEnabled()) {
- logDiagnostic(msg.toString());
- }
- throw new LogConfigurationException(msg.toString());
- }
- if (isDiagnosticsEnabled()) {
- StringBuffer msg = new StringBuffer();
- msg.append("[WARNING] Log class '");
- msg.append(badClass.getName());
- msg.append("' does not implement the Log interface.");
- logDiagnostic(msg.toString());
- }
- }
- }
diff --git a/clients/java/src/org/apache/commons/logging/impl/NoOpLog.java b/clients/java/src/org/apache/commons/logging/impl/NoOpLog.java
deleted file mode 100644
index a66bd10..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/NoOpLog.java
+++ /dev/null
@@ -1,107 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import java.io.Serializable;
-import org.apache.commons.logging.Log;
- *
Trivial implementation of Log that throws away all messages. No
- * configurable system properties are supported.
- * @author
Scott Sanders
- * @author Rod Waldhoff
- * @version $Id: NoOpLog.java 424107 2006-07-20 23:15:42Z skitching $
-public class NoOpLog implements Log, Serializable {
- /** Convenience constructor */
- public NoOpLog() { }
- /** Base constructor */
- public NoOpLog(String name) { }
- /** Do nothing */
- public void trace(Object message) { }
- /** Do nothing */
- public void trace(Object message, Throwable t) { }
- /** Do nothing */
- public void debug(Object message) { }
- /** Do nothing */
- public void debug(Object message, Throwable t) { }
- /** Do nothing */
- public void info(Object message) { }
- /** Do nothing */
- public void info(Object message, Throwable t) { }
- /** Do nothing */
- public void warn(Object message) { }
- /** Do nothing */
- public void warn(Object message, Throwable t) { }
- /** Do nothing */
- public void error(Object message) { }
- /** Do nothing */
- public void error(Object message, Throwable t) { }
- /** Do nothing */
- public void fatal(Object message) { }
- /** Do nothing */
- public void fatal(Object message, Throwable t) { }
- /**
- * Debug is never enabled.
- *
- * @return false
- */
- public final boolean isDebugEnabled() { return false; }
- /**
- * Error is never enabled.
- *
- * @return false
- */
- public final boolean isErrorEnabled() { return false; }
- /**
- * Fatal is never enabled.
- *
- * @return false
- */
- public final boolean isFatalEnabled() { return false; }
- /**
- * Info is never enabled.
- *
- * @return false
- */
- public final boolean isInfoEnabled() { return false; }
- /**
- * Trace is never enabled.
- *
- * @return false
- */
- public final boolean isTraceEnabled() { return false; }
- /**
- * Warn is never enabled.
- *
- * @return false
- */
- public final boolean isWarnEnabled() { return false; }
diff --git a/clients/java/src/org/apache/commons/logging/impl/SimpleLog.java b/clients/java/src/org/apache/commons/logging/impl/SimpleLog.java
deleted file mode 100644
index fe1a7c5..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/SimpleLog.java
+++ /dev/null
@@ -1,721 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Properties;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogConfigurationException;
- *
Simple implementation of Log that sends all enabled log messages,
- * for all defined loggers, to System.err. The following system properties
- * are supported to configure the behavior of this logger:
- *
-
org.apache.commons.logging.simplelog.defaultlog
-
- * Default logging detail level for all instances of SimpleLog.
- * Must be one of ("trace", "debug", "info", "warn", "error", or "fatal").
- * If not specified, defaults to "info".
- *
-
org.apache.commons.logging.simplelog.log.xxxxx
-
- * Logging detail level for a SimpleLog instance named "xxxxx".
- * Must be one of ("trace", "debug", "info", "warn", "error", or "fatal").
- * If not specified, the default logging detail level is used.
- *
-
org.apache.commons.logging.simplelog.showlogname
-
- * Set to
true
if you want the Log instance name to be
- * included in output messages. Defaults to
false
.
- *
-
org.apache.commons.logging.simplelog.showShortLogname
-
- * Set to
true
if you want the last component of the name to be
- * included in output messages. Defaults to
true
.
- *
-
org.apache.commons.logging.simplelog.showdatetime
-
- * Set to
true
if you want the current date and time
- * to be included in output messages. Default is
false
.
- *
-
org.apache.commons.logging.simplelog.dateTimeFormat
-
- * The date and time format to be used in the output messages.
- * The pattern describing the date and time format is the same that is
- * used in
java.text.SimpleDateFormat
. If the format is not
- * specified or is invalid, the default format is used.
- * The default format is
yyyy/MM/dd HH:mm:ss:SSS zzz
.
- *
In addition to looking for system properties with the names specified
- * above, this implementation also checks for a class loader resource named
- *
"simplelog.properties"
, and includes any matching definitions
- * from this resource (if it exists).
- * @author
Scott Sanders
- * @author Rod Waldhoff
- * @author Robert Burrell Donkin
- * @version $Id: SimpleLog.java 581090 2007-10-01 22:01:06Z dennisl $
-public class SimpleLog implements Log, Serializable {
- // ------------------------------------------------------- Class Attributes
- /** All system properties used by
SimpleLog
start with this */
- static protected final String systemPrefix =
- "org.apache.commons.logging.simplelog.";
- /** Properties loaded from simplelog.properties */
- static protected final Properties simpleLogProps = new Properties();
- /** The default format to use when formating dates */
- static protected final String DEFAULT_DATE_TIME_FORMAT =
- "yyyy/MM/dd HH:mm:ss:SSS zzz";
- /** Include the instance name in the log message? */
- static protected boolean showLogName = false;
- /** Include the short name ( last component ) of the logger in the log
- * message. Defaults to true - otherwise we'll be lost in a flood of
- * messages without knowing who sends them.
- */
- static protected boolean showShortName = true;
- /** Include the current time in the log message */
- static protected boolean showDateTime = false;
- /** The date and time format to use in the log message */
- static protected String dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
- /**
- * Used to format times.
- *
- * Any code that accesses this object should first obtain a lock on it,
- * ie use synchronized(dateFormatter); this requirement was introduced
- * in 1.1.1 to fix an existing thread safety bug (SimpleDateFormat.format
- * is not thread-safe).
- */
- static protected DateFormat dateFormatter = null;
- // ---------------------------------------------------- Log Level Constants
- /** "Trace" level logging. */
- public static final int LOG_LEVEL_TRACE = 1;
- /** "Debug" level logging. */
- public static final int LOG_LEVEL_DEBUG = 2;
- /** "Info" level logging. */
- public static final int LOG_LEVEL_INFO = 3;
- /** "Warn" level logging. */
- public static final int LOG_LEVEL_WARN = 4;
- /** "Error" level logging. */
- public static final int LOG_LEVEL_ERROR = 5;
- /** "Fatal" level logging. */
- public static final int LOG_LEVEL_FATAL = 6;
- /** Enable all logging levels */
- public static final int LOG_LEVEL_ALL = (LOG_LEVEL_TRACE - 1);
- /** Enable no logging levels */
- public static final int LOG_LEVEL_OFF = (LOG_LEVEL_FATAL + 1);
- // ------------------------------------------------------------ Initializer
- private static String getStringProperty(String name) {
- String prop = null;
- try {
- prop = System.getProperty(name);
- } catch (SecurityException e) {
- ; // Ignore
- }
- return (prop == null) ? simpleLogProps.getProperty(name) : prop;
- }
- private static String getStringProperty(String name, String dephault) {
- String prop = getStringProperty(name);
- return (prop == null) ? dephault : prop;
- }
- private static boolean getBooleanProperty(String name, boolean dephault) {
- String prop = getStringProperty(name);
- return (prop == null) ? dephault : "true".equalsIgnoreCase(prop);
- }
- // Initialize class attributes.
- // Load properties file, if found.
- // Override with system properties.
- static {
- // Add props from the resource simplelog.properties
- InputStream in = getResourceAsStream("simplelog.properties");
- if(null != in) {
- try {
- simpleLogProps.load(in);
- in.close();
- } catch(java.io.IOException e) {
- // ignored
- }
- }
- showLogName = getBooleanProperty( systemPrefix + "showlogname", showLogName);
- showShortName = getBooleanProperty( systemPrefix + "showShortLogname", showShortName);
- showDateTime = getBooleanProperty( systemPrefix + "showdatetime", showDateTime);
- if(showDateTime) {
- dateTimeFormat = getStringProperty(systemPrefix + "dateTimeFormat",
- dateTimeFormat);
- try {
- dateFormatter = new SimpleDateFormat(dateTimeFormat);
- } catch(IllegalArgumentException e) {
- // If the format pattern is invalid - use the default format
- dateTimeFormat = DEFAULT_DATE_TIME_FORMAT;
- dateFormatter = new SimpleDateFormat(dateTimeFormat);
- }
- }
- }
- // ------------------------------------------------------------- Attributes
- /** The name of this simple log instance */
- protected String logName = null;
- /** The current log level */
- protected int currentLogLevel;
- /** The short name of this simple log instance */
- private String shortLogName = null;
- // ------------------------------------------------------------ Constructor
- /**
- * Construct a simple log with given name.
- *
- * @param name log name
- */
- public SimpleLog(String name) {
- logName = name;
- // Set initial log level
- // Used to be: set default log level to ERROR
- // IMHO it should be lower, but at least info ( costin ).
- setLevel(SimpleLog.LOG_LEVEL_INFO);
- // Set log level from properties
- String lvl = getStringProperty(systemPrefix + "log." + logName);
- int i = String.valueOf(name).lastIndexOf(".");
- while(null == lvl && i > -1) {
- name = name.substring(0,i);
- lvl = getStringProperty(systemPrefix + "log." + name);
- i = String.valueOf(name).lastIndexOf(".");
- }
- if(null == lvl) {
- lvl = getStringProperty(systemPrefix + "defaultlog");
- }
- if("all".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_ALL);
- } else if("trace".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_TRACE);
- } else if("debug".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_DEBUG);
- } else if("info".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_INFO);
- } else if("warn".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_WARN);
- } else if("error".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_ERROR);
- } else if("fatal".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_FATAL);
- } else if("off".equalsIgnoreCase(lvl)) {
- setLevel(SimpleLog.LOG_LEVEL_OFF);
- }
- }
- // -------------------------------------------------------- Properties
- /**
- *
Set logging level.
- *
- * @param currentLogLevel new logging level
- */
- public void setLevel(int currentLogLevel) {
- this.currentLogLevel = currentLogLevel;
- }
- /**
- *
Get logging level.
- */
- public int getLevel() {
- return currentLogLevel;
- }
- // -------------------------------------------------------- Logging Methods
- /**
- *
Do the actual logging.
- * This method assembles the message
- * and then calls
write()
to cause it to be written.
- *
- * @param type One of the LOG_LEVEL_XXX constants defining the log level
- * @param message The message itself (typically a String)
- * @param t The exception whose stack trace should be logged
- */
- protected void log(int type, Object message, Throwable t) {
- // Use a string buffer for better performance
- StringBuffer buf = new StringBuffer();
- // Append date-time if so configured
- if(showDateTime) {
- Date now = new Date();
- String dateText;
- synchronized(dateFormatter) {
- dateText = dateFormatter.format(now);
- }
- buf.append(dateText);
- buf.append(" ");
- }
- // Append a readable representation of the log level
- switch(type) {
- case SimpleLog.LOG_LEVEL_TRACE: buf.append("[TRACE] "); break;
- case SimpleLog.LOG_LEVEL_DEBUG: buf.append("[DEBUG] "); break;
- case SimpleLog.LOG_LEVEL_INFO: buf.append("[INFO] "); break;
- case SimpleLog.LOG_LEVEL_WARN: buf.append("[WARN] "); break;
- case SimpleLog.LOG_LEVEL_ERROR: buf.append("[ERROR] "); break;
- case SimpleLog.LOG_LEVEL_FATAL: buf.append("[FATAL] "); break;
- }
- // Append the name of the log instance if so configured
- if( showShortName) {
- if( shortLogName==null ) {
- // Cut all but the last component of the name for both styles
- shortLogName = logName.substring(logName.lastIndexOf(".") + 1);
- shortLogName =
- shortLogName.substring(shortLogName.lastIndexOf("/") + 1);
- }
- buf.append(String.valueOf(shortLogName)).append(" - ");
- } else if(showLogName) {
- buf.append(String.valueOf(logName)).append(" - ");
- }
- // Append the message
- buf.append(String.valueOf(message));
- // Append stack trace if not null
- if(t != null) {
- buf.append(" ");
- java.io.StringWriter sw= new java.io.StringWriter(1024);
- java.io.PrintWriter pw= new java.io.PrintWriter(sw);
- t.printStackTrace(pw);
- pw.close();
- buf.append(sw.toString());
- }
- // Print to the appropriate destination
- write(buf);
- }
- /**
- *
Write the content of the message accumulated in the specified
- *
StringBuffer
to the appropriate output destination. The
- * default implementation writes to
System.err
.
- *
- * @param buffer A
StringBuffer
containing the accumulated
- * text to be logged
- */
- protected void write(StringBuffer buffer) {
- System.err.println(buffer.toString());
- }
- /**
- * Is the given log level currently enabled?
- *
- * @param logLevel is this level enabled?
- */
- protected boolean isLevelEnabled(int logLevel) {
- // log level are numerically ordered so can use simple numeric
- // comparison
- return (logLevel >= currentLogLevel);
- }
- // -------------------------------------------------------- Log Implementation
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_DEBUG
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#debug(Object)
- */
- public final void debug(Object message) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
- log(SimpleLog.LOG_LEVEL_DEBUG, message, null);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_DEBUG
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#debug(Object, Throwable)
- */
- public final void debug(Object message, Throwable t) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG)) {
- log(SimpleLog.LOG_LEVEL_DEBUG, message, t);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_TRACE
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#trace(Object)
- */
- public final void trace(Object message) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
- log(SimpleLog.LOG_LEVEL_TRACE, message, null);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_TRACE
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#trace(Object, Throwable)
- */
- public final void trace(Object message, Throwable t) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE)) {
- log(SimpleLog.LOG_LEVEL_TRACE, message, t);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#info(Object)
- */
- public final void info(Object message) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
- log(SimpleLog.LOG_LEVEL_INFO,message,null);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_INFO
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#info(Object, Throwable)
- */
- public final void info(Object message, Throwable t) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_INFO)) {
- log(SimpleLog.LOG_LEVEL_INFO, message, t);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_WARN
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#warn(Object)
- */
- public final void warn(Object message) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
- log(SimpleLog.LOG_LEVEL_WARN, message, null);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_WARN
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#warn(Object, Throwable)
- */
- public final void warn(Object message, Throwable t) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_WARN)) {
- log(SimpleLog.LOG_LEVEL_WARN, message, t);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_ERROR
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#error(Object)
- */
- public final void error(Object message) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
- log(SimpleLog.LOG_LEVEL_ERROR, message, null);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_ERROR
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#error(Object, Throwable)
- */
- public final void error(Object message, Throwable t) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR)) {
- log(SimpleLog.LOG_LEVEL_ERROR, message, t);
- }
- }
- /**
- * Log a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_FATAL
.
- *
- * @param message to log
- * @see org.apache.commons.logging.Log#fatal(Object)
- */
- public final void fatal(Object message) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
- log(SimpleLog.LOG_LEVEL_FATAL, message, null);
- }
- }
- /**
- * Logs a message with
- *
org.apache.commons.logging.impl.SimpleLog.LOG_LEVEL_FATAL
.
- *
- * @param message to log
- * @param t log this cause
- * @see org.apache.commons.logging.Log#fatal(Object, Throwable)
- */
- public final void fatal(Object message, Throwable t) {
- if (isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL)) {
- log(SimpleLog.LOG_LEVEL_FATAL, message, t);
- }
- }
- /**
- *
Are debug messages currently enabled?
- *
- *
This allows expensive operations such as
String
- * concatenation to be avoided when the message will be ignored by the
- * logger.
- */
- public final boolean isDebugEnabled() {
- return isLevelEnabled(SimpleLog.LOG_LEVEL_DEBUG);
- }
- /**
- *
Are error messages currently enabled?
- *
- *
This allows expensive operations such as
String
- * concatenation to be avoided when the message will be ignored by the
- * logger.
- */
- public final boolean isErrorEnabled() {
- return isLevelEnabled(SimpleLog.LOG_LEVEL_ERROR);
- }
- /**
- *
Are fatal messages currently enabled?
- *
- *
This allows expensive operations such as
String
- * concatenation to be avoided when the message will be ignored by the
- * logger.
- */
- public final boolean isFatalEnabled() {
- return isLevelEnabled(SimpleLog.LOG_LEVEL_FATAL);
- }
- /**
- *
Are info messages currently enabled?
- *
- *
This allows expensive operations such as
String
- * concatenation to be avoided when the message will be ignored by the
- * logger.
- */
- public final boolean isInfoEnabled() {
- return isLevelEnabled(SimpleLog.LOG_LEVEL_INFO);
- }
- /**
- *
Are trace messages currently enabled?
- *
- *
This allows expensive operations such as
String
- * concatenation to be avoided when the message will be ignored by the
- * logger.
- */
- public final boolean isTraceEnabled() {
- return isLevelEnabled(SimpleLog.LOG_LEVEL_TRACE);
- }
- /**
- *
Are warn messages currently enabled?
- *
- *
This allows expensive operations such as
String
- * concatenation to be avoided when the message will be ignored by the
- * logger.
- */
- public final boolean isWarnEnabled() {
- return isLevelEnabled(SimpleLog.LOG_LEVEL_WARN);
- }
- /**
- * Return the thread context class loader if available.
- * Otherwise return null.
- *
- * The thread context class loader is available for JDK 1.2
- * or later, if certain security conditions are met.
- *
- * @exception LogConfigurationException if a suitable class loader
- * cannot be identified.
- */
- private static ClassLoader getContextClassLoader()
- {
- ClassLoader classLoader = null;
- if (classLoader == null) {
- try {
- // Are we running on a JDK 1.2 or later system?
- Method method = Thread.class.getMethod("getContextClassLoader",
- (Class[]) null);
- // Get the thread context class loader (if there is one)
- try {
- classLoader = (ClassLoader)method.invoke(Thread.currentThread(),
- (Class[]) null);
- } catch (IllegalAccessException e) {
- ; // ignore
- } catch (InvocationTargetException e) {
- /**
- * InvocationTargetException is thrown by 'invoke' when
- * the method being invoked (getContextClassLoader) throws
- * an exception.
- *
- * getContextClassLoader() throws SecurityException when
- * the context class loader isn't an ancestor of the
- * calling class's class loader, or if security
- * permissions are restricted.
- *
- * In the first case (not related), we want to ignore and
- * keep going. We cannot help but also ignore the second
- * with the logic below, but other calls elsewhere (to
- * obtain a class loader) will trigger this exception where
- * we can make a distinction.
- */
- if (e.getTargetException() instanceof SecurityException) {
- ; // ignore
- } else {
- // Capture 'e.getTargetException()' exception for details
- // alternate: log 'e.getTargetException()', and pass back 'e'.
- throw new LogConfigurationException
- ("Unexpected InvocationTargetException", e.getTargetException());
- }
- }
- } catch (NoSuchMethodException e) {
- // Assume we are running on JDK 1.1
- ; // ignore
- }
- }
- if (classLoader == null) {
- classLoader = SimpleLog.class.getClassLoader();
- }
- // Return the selected class loader
- return classLoader;
- }
- private static InputStream getResourceAsStream(final String name)
- {
- return (InputStream)AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- ClassLoader threadCL = getContextClassLoader();
- if (threadCL != null) {
- return threadCL.getResourceAsStream(name);
- } else {
- return ClassLoader.getSystemResourceAsStream(name);
- }
- }
- });
- }
diff --git a/clients/java/src/org/apache/commons/logging/impl/WeakHashtable.java b/clients/java/src/org/apache/commons/logging/impl/WeakHashtable.java
deleted file mode 100644
index 3748ceb..0000000
--- a/clients/java/src/org/apache/commons/logging/impl/WeakHashtable.java
+++ /dev/null
@@ -1,478 +0,0 @@
- * 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.
-package org.apache.commons.logging.impl;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-import java.util.*;
- *
Implementation of
Hashtable
that uses
WeakReference
's
- * to hold its keys thus allowing them to be reclaimed by the garbage collector.
- * The associated values are retained using strong references.
- *
This class follows the symantics of
Hashtable
as closely as
- * possible. It therefore does not accept null values or keys.
- *
Note:
- * This is
not
intended to be a general purpose hash table replacement.
- * This implementation is also tuned towards a particular purpose: for use as a replacement
- * for
Hashtable
in
LogFactory
. This application requires
- * good liveliness for
get
and
put
. Various tradeoffs
- * have been made with this in mind.
- *
Usage:
typical use case is as a drop-in replacement
- * for the
Hashtable
used in
LogFactory
for J2EE enviroments
- * running 1.3+ JVMs. Use of this class
in most cases
(see below) will
- * allow classloaders to be collected by the garbage collector without the need
- * to call {@link org.apache.commons.logging.LogFactory#release(ClassLoader) LogFactory.release(ClassLoader)}.
- *
org.apache.commons.logging.LogFactory
checks whether this class
- * can be supported by the current JVM, and if so then uses it to store
- * references to the
LogFactory
implementationd it loads
- * (rather than using a standard Hashtable instance).
- * Having this class used instead of
Hashtable
solves
- * certain issues related to dynamic reloading of applications in J2EE-style
- * environments. However this class requires java 1.3 or later (due to its use
- * of
java.lang.ref.WeakReference
and associates).
- * And by the way, this extends
Hashtable
rather than
HashMap
- * for backwards compatibility reasons. See the documentation
- * for method
LogFactory.createFactoryStore
for more details.
- *
The reason all this is necessary is due to a issue which
- * arises during hot deploy in a J2EE-like containers.
- * Each component running in the container owns one or more classloaders; when
- * the component loads a LogFactory instance via the component classloader
- * a reference to it gets stored in the static LogFactory.factories member,
- * keyed by the component's classloader so different components don't
- * stomp on each other. When the component is later unloaded, the container
- * sets the component's classloader to null with the intent that all the
- * component's classes get garbage-collected. However there's still a
- * reference to the component's classloader from a key in the "global"
- *
LogFactory
's factories member! If
LogFactory.release()
- * is called whenever component is unloaded, the classloaders will be correctly
- * garbage collected; this
should
be done by any container that
- * bundles commons-logging by default. However, holding the classloader
- * references weakly ensures that the classloader will be garbage collected
- * without the container performing this step.
- *
Limitations:
- * There is still one (unusual) scenario in which a component will not
- * be correctly unloaded without an explicit release. Though weak references
- * are used for its keys, it is necessary to use strong references for its values.
- *
If the abstract class
LogFactory
is
- * loaded by the container classloader but a subclass of
- *
LogFactory
[LogFactory1] is loaded by the component's
- * classloader and an instance stored in the static map associated with the
- * base LogFactory class, then there is a strong reference from the LogFactory
- * class to the LogFactory1 instance (as normal) and a strong reference from
- * the LogFactory1 instance to the component classloader via
- *
getClass().getClassLoader()
. This chain of references will prevent
- * collection of the child classloader.
- * Such a situation occurs when the commons-logging.jar is
- * loaded by a parent classloader (e.g. a server level classloader in a
- * servlet container) and a custom
LogFactory
implementation is
- * loaded by a child classloader (e.g. a web app classloader).
- *
To avoid this scenario, ensure
- * that any custom LogFactory subclass is loaded by the same classloader as
- * the base
LogFactory
. Creating custom LogFactory subclasses is,
- * however, rare. The standard LogFactoryImpl class should be sufficient
- * for most or all users.
- * @author Brian Stansberry
- * @since 1.1
-public final class WeakHashtable extends Hashtable {
- /**
- * The maximum number of times put() or remove() can be called before
- * the map will be purged of all cleared entries.
- */
- private static final int MAX_CHANGES_BEFORE_PURGE = 100;
- /**
- * The maximum number of times put() or remove() can be called before
- * the map will be purged of one cleared entry.
- */
- private static final int PARTIAL_PURGE_COUNT = 10;
- /* ReferenceQueue we check for gc'd keys */
- private ReferenceQueue queue = new ReferenceQueue();
- /* Counter used to control how often we purge gc'd entries */
- private int changeCount = 0;
- /**
- * Constructs a WeakHashtable with the Hashtable default
- * capacity and load factor.
- */
- public WeakHashtable() {}
- /**
- *@see Hashtable
- */
- public boolean containsKey(Object key) {
- // purge should not be required
- Referenced referenced = new Referenced(key);
- return super.containsKey(referenced);
- }
- /**
- *@see Hashtable
- */
- public Enumeration elements() {
- purge();
- return super.elements();
- }
- /**
- *@see Hashtable
- */
- public Set entrySet() {
- purge();
- Set referencedEntries = super.entrySet();
- Set unreferencedEntries = new HashSet();
- for (Iterator it=referencedEntries.iterator(); it.hasNext();) {
- Map.Entry entry = (Map.Entry) it.next();
- Referenced referencedKey = (Referenced) entry.getKey();
- Object key = referencedKey.getValue();
- Object value = entry.getValue();
- if (key != null) {
- Entry dereferencedEntry = new Entry(key, value);
- unreferencedEntries.add(dereferencedEntry);
- }
- }
- return unreferencedEntries;
- }
- /**
- *@see Hashtable
- */
- public Object get(Object key) {
- // for performance reasons, no purge
- Referenced referenceKey = new Referenced(key);
- return super.get(referenceKey);
- }
- /**
- *@see Hashtable
- */
- public Enumeration keys() {
- purge();
- final Enumeration enumer = super.keys();
- return new Enumeration() {
- public boolean hasMoreElements() {
- return enumer.hasMoreElements();
- }
- public Object nextElement() {
- Referenced nextReference = (Referenced) enumer.nextElement();
- return nextReference.getValue();
- }
- };
- }
- /**
- *@see Hashtable
- */
- public Set keySet() {
- purge();
- Set referencedKeys = super.keySet();
- Set unreferencedKeys = new HashSet();
- for (Iterator it=referencedKeys.iterator(); it.hasNext();) {
- Referenced referenceKey = (Referenced) it.next();
- Object keyValue = referenceKey.getValue();
- if (keyValue != null) {
- unreferencedKeys.add(keyValue);
- }
- }
- return unreferencedKeys;
- }
- /**
- *@see Hashtable
- */
- public Object put(Object key, Object value) {
- // check for nulls, ensuring symantics match superclass
- if (key == null) {
- throw new NullPointerException("Null keys are not allowed");
- }
- if (value == null) {
- throw new NullPointerException("Null values are not allowed");
- }
- // for performance reasons, only purge every
- // MAX_CHANGES_BEFORE_PURGE times
- if (changeCount++ > MAX_CHANGES_BEFORE_PURGE) {
- purge();
- changeCount = 0;
- }
- // do a partial purge more often
- else if ((changeCount % PARTIAL_PURGE_COUNT) == 0) {
- purgeOne();
- }
- Referenced keyRef = new Referenced(key, queue);
- return super.put(keyRef, value);
- }
- /**
- *@see Hashtable
- */
- public void putAll(Map t) {
- if (t != null) {
- Set entrySet = t.entrySet();
- for (Iterator it=entrySet.iterator(); it.hasNext();) {
- Map.Entry entry = (Map.Entry) it.next();
- put(entry.getKey(), entry.getValue());
- }
- }
- }
- /**
- *@see Hashtable
- */
- public Collection values() {
- purge();
- return super.values();
- }
- /**
- *@see Hashtable
- */
- public Object remove(Object key) {
- // for performance reasons, only purge every
- // MAX_CHANGES_BEFORE_PURGE times
- if (changeCount++ > MAX_CHANGES_BEFORE_PURGE) {
- purge();
- changeCount = 0;
- }
- // do a partial purge more often
- else if ((changeCount % PARTIAL_PURGE_COUNT) == 0) {
- purgeOne();
- }
- return super.remove(new Referenced(key));
- }
- /**
- *@see Hashtable
- */
- public boolean isEmpty() {
- purge();
- return super.isEmpty();
- }
- /**
- *@see Hashtable
- */
- public int size() {
- purge();
- return super.size();
- }
- /**
- *@see Hashtable
- */
- public String toString() {
- purge();
- return super.toString();
- }
- /**
- * @see Hashtable
- */
- protected void rehash() {
- // purge here to save the effort of rehashing dead entries
- purge();
- super.rehash();
- }
- /**
- * Purges all entries whose wrapped keys
- * have been garbage collected.
- */
- private void purge() {
- synchronized (queue) {
- WeakKey key;
- while ((key = (WeakKey) queue.poll()) != null) {
- super.remove(key.getReferenced());
- }
- }
- }
- /**
- * Purges one entry whose wrapped key
- * has been garbage collected.
- */
- private void purgeOne() {
- synchronized (queue) {
- WeakKey key = (WeakKey) queue.poll();
- if (key != null) {
- super.remove(key.getReferenced());
- }
- }
- }
- /** Entry implementation */
- private final static class Entry implements Map.Entry {
- private final Object key;
- private final Object value;
- private Entry(Object key, Object value) {
- this.key = key;
- this.value = value;
- }
- public boolean equals(Object o) {
- boolean result = false;
- if (o != null && o instanceof Map.Entry) {
- Map.Entry entry = (Map.Entry) o;
- result = (getKey()==null ?
- entry.getKey() == null :
- getKey().equals(entry.getKey()))
- (getValue()==null ?
- entry.getValue() == null :
- getValue().equals(entry.getValue()));
- }
- return result;
- }
- public int hashCode() {
- return (getKey()==null ? 0 : getKey().hashCode()) ^
- (getValue()==null ? 0 : getValue().hashCode());
- }
- public Object setValue(Object value) {
- throw new UnsupportedOperationException("Entry.setValue is not supported.");
- }
- public Object getValue() {
- return value;
- }
- public Object getKey() {
- return key;
- }
- }
- /** Wrapper giving correct symantics for equals and hashcode */
- private final static class Referenced {
- private final WeakReference reference;
- private final int hashCode;
- /**
- *
- * @throws NullPointerException if referant is
null
- */
- private Referenced(Object referant) {
- reference = new WeakReference(referant);
- // Calc a permanent hashCode so calls to Hashtable.remove()
- // work if the WeakReference has been cleared
- hashCode = referant.hashCode();
- }
- /**
- *
- * @throws NullPointerException if key is
null
- */
- private Referenced(Object key, ReferenceQueue queue) {
- reference = new WeakKey(key, queue, this);
- // Calc a permanent hashCode so calls to Hashtable.remove()
- // work if the WeakReference has been cleared
- hashCode = key.hashCode();
- }
- public int hashCode() {
- return hashCode;
- }
- private Object getValue() {
- return reference.get();
- }
- public boolean equals(Object o) {
- boolean result = false;
- if (o instanceof Referenced) {
- Referenced otherKey = (Referenced) o;
- Object thisKeyValue = getValue();
- Object otherKeyValue = otherKey.getValue();
- if (thisKeyValue == null) {
- result = (otherKeyValue == null);
- // Since our hashcode was calculated from the original
- // non-null referant, the above check breaks the
- // hashcode/equals contract, as two cleared Referenced
- // objects could test equal but have different hashcodes.
- // We can reduce (not eliminate) the chance of this
- // happening by comparing hashcodes.
- if (result == true) {
- result = (this.hashCode() == otherKey.hashCode());
- }
- // In any case, as our c'tor does not allow null referants
- // and Hashtable does not do equality checks between
- // existing keys, normal hashtable operations should never
- // result in an equals comparison between null referants
- }
- else
- {
- result = thisKeyValue.equals(otherKeyValue);
- }
- }
- return result;
- }
- }
- /**
- * WeakReference subclass that holds a hard reference to an
- * associated
value
and also makes accessible
- * the Referenced object holding it.
- */
- private final static class WeakKey extends WeakReference {
- private final Referenced referenced;
- private WeakKey(Object key,
- ReferenceQueue queue,
- Referenced referenced) {
- super(key, queue);
- this.referenced = referenced;
- }
- private Referenced getReferenced() {
- return referenced;
- }
- }
diff --git a/clients/java/src/org/json/JSONArray.java b/clients/java/src/org/json/JSONArray.java
deleted file mode 100644
index a8c6082..0000000
--- a/clients/java/src/org/json/JSONArray.java
+++ /dev/null
@@ -1,900 +0,0 @@
-package org.json;
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-The Software shall be used for Good, not Evil.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-import java.io.IOException;
-import java.io.Writer;
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Map;
- * A JSONArray is an ordered sequence of values. Its external text form is a
- * string wrapped in square brackets with commas separating the values. The
- * internal form is an object having
get
and
opt
- * methods for accessing the values by index, and
put
methods for
- * adding or replacing values. The values can be any of these types:
- *
Boolean
,
JSONArray
,
JSONObject
,
- *
Number
,
String
, or the
- *
JSONObject.NULL object
.
- * The constructor can convert a JSON text into a Java object. The
- *
toString
method converts to JSON text.
- * A
get
method returns a value if one can be found, and throws an
- * exception if one cannot be found. An
opt
method returns a
- * default value instead of throwing an exception, and so is useful for
- * obtaining optional values.
- * The generic
get()
and
opt()
methods return an
- * object which you can cast or query for type. There are also typed
- *
get
and
opt
methods that do type checking and type
- * coersion for you.
- * The texts produced by the
toString
methods strictly conform to
- * JSON syntax rules. The constructors are more forgiving in the texts they will
- * accept:
- *
-
An extra
,
(comma)
may appear just
- * before the closing bracket.
- *
-
The
null
value will be inserted when there
- * is
,
(comma)
elision.
- *
-
Strings may be quoted with
'
(single
- * quote)
.
- *
-
Strings do not need to be quoted at all if they do not begin with a quote
- * or single quote, and if they do not contain leading or trailing spaces,
- * and if they do not contain any of these characters:
- *
{ } [ ] / \ : , = ; #
and if they do not look like numbers
- * and if they are not the reserved words
true
,
- *
false
, or
null
.
- *
-
Values can be separated by
;
(semicolon)
as
- * well as by
,
(comma)
.
- *
-
Numbers may have the
0-
(octal)
or
- *
0x-
(hex)
prefix.
- *
-
Comments written in the slashshlash, slashstar, and hash conventions
- * will be ignored.
- * @author JSON.org
- * @version 2
-public class JSONArray {
- /**
- * The arrayList where the JSONArray's properties are kept.
- */
- private ArrayList myArrayList;
- /**
- * Construct an empty JSONArray.
- */
- public JSONArray() {
- this.myArrayList = new ArrayList();
- }
- /**
- * Construct a JSONArray from a JSONTokener.
- * @param x A JSONTokener
- * @throws JSONException If there is a syntax error.
- */
- public JSONArray(JSONTokener x) throws JSONException {
- this();
- char c = x.nextClean();
- char q;
- if (c == '[') {
- q = ']';
- } else if (c == '(') {
- q = ')';
- } else {
- throw x.syntaxError("A JSONArray text must start with '['");
- }
- if (x.nextClean() == ']') {
- return;
- }
- x.back();
- for (;;) {
- if (x.nextClean() == ',') {
- x.back();
- this.myArrayList.add(null);
- } else {
- x.back();
- this.myArrayList.add(x.nextValue());
- }
- c = x.nextClean();
- switch (c) {
- case ';':
- case ',':
- if (x.nextClean() == ']') {
- return;
- }
- x.back();
- break;
- case ']':
- case ')':
- if (q != c) {
- throw x.syntaxError("Expected a '" + String.valueOf(c) + "'");
- }
- return;
- default:
- throw x.syntaxError("Expected a ',' or ']'");
- }
- }
- }
- /**
- * Construct a JSONArray from a source JSON text.
- * @param source A string that begins with
- *
[
(left bracket)
- * and ends with
]
(right bracket)
.
- * @throws JSONException If there is a syntax error.
- */
- public JSONArray(String source) throws JSONException {
- this(new JSONTokener(source));
- }
- /**
- * Construct a JSONArray from a Collection.
- * @param collection A Collection.
- */
- public JSONArray(Collection collection) {
- this.myArrayList = (collection == null) ?
- new ArrayList() :
- new ArrayList(collection);
- }
- /**
- * Construct a JSONArray from an array
- * @throws JSONException If not an array.
- */
- public JSONArray(Object array) throws JSONException {
- this();
- if (array.getClass().isArray()) {
- int length = Array.getLength(array);
- for (int i = 0; i < length; i += 1) {
- this.put(Array.get(array, i));
- }
- } else {
- throw new JSONException("JSONArray initial value should be a string or collection or array.");
- }
- }
- /**
- * Get the object value associated with an index.
- * @param index
- * The index must be between 0 and length() - 1.
- * @return An object value.
- * @throws JSONException If there is no value for the index.
- */
- public Object get(int index) throws JSONException {
- Object o = opt(index);
- if (o == null) {
- throw new JSONException("JSONArray[" + index + "] not found.");
- }
- return o;
- }
- /**
- * Get the boolean value associated with an index.
- * The string values "true" and "false" are converted to boolean.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The truth.
- * @throws JSONException If there is no value for the index or if the
- * value is not convertable to boolean.
- */
- public boolean getBoolean(int index) throws JSONException {
- Object o = get(index);
- if (o.equals(Boolean.FALSE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("false"))) {
- return false;
- } else if (o.equals(Boolean.TRUE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
- }
- /**
- * Get the double value associated with an index.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException If the key is not found or if the value cannot
- * be converted to a number.
- */
- public double getDouble(int index) throws JSONException {
- Object o = get(index);
- try {
- return o instanceof Number ?
- ((Number)o).doubleValue() :
- Double.valueOf((String)o).doubleValue();
- } catch (Exception e) {
- throw new JSONException("JSONArray[" + index +
- "] is not a number.");
- }
- }
- /**
- * Get the int value associated with an index.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException If the key is not found or if the value cannot
- * be converted to a number.
- * if the value cannot be converted to a number.
- */
- public int getInt(int index) throws JSONException {
- Object o = get(index);
- return o instanceof Number ?
- ((Number)o).intValue() : (int)getDouble(index);
- }
- /**
- * Get the JSONArray associated with an index.
- * @param index The index must be between 0 and length() - 1.
- * @return A JSONArray value.
- * @throws JSONException If there is no value for the index. or if the
- * value is not a JSONArray
- */
- public JSONArray getJSONArray(int index) throws JSONException {
- Object o = get(index);
- if (o instanceof JSONArray) {
- return (JSONArray)o;
- }
- throw new JSONException("JSONArray[" + index +
- "] is not a JSONArray.");
- }
- /**
- * Get the JSONObject associated with an index.
- * @param index subscript
- * @return A JSONObject value.
- * @throws JSONException If there is no value for the index or if the
- * value is not a JSONObject
- */
- public JSONObject getJSONObject(int index) throws JSONException {
- Object o = get(index);
- if (o instanceof JSONObject) {
- return (JSONObject)o;
- }
- throw new JSONException("JSONArray[" + index +
- "] is not a JSONObject.");
- }
- /**
- * Get the long value associated with an index.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- * @throws JSONException If the key is not found or if the value cannot
- * be converted to a number.
- */
- public long getLong(int index) throws JSONException {
- Object o = get(index);
- return o instanceof Number ?
- ((Number)o).longValue() : (long)getDouble(index);
- }
- /**
- * Get the string associated with an index.
- * @param index The index must be between 0 and length() - 1.
- * @return A string value.
- * @throws JSONException If there is no value for the index.
- */
- public String getString(int index) throws JSONException {
- return get(index).toString();
- }
- /**
- * Determine if the value is null.
- * @param index The index must be between 0 and length() - 1.
- * @return true if the value at the index is null, or if there is no value.
- */
- public boolean isNull(int index) {
- return JSONObject.NULL.equals(opt(index));
- }
- /**
- * Make a string from the contents of this JSONArray. The
- *
separator
string is inserted between each element.
- * Warning: This method assumes that the data structure is acyclical.
- * @param separator A string that will be inserted between the elements.
- * @return a string.
- * @throws JSONException If the array contains an invalid number.
- */
- public String join(String separator) throws JSONException {
- int len = length();
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < len; i += 1) {
- if (i > 0) {
- sb.append(separator);
- }
- sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
- }
- return sb.toString();
- }
- /**
- * Get the number of elements in the JSONArray, included nulls.
- *
- * @return The length (or size).
- */
- public int length() {
- return this.myArrayList.size();
- }
- /**
- * Get the optional object value associated with an index.
- * @param index The index must be between 0 and length() - 1.
- * @return An object value, or null if there is no
- * object at that index.
- */
- public Object opt(int index) {
- return (index < 0 || index >= length()) ?
- null : this.myArrayList.get(index);
- }
- /**
- * Get the optional boolean value associated with an index.
- * It returns false if there is no value at that index,
- * or if the value is not Boolean.TRUE or the String "true".
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The truth.
- */
- public boolean optBoolean(int index) {
- return optBoolean(index, false);
- }
- /**
- * Get the optional boolean value associated with an index.
- * It returns the defaultValue if there is no value at that index or if
- * it is not a Boolean or the String "true" or "false" (case insensitive).
- *
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue A boolean default.
- * @return The truth.
- */
- public boolean optBoolean(int index, boolean defaultValue) {
- try {
- return getBoolean(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get the optional double value associated with an index.
- * NaN is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- */
- public double optDouble(int index) {
- return optDouble(index, Double.NaN);
- }
- /**
- * Get the optional double value associated with an index.
- * The defaultValue is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index subscript
- * @param defaultValue The default value.
- * @return The value.
- */
- public double optDouble(int index, double defaultValue) {
- try {
- return getDouble(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get the optional int value associated with an index.
- * Zero is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- */
- public int optInt(int index) {
- return optInt(index, 0);
- }
- /**
- * Get the optional int value associated with an index.
- * The defaultValue is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue The default value.
- * @return The value.
- */
- public int optInt(int index, int defaultValue) {
- try {
- return getInt(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get the optional JSONArray associated with an index.
- * @param index subscript
- * @return A JSONArray value, or null if the index has no value,
- * or if the value is not a JSONArray.
- */
- public JSONArray optJSONArray(int index) {
- Object o = opt(index);
- return o instanceof JSONArray ? (JSONArray)o : null;
- }
- /**
- * Get the optional JSONObject associated with an index.
- * Null is returned if the key is not found, or null if the index has
- * no value, or if the value is not a JSONObject.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return A JSONObject value.
- */
- public JSONObject optJSONObject(int index) {
- Object o = opt(index);
- return o instanceof JSONObject ? (JSONObject)o : null;
- }
- /**
- * Get the optional long value associated with an index.
- * Zero is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return The value.
- */
- public long optLong(int index) {
- return optLong(index, 0);
- }
- /**
- * Get the optional long value associated with an index.
- * The defaultValue is returned if there is no value for the index,
- * or if the value is not a number and cannot be converted to a number.
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue The default value.
- * @return The value.
- */
- public long optLong(int index, long defaultValue) {
- try {
- return getLong(index);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get the optional string value associated with an index. It returns an
- * empty string if there is no value at that index. If the value
- * is not a string and is not null, then it is coverted to a string.
- *
- * @param index The index must be between 0 and length() - 1.
- * @return A String value.
- */
- public String optString(int index) {
- return optString(index, "");
- }
- /**
- * Get the optional string associated with an index.
- * The defaultValue is returned if the key is not found.
- *
- * @param index The index must be between 0 and length() - 1.
- * @param defaultValue The default value.
- * @return A String value.
- */
- public String optString(int index, String defaultValue) {
- Object o = opt(index);
- return o != null ? o.toString() : defaultValue;
- }
- /**
- * Append a boolean value. This increases the array's length by one.
- *
- * @param value A boolean value.
- * @return this.
- */
- public JSONArray put(boolean value) {
- put(value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONArray which is produced from a Collection.
- * @param value A Collection value.
- * @return this.
- */
- public JSONArray put(Collection value) {
- put(new JSONArray(value));
- return this;
- }
- /**
- * Append a double value. This increases the array's length by one.
- *
- * @param value A double value.
- * @throws JSONException if the value is not finite.
- * @return this.
- */
- public JSONArray put(double value) throws JSONException {
- Double d = new Double(value);
- JSONObject.testValidity(d);
- put(d);
- return this;
- }
- /**
- * Append an int value. This increases the array's length by one.
- *
- * @param value An int value.
- * @return this.
- */
- public JSONArray put(int value) {
- put(new Integer(value));
- return this;
- }
- /**
- * Append an long value. This increases the array's length by one.
- *
- * @param value A long value.
- * @return this.
- */
- public JSONArray put(long value) {
- put(new Long(value));
- return this;
- }
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONObject which is produced from a Map.
- * @param value A Map value.
- * @return this.
- */
- public JSONArray put(Map value) {
- put(new JSONObject(value));
- return this;
- }
- /**
- * Append an object value. This increases the array's length by one.
- * @param value An object value. The value should be a
- * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
- * JSONObject.NULL object.
- * @return this.
- */
- public JSONArray put(Object value) {
- this.myArrayList.add(value);
- return this;
- }
- /**
- * Put or replace a boolean value in the JSONArray. If the index is greater
- * than the length of the JSONArray, then null elements will be added as
- * necessary to pad it out.
- * @param index The subscript.
- * @param value A boolean value.
- * @return this.
- * @throws JSONException If the index is negative.
- */
- public JSONArray put(int index, boolean value) throws JSONException {
- put(index, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONArray which is produced from a Collection.
- * @param index The subscript.
- * @param value A Collection value.
- * @return this.
- * @throws JSONException If the index is negative or if the value is
- * not finite.
- */
- public JSONArray put(int index, Collection value) throws JSONException {
- put(index, new JSONArray(value));
- return this;
- }
- /**
- * Put or replace a double value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad
- * it out.
- * @param index The subscript.
- * @param value A double value.
- * @return this.
- * @throws JSONException If the index is negative or if the value is
- * not finite.
- */
- public JSONArray put(int index, double value) throws JSONException {
- put(index, new Double(value));
- return this;
- }
- /**
- * Put or replace an int value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad
- * it out.
- * @param index The subscript.
- * @param value An int value.
- * @return this.
- * @throws JSONException If the index is negative.
- */
- public JSONArray put(int index, int value) throws JSONException {
- put(index, new Integer(value));
- return this;
- }
- /**
- * Put or replace a long value. If the index is greater than the length of
- * the JSONArray, then null elements will be added as necessary to pad
- * it out.
- * @param index The subscript.
- * @param value A long value.
- * @return this.
- * @throws JSONException If the index is negative.
- */
- public JSONArray put(int index, long value) throws JSONException {
- put(index, new Long(value));
- return this;
- }
- /**
- * Put a value in the JSONArray, where the value will be a
- * JSONObject which is produced from a Map.
- * @param index The subscript.
- * @param value The Map value.
- * @return this.
- * @throws JSONException If the index is negative or if the the value is
- * an invalid number.
- */
- public JSONArray put(int index, Map value) throws JSONException {
- put(index, new JSONObject(value));
- return this;
- }
- /**
- * Put or replace an object value in the JSONArray. If the index is greater
- * than the length of the JSONArray, then null elements will be added as
- * necessary to pad it out.
- * @param index The subscript.
- * @param value The value to put into the array. The value should be a
- * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
- * JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the index is negative or if the the value is
- * an invalid number.
- */
- public JSONArray put(int index, Object value) throws JSONException {
- JSONObject.testValidity(value);
- if (index < 0) {
- throw new JSONException("JSONArray[" + index + "] not found.");
- }
- if (index < length()) {
- this.myArrayList.set(index, value);
- } else {
- while (index != length()) {
- put(JSONObject.NULL);
- }
- put(value);
- }
- return this;
- }
- /**
- * Produce a JSONObject by combining a JSONArray of names with the values
- * of this JSONArray.
- * @param names A JSONArray containing a list of key strings. These will be
- * paired with the values.
- * @return A JSONObject, or null if there are no names or if this JSONArray
- * has no values.
- * @throws JSONException If any of the names are null.
- */
- public JSONObject toJSONObject(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0 || length() == 0) {
- return null;
- }
- JSONObject jo = new JSONObject();
- for (int i = 0; i < names.length(); i += 1) {
- jo.put(names.getString(i), this.opt(i));
- }
- return jo;
- }
- /**
- * Make a JSON text of this JSONArray. For compactness, no
- * unnecessary whitespace is added. If it is not possible to produce a
- * syntactically correct JSON text then null will be returned instead. This
- * could occur if the array contains an invalid number.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return a printable, displayable, transmittable
- * representation of the array.
- */
- public String toString() {
- try {
- return '[' + join(",") + ']';
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * Make a prettyprinted JSON text of this JSONArray.
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with
[
(left bracket)
and ending
- * with
]
(right bracket)
.
- * @throws JSONException
- */
- public String toString(int indentFactor) throws JSONException {
- return toString(indentFactor, 0);
- }
- /**
- * Make a prettyprinted JSON text of this JSONArray.
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @param indent The indention of the top level.
- * @return a printable, displayable, transmittable
- * representation of the array.
- * @throws JSONException
- */
- String toString(int indentFactor, int indent) throws JSONException {
- int len = length();
- if (len == 0) {
- return "[]";
- }
- int i;
- StringBuffer sb = new StringBuffer("[");
- if (len == 1) {
- sb.append(JSONObject.valueToString(this.myArrayList.get(0),
- indentFactor, indent));
- } else {
- int newindent = indent + indentFactor;
- sb.append('\n');
- for (i = 0; i < len; i += 1) {
- if (i > 0) {
- sb.append(",\n");
- }
- for (int j = 0; j < newindent; j += 1) {
- sb.append(' ');
- }
- sb.append(JSONObject.valueToString(this.myArrayList.get(i),
- indentFactor, newindent));
- }
- sb.append('\n');
- for (i = 0; i < indent; i += 1) {
- sb.append(' ');
- }
- }
- sb.append(']');
- return sb.toString();
- }
- /**
- * Write the contents of the JSONArray as JSON text to a writer.
- * For compactness, no whitespace is added.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer) throws JSONException {
- try {
- boolean b = false;
- int len = length();
- writer.write('[');
- for (int i = 0; i < len; i += 1) {
- if (b) {
- writer.write(',');
- }
- Object v = this.myArrayList.get(i);
- if (v instanceof JSONObject) {
- ((JSONObject)v).write(writer);
- } else if (v instanceof JSONArray) {
- ((JSONArray)v).write(writer);
- } else {
- writer.write(JSONObject.valueToString(v));
- }
- b = true;
- }
- writer.write(']');
- return writer;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
\ No newline at end of file
diff --git a/clients/java/src/org/json/JSONException.java b/clients/java/src/org/json/JSONException.java
deleted file mode 100644
index 535168f..0000000
--- a/clients/java/src/org/json/JSONException.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package org.json;
- * The JSONException is thrown by the JSON.org classes then things are amiss.
- * @author JSON.org
- * @version 2
-public class JSONException extends Exception {
- private Throwable cause;
- /**
- * Constructs a JSONException with an explanatory message.
- * @param message Detail about the reason for the exception.
- */
- public JSONException(String message) {
- super(message);
- }
- public JSONException(Throwable t) {
- super(t.getMessage());
- this.cause = t;
- }
- public Throwable getCause() {
- return this.cause;
- }
diff --git a/clients/java/src/org/json/JSONObject.java b/clients/java/src/org/json/JSONObject.java
deleted file mode 100644
index a459512..0000000
--- a/clients/java/src/org/json/JSONObject.java
+++ /dev/null
@@ -1,1380 +0,0 @@
-package org.json;
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-The Software shall be used for Good, not Evil.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Collection;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
- * A JSONObject is an unordered collection of name/value pairs. Its
- * external form is a string wrapped in curly braces with colons between the
- * names and values, and commas between the values and names. The internal form
- * is an object having
get
and
opt
methods for
- * accessing the values by name, and
put
methods for adding or
- * replacing values by name. The values can be any of these types:
- *
Boolean
,
JSONArray
,
JSONObject
,
- *
Number
,
String
, or the
JSONObject.NULL
- * object. A JSONObject constructor can be used to convert an external form
- * JSON text into an internal form whose values can be retrieved with the
- *
get
and
opt
methods, or to convert values into a
- * JSON text using the
put
and
toString
methods.
- * A
get
method returns a value if one can be found, and throws an
- * exception if one cannot be found. An
opt
method returns a
- * default value instead of throwing an exception, and so is useful for
- * obtaining optional values.
- * The generic
get()
and
opt()
methods return an
- * object, which you can cast or query for type. There are also typed
- *
get
and
opt
methods that do type checking and type
- * coersion for you.
- * The
put
methods adds values to an object. For example,
- * myString = new JSONObject().put("JSON", "Hello, World!").toString();
- * produces the string
{"JSON": "Hello, World"}
.
- * The texts produced by the
toString
methods strictly conform to
- * the JSON sysntax rules.
- * The constructors are more forgiving in the texts they will accept:
- *
-
An extra
,
(comma)
may appear just
- * before the closing brace.
- *
-
Strings may be quoted with
'
(single
- * quote)
.
- *
-
Strings do not need to be quoted at all if they do not begin with a quote
- * or single quote, and if they do not contain leading or trailing spaces,
- * and if they do not contain any of these characters:
- *
{ } [ ] / \ : , = ; #
and if they do not look like numbers
- * and if they are not the reserved words
true
,
- *
false
, or
null
.
- *
-
Keys can be followed by
=
or
=>
as well as
- * by
:
.
- *
-
Values can be followed by
;
(semicolon)
as
- * well as by
,
(comma)
.
- *
-
Numbers may have the
0-
(octal)
or
- *
0x-
(hex)
prefix.
- *
-
Comments written in the slashshlash, slashstar, and hash conventions
- * will be ignored.
- * @author JSON.org
- * @version 2
-public class JSONObject {
- /**
- * JSONObject.NULL is equivalent to the value that JavaScript calls null,
- * whilst Java's null is equivalent to the value that JavaScript calls
- * undefined.
- */
- private static final class Null {
- /**
- * There is only intended to be a single instance of the NULL object,
- * so the clone method returns itself.
- * @return NULL.
- */
- protected final Object clone() {
- return this;
- }
- /**
- * A Null object is equal to the null value and to itself.
- * @param object An object to test for nullness.
- * @return true if the object parameter is the JSONObject.NULL object
- * or null.
- */
- public boolean equals(Object object) {
- return object == null || object == this;
- }
- /**
- * Get the "null" string value.
- * @return The string "null".
- */
- public String toString() {
- return "null";
- }
- }
- /**
- * The hash map where the JSONObject's properties are kept.
- */
- private HashMap myHashMap;
- /**
- * It is sometimes more convenient and less ambiguous to have a
- *
NULL
object than to use Java's
null
value.
- *
JSONObject.NULL.equals(null)
returns
true
.
- *
JSONObject.NULL.toString()
returns
"null"
.
- */
- public static final Object NULL = new Null();
- /**
- * Construct an empty JSONObject.
- */
- public JSONObject() {
- this.myHashMap = new HashMap();
- }
- /**
- * Construct a JSONObject from a subset of another JSONObject.
- * An array of strings is used to identify the keys that should be copied.
- * Missing keys are ignored.
- * @param jo A JSONObject.
- * @param names An array of strings.
- * @exception JSONException If a value is a non-finite number.
- */
- public JSONObject(JSONObject jo, String[] names) throws JSONException {
- this();
- for (int i = 0; i < names.length; i += 1) {
- putOpt(names[i], jo.opt(names[i]));
- }
- }
- /**
- * Construct a JSONObject from a JSONTokener.
- * @param x A JSONTokener object containing the source string.
- * @throws JSONException If there is a syntax error in the source string.
- */
- public JSONObject(JSONTokener x) throws JSONException {
- this();
- char c;
- String key;
- if (x.nextClean() != '{') {
- throw x.syntaxError("A JSONObject text must begin with '{'");
- }
- for (;;) {
- c = x.nextClean();
- switch (c) {
- case 0:
- throw x.syntaxError("A JSONObject text must end with '}'");
- case '}':
- return;
- default:
- x.back();
- key = x.nextValue().toString();
- }
- /*
- * The key is followed by ':'. We will also tolerate '=' or '=>'.
- */
- c = x.nextClean();
- if (c == '=') {
- if (x.next() != '>') {
- x.back();
- }
- } else if (c != ':') {
- throw x.syntaxError("Expected a ':' after a key");
- }
- put(key, x.nextValue());
- /*
- * Pairs are separated by ','. We will also tolerate ';'.
- */
- switch (x.nextClean()) {
- case ';':
- case ',':
- if (x.nextClean() == '}') {
- return;
- }
- x.back();
- break;
- case '}':
- return;
- default:
- throw x.syntaxError("Expected a ',' or '}'");
- }
- }
- }
- /**
- * Construct a JSONObject from a Map.
- * @param map A map object that can be used to initialize the contents of
- * the JSONObject.
- */
- public JSONObject(Map map) {
- this.myHashMap = (map == null) ?
- new HashMap() :
- new HashMap(map);
- }
- /**
- * Construct a JSONObject from an Object using bean getters.
- * It reflects on all of the public methods of the object.
- * For each of the methods with no parameters and a name starting
- * with
"get"
or
"is"
followed by an uppercase letter,
- * the method is invoked, and a key and the value returned from the getter method
- * are put into the new JSONObject.
- *
- * The key is formed by removing the
"get"
or
"is"
prefix. If the second remaining
- * character is not upper case, then the first
- * character is converted to lower case.
- *
- * For example, if an object has a method named
"getName"
, and
- * if the result of calling
object.getName()
is
"Larry Fine"
,
- * then the JSONObject will contain
"name": "Larry Fine"
.
- *
- * @param bean An object that has getter methods that should be used
- * to make a JSONObject.
- */
- public JSONObject(Object bean) {
- this();
- Class klass = bean.getClass();
- Method[] methods = klass.getMethods();
- for (int i = 0; i < methods.length; i += 1) {
- try {
- Method method = methods[i];
- String name = method.getName();
- String key = "";
- if (name.startsWith("get")) {
- key = name.substring(3);
- } else if (name.startsWith("is")) {
- key = name.substring(2);
- }
- if (key.length() > 0 &&
- Character.isUpperCase(key.charAt(0)) &&
- method.getParameterTypes().length == 0) {
- if (key.length() == 1) {
- key = key.toLowerCase();
- } else if (!Character.isUpperCase(key.charAt(1))) {
- key = key.substring(0, 1).toLowerCase() +
- key.substring(1);
- }
- this.put(key, method.invoke(bean, null));
- }
- } catch (Exception e) {
- /* forget about it */
- }
- }
- }
- /**
- * Construct a JSONObject from an Object, using reflection to find the
- * public members. The resulting JSONObject's keys will be the strings
- * from the names array, and the values will be the field values associated
- * with those keys in the object. If a key is not found or not visible,
- * then it will not be copied into the new JSONObject.
- * @param object An object that has fields that should be used to make a
- * JSONObject.
- * @param names An array of strings, the names of the fields to be obtained
- * from the object.
- */
- public JSONObject(Object object, String names[]) {
- this();
- Class c = object.getClass();
- for (int i = 0; i < names.length; i += 1) {
- String name = names[i];
- try {
- Field field = c.getField(name);
- Object value = field.get(object);
- this.put(name, value);
- } catch (Exception e) {
- /* forget about it */
- }
- }
- }
- /**
- * Construct a JSONObject from a source JSON text string.
- * This is the most commonly used JSONObject constructor.
- * @param source A string beginning
- * with
{
(left brace)
and ending
- * with
}
(right brace)
.
- * @exception JSONException If there is a syntax error in the source string.
- */
- public JSONObject(String source) throws JSONException {
- this(new JSONTokener(source));
- }
- /**
- * Accumulate values under a key. It is similar to the put method except
- * that if there is already an object stored under the key then a
- * JSONArray is stored under the key to hold all of the accumulated values.
- * If there is already a JSONArray, then the new value is appended to it.
- * In contrast, the put method replaces the previous value.
- * @param key A key string.
- * @param value An object to be accumulated under the key.
- * @return this.
- * @throws JSONException If the value is an invalid number
- * or if the key is null.
- */
- public JSONObject accumulate(String key, Object value)
- throws JSONException {
- testValidity(value);
- Object o = opt(key);
- if (o == null) {
- put(key, value instanceof JSONArray ?
- new JSONArray().put(value) :
- value);
- } else if (o instanceof JSONArray) {
- ((JSONArray)o).put(value);
- } else {
- put(key, new JSONArray().put(o).put(value));
- }
- return this;
- }
- /**
- * Append values to the array under a key. If the key does not exist in the
- * JSONObject, then the key is put in the JSONObject with its value being a
- * JSONArray containing the value parameter. If the key was already
- * associated with a JSONArray, then the value parameter is appended to it.
- * @param key A key string.
- * @param value An object to be accumulated under the key.
- * @return this.
- * @throws JSONException If the key is null or if the current value
- * associated with the key is not a JSONArray.
- */
- public JSONObject append(String key, Object value)
- throws JSONException {
- testValidity(value);
- Object o = opt(key);
- if (o == null) {
- put(key, new JSONArray().put(value));
- } else if (o instanceof JSONArray) {
- put(key, ((JSONArray)o).put(value));
- } else {
- throw new JSONException("JSONObject[" + key +
- "] is not a JSONArray.");
- }
- return this;
- }
- /**
- * Produce a string from a double. The string "null" will be returned if
- * the number is not finite.
- * @param d A double.
- * @return A String.
- */
- static public String doubleToString(double d) {
- if (Double.isInfinite(d) || Double.isNaN(d)) {
- return "null";
- }
-// Shave off trailing zeros and decimal point, if possible.
- String s = Double.toString(d);
- if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
- while (s.endsWith("0")) {
- s = s.substring(0, s.length() - 1);
- }
- if (s.endsWith(".")) {
- s = s.substring(0, s.length() - 1);
- }
- }
- return s;
- }
- /**
- * Get the value object associated with a key.
- *
- * @param key A key string.
- * @return The object associated with the key.
- * @throws JSONException if the key is not found.
- */
- public Object get(String key) throws JSONException {
- Object o = opt(key);
- if (o == null) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] not found.");
- }
- return o;
- }
- /**
- * Get the boolean value associated with a key.
- *
- * @param key A key string.
- * @return The truth.
- * @throws JSONException
- * if the value is not a Boolean or the String "true" or "false".
- */
- public boolean getBoolean(String key) throws JSONException {
- Object o = get(key);
- if (o.equals(Boolean.FALSE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("false"))) {
- return false;
- } else if (o.equals(Boolean.TRUE) ||
- (o instanceof String &&
- ((String)o).equalsIgnoreCase("true"))) {
- return true;
- }
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a Boolean.");
- }
- /**
- * Get the double value associated with a key.
- * @param key A key string.
- * @return The numeric value.
- * @throws JSONException if the key is not found or
- * if the value is not a Number object and cannot be converted to a number.
- */
- public double getDouble(String key) throws JSONException {
- Object o = get(key);
- try {
- return o instanceof Number ?
- ((Number)o).doubleValue() :
- Double.valueOf((String)o).doubleValue();
- } catch (Exception e) {
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a number.");
- }
- }
- /**
- * Get the int value associated with a key. If the number value is too
- * large for an int, it will be clipped.
- *
- * @param key A key string.
- * @return The integer value.
- * @throws JSONException if the key is not found or if the value cannot
- * be converted to an integer.
- */
- public int getInt(String key) throws JSONException {
- Object o = get(key);
- return o instanceof Number ?
- ((Number)o).intValue() : (int)getDouble(key);
- }
- /**
- * Get the JSONArray value associated with a key.
- *
- * @param key A key string.
- * @return A JSONArray which is the value.
- * @throws JSONException if the key is not found or
- * if the value is not a JSONArray.
- */
- public JSONArray getJSONArray(String key) throws JSONException {
- Object o = get(key);
- if (o instanceof JSONArray) {
- return (JSONArray)o;
- }
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONArray.");
- }
- /**
- * Get the JSONObject value associated with a key.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- * @throws JSONException if the key is not found or
- * if the value is not a JSONObject.
- */
- public JSONObject getJSONObject(String key) throws JSONException {
- Object o = get(key);
- if (o instanceof JSONObject) {
- return (JSONObject)o;
- }
- throw new JSONException("JSONObject[" + quote(key) +
- "] is not a JSONObject.");
- }
- /**
- * Get the long value associated with a key. If the number value is too
- * long for a long, it will be clipped.
- *
- * @param key A key string.
- * @return The long value.
- * @throws JSONException if the key is not found or if the value cannot
- * be converted to a long.
- */
- public long getLong(String key) throws JSONException {
- Object o = get(key);
- return o instanceof Number ?
- ((Number)o).longValue() : (long)getDouble(key);
- }
- /**
- * Get an array of field names from a JSONObject.
- *
- * @return An array of field names, or null if there are no names.
- */
- public static String[] getNames(JSONObject jo) {
- int length = jo.length();
- if (length == 0) {
- return null;
- }
- Iterator i = jo.keys();
- String[] names = new String[length];
- int j = 0;
- while (i.hasNext()) {
- names[j] = (String)i.next();
- j += 1;
- }
- return names;
- }
- /**
- * Get an array of field names from an Object.
- *
- * @return An array of field names, or null if there are no names.
- */
- public static String[] getNames(Object object) {
- if (object == null) {
- return null;
- }
- Class klass = object.getClass();
- Field[] fields = klass.getFields();
- int length = fields.length;
- if (length == 0) {
- return null;
- }
- String[] names = new String[length];
- for (int i = 0; i < length; i += 1) {
- names[i] = fields[i].getName();
- }
- return names;
- }
- /**
- * Get the string associated with a key.
- *
- * @param key A key string.
- * @return A string which is the value.
- * @throws JSONException if the key is not found.
- */
- public String getString(String key) throws JSONException {
- return get(key).toString();
- }
- /**
- * Determine if the JSONObject contains a specific key.
- * @param key A key string.
- * @return true if the key exists in the JSONObject.
- */
- public boolean has(String key) {
- return this.myHashMap.containsKey(key);
- }
- /**
- * Determine if the value associated with the key is null or if there is
- * no value.
- * @param key A key string.
- * @return true if there is no value associated with the key or if
- * the value is the JSONObject.NULL object.
- */
- public boolean isNull(String key) {
- return JSONObject.NULL.equals(opt(key));
- }
- /**
- * Get an enumeration of the keys of the JSONObject.
- *
- * @return An iterator of the keys.
- */
- public Iterator keys() {
- return this.myHashMap.keySet().iterator();
- }
- /**
- * Get the number of keys stored in the JSONObject.
- *
- * @return The number of keys in the JSONObject.
- */
- public int length() {
- return this.myHashMap.size();
- }
- /**
- * Produce a JSONArray containing the names of the elements of this
- * JSONObject.
- * @return A JSONArray containing the key strings, or null if the JSONObject
- * is empty.
- */
- public JSONArray names() {
- JSONArray ja = new JSONArray();
- Iterator keys = keys();
- while (keys.hasNext()) {
- ja.put(keys.next());
- }
- return ja.length() == 0 ? null : ja;
- }
- /**
- * Produce a string from a Number.
- * @param n A Number
- * @return A String.
- * @throws JSONException If n is a non-finite number.
- */
- static public String numberToString(Number n)
- throws JSONException {
- if (n == null) {
- throw new JSONException("Null pointer");
- }
- testValidity(n);
-// Shave off trailing zeros and decimal point, if possible.
- String s = n.toString();
- if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
- while (s.endsWith("0")) {
- s = s.substring(0, s.length() - 1);
- }
- if (s.endsWith(".")) {
- s = s.substring(0, s.length() - 1);
- }
- }
- return s;
- }
- /**
- * Get an optional value associated with a key.
- * @param key A key string.
- * @return An object which is the value, or null if there is no value.
- */
- public Object opt(String key) {
- return key == null ? null : this.myHashMap.get(key);
- }
- /**
- * Get an optional boolean associated with a key.
- * It returns false if there is no such key, or if the value is not
- * Boolean.TRUE or the String "true".
- *
- * @param key A key string.
- * @return The truth.
- */
- public boolean optBoolean(String key) {
- return optBoolean(key, false);
- }
- /**
- * Get an optional boolean associated with a key.
- * It returns the defaultValue if there is no such key, or if it is not
- * a Boolean or the String "true" or "false" (case insensitive).
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return The truth.
- */
- public boolean optBoolean(String key, boolean defaultValue) {
- try {
- return getBoolean(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONArray which is produced from a Collection.
- * @param key A key string.
- * @param value A Collection value.
- * @return this.
- * @throws JSONException
- */
- public JSONObject put(String key, Collection value) throws JSONException {
- put(key, new JSONArray(value));
- return this;
- }
- /**
- * Get an optional double associated with a key,
- * or NaN if there is no such key or if its value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A string which is the key.
- * @return An object which is the value.
- */
- public double optDouble(String key) {
- return optDouble(key, Double.NaN);
- }
- /**
- * Get an optional double associated with a key, or the
- * defaultValue if there is no such key or if its value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public double optDouble(String key, double defaultValue) {
- try {
- Object o = opt(key);
- return o instanceof Number ? ((Number)o).doubleValue() :
- new Double((String)o).doubleValue();
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get an optional int value associated with a key,
- * or zero if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public int optInt(String key) {
- return optInt(key, 0);
- }
- /**
- * Get an optional int value associated with a key,
- * or the default if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public int optInt(String key, int defaultValue) {
- try {
- return getInt(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get an optional JSONArray associated with a key.
- * It returns null if there is no such key, or if its value is not a
- * JSONArray.
- *
- * @param key A key string.
- * @return A JSONArray which is the value.
- */
- public JSONArray optJSONArray(String key) {
- Object o = opt(key);
- return o instanceof JSONArray ? (JSONArray)o : null;
- }
- /**
- * Get an optional JSONObject associated with a key.
- * It returns null if there is no such key, or if its value is not a
- * JSONObject.
- *
- * @param key A key string.
- * @return A JSONObject which is the value.
- */
- public JSONObject optJSONObject(String key) {
- Object o = opt(key);
- return o instanceof JSONObject ? (JSONObject)o : null;
- }
- /**
- * Get an optional long value associated with a key,
- * or zero if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @return An object which is the value.
- */
- public long optLong(String key) {
- return optLong(key, 0);
- }
- /**
- * Get an optional long value associated with a key,
- * or the default if there is no such key or if the value is not a number.
- * If the value is a string, an attempt will be made to evaluate it as
- * a number.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return An object which is the value.
- */
- public long optLong(String key, long defaultValue) {
- try {
- return getLong(key);
- } catch (Exception e) {
- return defaultValue;
- }
- }
- /**
- * Get an optional string associated with a key.
- * It returns an empty string if there is no such key. If the value is not
- * a string and is not null, then it is coverted to a string.
- *
- * @param key A key string.
- * @return A string which is the value.
- */
- public String optString(String key) {
- return optString(key, "");
- }
- /**
- * Get an optional string associated with a key.
- * It returns the defaultValue if there is no such key.
- *
- * @param key A key string.
- * @param defaultValue The default.
- * @return A string which is the value.
- */
- public String optString(String key, String defaultValue) {
- Object o = opt(key);
- return o != null ? o.toString() : defaultValue;
- }
- /**
- * Put a key/boolean pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A boolean which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public JSONObject put(String key, boolean value) throws JSONException {
- put(key, value ? Boolean.TRUE : Boolean.FALSE);
- return this;
- }
- /**
- * Put a key/double pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A double which is the value.
- * @return this.
- * @throws JSONException If the key is null or if the number is invalid.
- */
- public JSONObject put(String key, double value) throws JSONException {
- put(key, new Double(value));
- return this;
- }
- /**
- * Put a key/int pair in the JSONObject.
- *
- * @param key A key string.
- * @param value An int which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public JSONObject put(String key, int value) throws JSONException {
- put(key, new Integer(value));
- return this;
- }
- /**
- * Put a key/long pair in the JSONObject.
- *
- * @param key A key string.
- * @param value A long which is the value.
- * @return this.
- * @throws JSONException If the key is null.
- */
- public JSONObject put(String key, long value) throws JSONException {
- put(key, new Long(value));
- return this;
- }
- /**
- * Put a key/value pair in the JSONObject, where the value will be a
- * JSONObject which is produced from a Map.
- * @param key A key string.
- * @param value A Map value.
- * @return this.
- * @throws JSONException
- */
- public JSONObject put(String key, Map value) throws JSONException {
- put(key, new JSONObject(value));
- return this;
- }
- /**
- * Put a key/value pair in the JSONObject. If the value is null,
- * then the key will be removed from the JSONObject if it is present.
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
- * or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is non-finite number
- * or if the key is null.
- */
- public JSONObject put(String key, Object value) throws JSONException {
- if (key == null) {
- throw new JSONException("Null key.");
- }
- if (value != null) {
- testValidity(value);
- this.myHashMap.put(key, value);
- } else {
- remove(key);
- }
- return this;
- }
- /**
- * Put a key/value pair in the JSONObject, but only if the
- * key and the value are both non-null.
- * @param key A key string.
- * @param value An object which is the value. It should be of one of these
- * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,
- * or the JSONObject.NULL object.
- * @return this.
- * @throws JSONException If the value is a non-finite number.
- */
- public JSONObject putOpt(String key, Object value) throws JSONException {
- if (key != null && value != null) {
- put(key, value);
- }
- return this;
- }
- /**
- * Produce a string in double quotes with backslash sequences in all the
- * right places. A backslash will be inserted within , allowing JSON
- * text to be delivered in HTML. In JSON text, a string cannot contain a
- * control character or an unescaped quote or backslash.
- * @param string A String
- * @return A String correctly formatted for insertion in a JSON text.
- */
- public static String quote(String string) {
- if (string == null || string.length() == 0) {
- return "\"\"";
- }
- char b;
- char c = 0;
- int i;
- int len = string.length();
- StringBuffer sb = new StringBuffer(len + 4);
- String t;
- sb.append('"');
- for (i = 0; i < len; i += 1) {
- b = c;
- c = string.charAt(i);
- switch (c) {
- case '\\':
- case '"':
- sb.append('\\');
- sb.append(c);
- break;
- case '/':
- if (b == '= '\u0080' && c < '\u00a0') ||
- (c >= '\u2000' && c < '\u2100')) {
- t = "000" + Integer.toHexString(c);
- sb.append("\\u" + t.substring(t.length() - 4));
- } else {
- sb.append(c);
- }
- }
- }
- sb.append('"');
- return sb.toString();
- }
- /**
- * Remove a name and its value, if present.
- * @param key The name to be removed.
- * @return The value that was associated with the name,
- * or null if there was no value.
- */
- public Object remove(String key) {
- return this.myHashMap.remove(key);
- }
- /**
- * Throw an exception if the object is an NaN or infinite number.
- * @param o The object to test.
- * @throws JSONException If o is a non-finite number.
- */
- static void testValidity(Object o) throws JSONException {
- if (o != null) {
- if (o instanceof Double) {
- if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
- }
- } else if (o instanceof Float) {
- if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
- throw new JSONException(
- "JSON does not allow non-finite numbers.");
- }
- }
- }
- }
- /**
- * Produce a JSONArray containing the values of the members of this
- * JSONObject.
- * @param names A JSONArray containing a list of key strings. This
- * determines the sequence of the values in the result.
- * @return A JSONArray of values.
- * @throws JSONException If any of the values are non-finite numbers.
- */
- public JSONArray toJSONArray(JSONArray names) throws JSONException {
- if (names == null || names.length() == 0) {
- return null;
- }
- JSONArray ja = new JSONArray();
- for (int i = 0; i < names.length(); i += 1) {
- ja.put(this.opt(names.getString(i)));
- }
- return ja;
- }
- /**
- * Make a JSON text of this JSONObject. For compactness, no whitespace
- * is added. If this would not result in a syntactically correct JSON text,
- * then null will be returned instead.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return a printable, displayable, portable, transmittable
- * representation of the object, beginning
- * with
{
(left brace)
and ending
- * with
}
(right brace)
.
- */
- public String toString() {
- try {
- Iterator keys = keys();
- StringBuffer sb = new StringBuffer("{");
- while (keys.hasNext()) {
- if (sb.length() > 1) {
- sb.append(',');
- }
- Object o = keys.next();
- sb.append(quote(o.toString()));
- sb.append(':');
- sb.append(valueToString(this.myHashMap.get(o)));
- }
- sb.append('}');
- return sb.toString();
- } catch (Exception e) {
- return null;
- }
- }
- /**
- * Make a prettyprinted JSON text of this JSONObject.
- *
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @return a printable, displayable, portable, transmittable
- * representation of the object, beginning
- * with
{
(left brace)
and ending
- * with
}
(right brace)
.
- * @throws JSONException If the object contains an invalid number.
- */
- public String toString(int indentFactor) throws JSONException {
- return toString(indentFactor, 0);
- }
- /**
- * Make a prettyprinted JSON text of this JSONObject.
- *
- * Warning: This method assumes that the data structure is acyclical.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @param indent The indentation of the top level.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with
{
(left brace)
and ending
- * with
}
(right brace)
.
- * @throws JSONException If the object contains an invalid number.
- */
- String toString(int indentFactor, int indent) throws JSONException {
- int i;
- int n = length();
- if (n == 0) {
- return "{}";
- }
- Iterator keys = keys();
- StringBuffer sb = new StringBuffer("{");
- int newindent = indent + indentFactor;
- Object o;
- if (n == 1) {
- o = keys.next();
- sb.append(quote(o.toString()));
- sb.append(": ");
- sb.append(valueToString(this.myHashMap.get(o), indentFactor,
- indent));
- } else {
- while (keys.hasNext()) {
- o = keys.next();
- if (sb.length() > 1) {
- sb.append(",\n");
- } else {
- sb.append('\n');
- }
- for (i = 0; i < newindent; i += 1) {
- sb.append(' ');
- }
- sb.append(quote(o.toString()));
- sb.append(": ");
- sb.append(valueToString(this.myHashMap.get(o), indentFactor,
- newindent));
- }
- if (sb.length() > 1) {
- sb.append('\n');
- for (i = 0; i < indent; i += 1) {
- sb.append(' ');
- }
- }
- }
- sb.append('}');
- return sb.toString();
- }
- /**
- * Make a JSON text of an Object value. If the object has an
- * value.toJSONString() method, then that method will be used to produce
- * the JSON text. The method is required to produce a strictly
- * conforming text. If the object does not contain a toJSONString
- * method (which is the most common case), then a text will be
- * produced by other means. If the value is an array or Collection,
- * then a JSONArray will be made from it and its toJSONString method
- * will be called. If the value is a MAP, then a JSONObject will be made
- * from it and its toJSONString method will be called. Otherwise, the
- * value's toString method will be called, and the result will be quoted.
- *
- *
- * Warning: This method assumes that the data structure is acyclical.
- * @param value The value to be serialized.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with
{
(left brace)
and ending
- * with
}
(right brace)
.
- * @throws JSONException If the value is or contains an invalid number.
- */
- static String valueToString(Object value) throws JSONException {
- if (value == null || value.equals(null)) {
- return "null";
- }
- if (value instanceof JSONString) {
- Object o;
- try {
- o = ((JSONString)value).toJSONString();
- } catch (Exception e) {
- throw new JSONException(e);
- }
- if (o instanceof String) {
- return (String)o;
- }
- throw new JSONException("Bad value from toJSONString: " + o);
- }
- if (value instanceof Number) {
- return numberToString((Number) value);
- }
- if (value instanceof Boolean || value instanceof JSONObject ||
- value instanceof JSONArray) {
- return value.toString();
- }
- if (value instanceof Map) {
- return new JSONObject((Map)value).toString();
- }
- if (value instanceof Collection) {
- return new JSONArray((Collection)value).toString();
- }
- if (value.getClass().isArray()) {
- return new JSONArray(value).toString();
- }
- return quote(value.toString());
- }
- /**
- * Make a prettyprinted JSON text of an object value.
- *
- * Warning: This method assumes that the data structure is acyclical.
- * @param value The value to be serialized.
- * @param indentFactor The number of spaces to add to each level of
- * indentation.
- * @param indent The indentation of the top level.
- * @return a printable, displayable, transmittable
- * representation of the object, beginning
- * with
{
(left brace)
and ending
- * with
}
(right brace)
.
- * @throws JSONException If the object contains an invalid number.
- */
- static String valueToString(Object value, int indentFactor, int indent)
- throws JSONException {
- if (value == null || value.equals(null)) {
- return "null";
- }
- try {
- if (value instanceof JSONString) {
- Object o = ((JSONString)value).toJSONString();
- if (o instanceof String) {
- return (String)o;
- }
- }
- } catch (Exception e) {
- /* forget about it */
- }
- if (value instanceof Number) {
- return numberToString((Number) value);
- }
- if (value instanceof Boolean) {
- return value.toString();
- }
- if (value instanceof JSONObject) {
- return ((JSONObject)value).toString(indentFactor, indent);
- }
- if (value instanceof JSONArray) {
- return ((JSONArray)value).toString(indentFactor, indent);
- }
- if (value instanceof Map) {
- return new JSONObject((Map)value).toString(indentFactor, indent);
- }
- if (value instanceof Collection) {
- return new JSONArray((Collection)value).toString(indentFactor, indent);
- }
- if (value.getClass().isArray()) {
- return new JSONArray(value).toString(indentFactor, indent);
- }
- return quote(value.toString());
- }
- /**
- * Write the contents of the JSONObject as JSON text to a writer.
- * For compactness, no whitespace is added.
- *
- * Warning: This method assumes that the data structure is acyclical.
- *
- * @return The writer.
- * @throws JSONException
- */
- public Writer write(Writer writer) throws JSONException {
- try {
- boolean b = false;
- Iterator keys = keys();
- writer.write('{');
- while (keys.hasNext()) {
- if (b) {
- writer.write(',');
- }
- Object k = keys.next();
- writer.write(quote(k.toString()));
- writer.write(':');
- Object v = this.myHashMap.get(k);
- if (v instanceof JSONObject) {
- ((JSONObject)v).write(writer);
- } else if (v instanceof JSONArray) {
- ((JSONArray)v).write(writer);
- } else {
- writer.write(valueToString(v));
- }
- b = true;
- }
- writer.write('}');
- return writer;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
\ No newline at end of file
diff --git a/clients/java/src/org/json/JSONString.java b/clients/java/src/org/json/JSONString.java
deleted file mode 100644
index 7f4f65b..0000000
--- a/clients/java/src/org/json/JSONString.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package org.json;
- * The
JSONString
interface allows a
toJSONString()
- * method so that a class can change the behavior of
- *
JSONObject.toString()
,
JSONArray.toString()
,
- * and
JSONWriter.value(
Object
)
. The
- *
toJSONString
method will be used instead of the default behavior
- * of using the Object's
toString()
method and quoting the result.
-public interface JSONString {
- /**
- * The
toJSONString
method allows a class to produce its own JSON
- * serialization.
- * @return A strictly syntactically correct JSON text.
- */
- public String toJSONString();
diff --git a/clients/java/src/org/json/JSONStringer.java b/clients/java/src/org/json/JSONStringer.java
deleted file mode 100644
index b68efa4..0000000
--- a/clients/java/src/org/json/JSONStringer.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package org.json;
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-The Software shall be used for Good, not Evil.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-import java.io.StringWriter;
- * JSONStringer provides a quick and convenient way of producing JSON text.
- * The texts produced strictly conform to JSON syntax rules. No whitespace is
- * added, so the results are ready for transmission or storage. Each instance of
- * JSONStringer can produce one JSON text.
- * A JSONStringer instance provides a
value
method for appending
- * values to the
- * text, and a
key
- * method for adding keys before values in objects. There are
array
- * and
endArray
methods that make and bound array values, and
- *
object
and
endObject
methods which make and bound
- * object values. All of these methods return the JSONWriter instance,
- * permitting cascade style. For example,
- * myString = new JSONStringer()
- * .object()
- * .key("JSON")
- * .value("Hello, World!")
- * .endObject()
- * .toString();
which produces the string
- * {"JSON":"Hello, World!"}
- * The first method called must be
array
or
object
.
- * There are no methods for adding commas or colons. JSONStringer adds them for
- * you. Objects and arrays can be nested up to 20 levels deep.
- * This can sometimes be easier than using a JSONObject to build a string.
- * @author JSON.org
- * @version 2
-public class JSONStringer extends JSONWriter {
- /**
- * Make a fresh JSONStringer. It can be used to build one JSON text.
- */
- public JSONStringer() {
- super(new StringWriter());
- }
- /**
- * Return the JSON text. This method is used to obtain the product of the
- * JSONStringer instance. It will return
null
if there was a
- * problem in the construction of the JSON text (such as the calls to
- *
array
were not properly balanced with calls to
- *
endArray
).
- * @return The JSON text.
- */
- public String toString() {
- return this.mode == 'd' ? this.writer.toString() : null;
- }
diff --git a/clients/java/src/org/json/JSONTokener.java b/clients/java/src/org/json/JSONTokener.java
deleted file mode 100644
index f7af8ca..0000000
--- a/clients/java/src/org/json/JSONTokener.java
+++ /dev/null
@@ -1,463 +0,0 @@
-package org.json;
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-The Software shall be used for Good, not Evil.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
- * A JSONTokener takes a source string and extracts characters and tokens from
- * it. It is used by the JSONObject and JSONArray constructors to parse
- * JSON source strings.
- * @author JSON.org
- * @version 2
-public class JSONTokener {
- /**
- * The index of the next character.
- */
- private int myIndex;
- /**
- * The source string being tokenized.
- */
- private String mySource;
- /**
- * Construct a JSONTokener from a string.
- *
- * @param s A source string.
- */
- public JSONTokener(String s) {
- this.myIndex = 0;
- this.mySource = s;
- }
- /**
- * Back up one character. This provides a sort of lookahead capability,
- * so that you can test for a digit or letter before attempting to parse
- * the next number or identifier.
- */
- public void back() {
- if (this.myIndex > 0) {
- this.myIndex -= 1;
- }
- }
- /**
- * Get the hex value of a character (base16).
- * @param c A character between '0' and '9' or between 'A' and 'F' or
- * between 'a' and 'f'.
- * @return An int between 0 and 15, or -1 if c was not a hex digit.
- */
- public static int dehexchar(char c) {
- if (c >= '0' && c <= '9') {
- return c - '0';
- }
- if (c >= 'A' && c <= 'F') {
- return c - ('A' - 10);
- }
- if (c >= 'a' && c <= 'f') {
- return c - ('a' - 10);
- }
- return -1;
- }
- /**
- * Determine if the source string still contains characters that next()
- * can consume.
- * @return true if not yet at the end of the source.
- */
- public boolean more() {
- return this.myIndex < this.mySource.length();
- }
- /**
- * Get the next character in the source string.
- *
- * @return The next character, or 0 if past the end of the source string.
- */
- public char next() {
- if (more()) {
- char c = this.mySource.charAt(this.myIndex);
- this.myIndex += 1;
- return c;
- }
- return 0;
- }
- /**
- * Consume the next character, and check that it matches a specified
- * character.
- * @param c The character to match.
- * @return The character.
- * @throws JSONException if the character does not match.
- */
- public char next(char c) throws JSONException {
- char n = next();
- if (n != c) {
- throw syntaxError("Expected '" + c + "' and instead saw '" +
- n + "'");
- }
- return n;
- }
- /**
- * Get the next n characters.
- *
- * @param n The number of characters to take.
- * @return A string of n characters.
- * @throws JSONException
- * Substring bounds error if there are not
- * n characters remaining in the source string.
- */
- public String next(int n) throws JSONException {
- int i = this.myIndex;
- int j = i + n;
- if (j >= this.mySource.length()) {
- throw syntaxError("Substring bounds error");
- }
- this.myIndex += n;
- return this.mySource.substring(i, j);
- }
- /**
- * Get the next char in the string, skipping whitespace
- * and comments (slashslash, slashstar, and hash).
- * @throws JSONException
- * @return A character, or 0 if there are no more characters.
- */
- public char nextClean() throws JSONException {
- for (;;) {
- char c = next();
- if (c == '/') {
- switch (next()) {
- case '/':
- do {
- c = next();
- } while (c != '\n' && c != '\r' && c != 0);
- break;
- case '*':
- for (;;) {
- c = next();
- if (c == 0) {
- throw syntaxError("Unclosed comment");
- }
- if (c == '*') {
- if (next() == '/') {
- break;
- }
- back();
- }
- }
- break;
- default:
- back();
- return '/';
- }
- } else if (c == '#') {
- do {
- c = next();
- } while (c != '\n' && c != '\r' && c != 0);
- } else if (c == 0 || c > ' ') {
- return c;
- }
- }
- }
- /**
- * Return the characters up to the next close quote character.
- * Backslash processing is done. The formal JSON format does not
- * allow strings in single quotes, but an implementation is allowed to
- * accept them.
- * @param quote The quoting character, either
- *
"
(double quote)
or
- *
'
(single quote)
.
- * @return A String.
- * @throws JSONException Unterminated string.
- */
- public String nextString(char quote) throws JSONException {
- char c;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = next();
- switch (c) {
- case 0:
- case '\n':
- case '\r':
- throw syntaxError("Unterminated string");
- case '\\':
- c = next();
- switch (c) {
- case 'b':
- sb.append('\b');
- break;
- case 't':
- sb.append('\t');
- break;
- case 'n':
- sb.append('\n');
- break;
- case 'f':
- sb.append('\f');
- break;
- case 'r':
- sb.append('\r');
- break;
- case 'u':
- sb.append((char)Integer.parseInt(next(4), 16));
- break;
- case 'x' :
- sb.append((char) Integer.parseInt(next(2), 16));
- break;
- default:
- sb.append(c);
- }
- break;
- default:
- if (c == quote) {
- return sb.toString();
- }
- sb.append(c);
- }
- }
- }
- /**
- * Get the text up but not including the specified character or the
- * end of line, whichever comes first.
- * @param d A delimiter character.
- * @return A string.
- */
- public String nextTo(char d) {
- StringBuffer sb = new StringBuffer();
- for (;;) {
- char c = next();
- if (c == d || c == 0 || c == '\n' || c == '\r') {
- if (c != 0) {
- back();
- }
- return sb.toString().trim();
- }
- sb.append(c);
- }
- }
- /**
- * Get the text up but not including one of the specified delimeter
- * characters or the end of line, whichever comes first.
- * @param delimiters A set of delimiter characters.
- * @return A string, trimmed.
- */
- public String nextTo(String delimiters) {
- char c;
- StringBuffer sb = new StringBuffer();
- for (;;) {
- c = next();
- if (delimiters.indexOf(c) >= 0 || c == 0 ||
- c == '\n' || c == '\r') {
- if (c != 0) {
- back();
- }
- return sb.toString().trim();
- }
- sb.append(c);
- }
- }
- /**
- * Get the next value. The value can be a Boolean, Double, Integer,
- * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
- * @throws JSONException If syntax error.
- *
- * @return An object.
- */
- public Object nextValue() throws JSONException {
- char c = nextClean();
- String s;
- switch (c) {
- case '"':
- case '\'':
- return nextString(c);
- case '{':
- back();
- return new JSONObject(this);
- case '[':
- case '(':
- back();
- return new JSONArray(this);
- }
- /*
- * Handle unquoted text. This could be the values true, false, or
- * null, or it can be a number. An implementation (such as this one)
- * is allowed to also accept non-standard forms.
- *
- * Accumulate characters until we reach the end of the text or a
- * formatting character.
- */
- StringBuffer sb = new StringBuffer();
- char b = c;
- while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
- sb.append(c);
- c = next();
- }
- back();
- /*
- * If it is true, false, or null, return the proper value.
- */
- s = sb.toString().trim();
- if (s.equals("")) {
- throw syntaxError("Missing value");
- }
- if (s.equalsIgnoreCase("true")) {
- return Boolean.TRUE;
- }
- if (s.equalsIgnoreCase("false")) {
- return Boolean.FALSE;
- }
- if (s.equalsIgnoreCase("null")) {
- return JSONObject.NULL;
- }
- /*
- * If it might be a number, try converting it. We support the 0- and 0x-
- * conventions. If a number cannot be produced, then the value will just
- * be a string. Note that the 0-, 0x-, plus, and implied string
- * conventions are non-standard. A JSON parser is free to accept
- * non-JSON forms as long as it accepts all correct JSON forms.
- */
- if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {
- if (b == '0') {
- if (s.length() > 2 &&
- (s.charAt(1) == 'x' || s.charAt(1) == 'X')) {
- try {
- return new Integer(Integer.parseInt(s.substring(2),
- 16));
- } catch (Exception e) {
- /* Ignore the error */
- }
- } else {
- try {
- return new Integer(Integer.parseInt(s, 8));
- } catch (Exception e) {
- /* Ignore the error */
- }
- }
- }
- try {
- return new Integer(s);
- } catch (Exception e) {
- try {
- return new Long(s);
- } catch (Exception f) {
- try {
- return new Double(s);
- } catch (Exception g) {
- return s;
- }
- }
- }
- }
- return s;
- }
- /**
- * Skip characters until the next character is the requested character.
- * If the requested character is not found, no characters are skipped.
- * @param to A character to skip to.
- * @return The requested character, or zero if the requested character
- * is not found.
- */
- public char skipTo(char to) {
- char c;
- int index = this.myIndex;
- do {
- c = next();
- if (c == 0) {
- this.myIndex = index;
- return c;
- }
- } while (c != to);
- back();
- return c;
- }
- /**
- * Skip characters until past the requested string.
- * If it is not found, we are left at the end of the source.
- * @param to A string to skip past.
- */
- public boolean skipPast(String to) {
- this.myIndex = this.mySource.indexOf(to, this.myIndex);
- if (this.myIndex < 0) {
- this.myIndex = this.mySource.length();
- return false;
- }
- this.myIndex += to.length();
- return true;
- }
- /**
- * Make a JSONException to signal a syntax error.
- *
- * @param message The error message.
- * @return A JSONException object, suitable for throwing
- */
- public JSONException syntaxError(String message) {
- return new JSONException(message + toString());
- }
- /**
- * Make a printable string of this JSONTokener.
- *
- * @return " at character [this.myIndex] of [this.mySource]"
- */
- public String toString() {
- return " at character " + this.myIndex + " of " + this.mySource;
- }
\ No newline at end of file
diff --git a/clients/java/src/org/json/JSONWriter.java b/clients/java/src/org/json/JSONWriter.java
deleted file mode 100644
index e1cd2e9..0000000
--- a/clients/java/src/org/json/JSONWriter.java
+++ /dev/null
@@ -1,318 +0,0 @@
-package org.json;
-import java.io.IOException;
-import java.io.Writer;
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-The Software shall be used for Good, not Evil.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
- * JSONWriter provides a quick and convenient way of producing JSON text.
- * The texts produced strictly conform to JSON syntax rules. No whitespace is
- * added, so the results are ready for transmission or storage. Each instance of
- * JSONWriter can produce one JSON text.
- * A JSONWriter instance provides a
value
method for appending
- * values to the
- * text, and a
key
- * method for adding keys before values in objects. There are
array
- * and
endArray
methods that make and bound array values, and
- *
object
and
endObject
methods which make and bound
- * object values. All of these methods return the JSONWriter instance,
- * permitting a cascade style. For example,
- * new JSONWriter(myWriter)
- * .object()
- * .key("JSON")
- * .value("Hello, World!")
- * .endObject();
which writes
- * {"JSON":"Hello, World!"}
- * The first method called must be
array
or
object
.
- * There are no methods for adding commas or colons. JSONWriter adds them for
- * you. Objects and arrays can be nested up to 20 levels deep.
- * This can sometimes be easier than using a JSONObject to build a string.
- * @author JSON.org
- * @version 2
-public class JSONWriter {
- private static final int maxdepth = 20;
- /**
- * The comma flag determines if a comma should be output before the next
- * value.
- */
- private boolean comma;
- /**
- * The current mode. Values:
- * 'a' (array),
- * 'd' (done),
- * 'i' (initial),
- * 'k' (key),
- * 'o' (object).
- */
- protected char mode;
- /**
- * The object/array stack.
- */
- private char stack[];
- /**
- * The stack top index. A value of 0 indicates that the stack is empty.
- */
- private int top;
- /**
- * The writer that will receive the output.
- */
- protected Writer writer;
- /**
- * Make a fresh JSONWriter. It can be used to build one JSON text.
- */
- public JSONWriter(Writer w) {
- this.comma = false;
- this.mode = 'i';
- this.stack = new char[maxdepth];
- this.top = 0;
- this.writer = w;
- }
- /**
- * Append a value.
- * @param s A string value.
- * @return this
- * @throws JSONException If the value is out of sequence.
- */
- private JSONWriter append(String s) throws JSONException {
- if (s == null) {
- throw new JSONException("Null pointer");
- }
- if (this.mode == 'o' || this.mode == 'a') {
- try {
- if (this.comma && this.mode == 'a') {
- this.writer.write(',');
- }
- this.writer.write(s);
- } catch (IOException e) {
- throw new JSONException(e);
- }
- if (this.mode == 'o') {
- this.mode = 'k';
- }
- this.comma = true;
- return this;
- }
- throw new JSONException("Value out of sequence.");
- }
- /**
- * Begin appending a new array. All values until the balancing
- *
endArray
will be appended to this array. The
- *
endArray
method must be called to mark the array's end.
- * @return this
- * @throws JSONException If the nesting is too deep, or if the object is
- * started in the wrong place (for example as a key or after the end of the
- * outermost array or object).
- */
- public JSONWriter array() throws JSONException {
- if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') {
- this.push('a');
- this.append("[");
- this.comma = false;
- return this;
- }
- throw new JSONException("Misplaced array.");
- }
- /**
- * End something.
- * @param m Mode
- * @param c Closing character
- * @return this
- * @throws JSONException If unbalanced.
- */
- private JSONWriter end(char m, char c) throws JSONException {
- if (this.mode != m) {
- throw new JSONException(m == 'o' ? "Misplaced endObject." :
- "Misplaced endArray.");
- }
- this.pop(m);
- try {
- this.writer.write(c);
- } catch (IOException e) {
- throw new JSONException(e);
- }
- this.comma = true;
- return this;
- }
- /**
- * End an array. This method most be called to balance calls to
- *
array
.
- * @return this
- * @throws JSONException If incorrectly nested.
- */
- public JSONWriter endArray() throws JSONException {
- return this.end('a', ']');
- }
- /**
- * End an object. This method most be called to balance calls to
- *
object
.
- * @return this
- * @throws JSONException If incorrectly nested.
- */
- public JSONWriter endObject() throws JSONException {
- return this.end('k', '}');
- }
- /**
- * Append a key. The key will be associated with the next value. In an
- * object, every value must be preceded by a key.
- * @param s A key string.
- * @return this
- * @throws JSONException If the key is out of place. For example, keys
- * do not belong in arrays or if the key is null.
- */
- public JSONWriter key(String s) throws JSONException {
- if (s == null) {
- throw new JSONException("Null key.");
- }
- if (this.mode == 'k') {
- try {
- if (this.comma) {
- this.writer.write(',');
- }
- this.writer.write(JSONObject.quote(s));
- this.writer.write(':');
- this.comma = false;
- this.mode = 'o';
- return this;
- } catch (IOException e) {
- throw new JSONException(e);
- }
- }
- throw new JSONException("Misplaced key.");
- }
- /**
- * Begin appending a new object. All keys and values until the balancing
- *
endObject
will be appended to this object. The
- *
endObject
method must be called to mark the object's end.
- * @return this
- * @throws JSONException If the nesting is too deep, or if the object is
- * started in the wrong place (for example as a key or after the end of the
- * outermost array or object).
- */
- public JSONWriter object() throws JSONException {
- if (this.mode == 'i') {
- this.mode = 'o';
- }
- if (this.mode == 'o' || this.mode == 'a') {
- this.append("{");
- this.push('k');
- this.comma = false;
- return this;
- }
- throw new JSONException("Misplaced object.");
- }
- /**
- * Pop an array or object scope.
- * @param c The scope to close.
- * @throws JSONException If nesting is wrong.
- */
- private void pop(char c) throws JSONException {
- if (this.top <= 0 || this.stack[this.top - 1] != c) {
- throw new JSONException("Nesting error.");
- }
- this.top -= 1;
- this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1];
- }
- /**
- * Push an array or object scope.
- * @param c The scope to open.
- * @throws JSONException If nesting is too deep.
- */
- private void push(char c) throws JSONException {
- if (this.top >= maxdepth) {
- throw new JSONException("Nesting too deep.");
- }
- this.stack[this.top] = c;
- this.mode = c;
- this.top += 1;
- }
- /**
- * Append either the value
true
or the value
- *
false
.
- * @param b A boolean.
- * @return this
- * @throws JSONException
- */
- public JSONWriter value(boolean b) throws JSONException {
- return this.append(b ? "true" : "false");
- }
- /**
- * Append a double value.
- * @param d A double.
- * @return this
- * @throws JSONException If the number is not finite.
- */
- public JSONWriter value(double d) throws JSONException {
- return this.value(new Double(d));
- }
- /**
- * Append a long value.
- * @param l A long.
- * @return this
- * @throws JSONException
- */
- public JSONWriter value(long l) throws JSONException {
- return this.append(Long.toString(l));
- }
- /**
- * Append an object value.
- * @param o The object to append. It can be null, or a Boolean, Number,
- * String, JSONObject, or JSONArray, or an object with a toJSONString()
- * method.
- * @return this
- * @throws JSONException If the value is out of sequence.
- */
- public JSONWriter value(Object o) throws JSONException {
- return this.append(JSONObject.valueToString(o));
- }
diff --git a/clients/javascript/lib/halcyon.js b/clients/javascript/lib/halcyon.js
deleted file mode 100644
index c872ade..0000000
--- a/clients/javascript/lib/halcyon.js
+++ /dev/null
@@ -1,42 +0,0 @@
-// The Halcyon JavaScript client library.
-// @dependency Prototype 1.6
-var Halcyon = Class.create({
- "initialize": function(uri) {
- this.uri = uri;
- },
- "request": function(method, options, callback) {
- // default options
- path = options['path'] || '/';
- params = options['params'] || {};
- headers = options['headers'] || {};
- // request URI
- url = this.uri + path;
- // perform request
- new Ajax.Request(url, {
- "method": method,
- "parameters": params,
- "requestHeaders": headers,
- "onSuccess": function(transport) {
- return callback(transport.responseText.evalJSON());
- },
- "onFailure": function(transport) {
- return callback(transport.responseText.evalJSON());
- }
- });
- },
- "get": function(options, callback) {
- return this.request('get', options, callback);
- },
- "post": function(options, callback) {
- return this.request('post', options, callback);
- },
- "put": function(options, callback) {
- return this.request('put', options, callback);
- },
- "delete": function(options, callback) {
- return this.request('delete', options, callback);
diff --git a/clients/php/example/simple-client.php b/clients/php/example/simple-client.php
deleted file mode 100644
index 7eea6aa..0000000
--- a/clients/php/example/simple-client.php
+++ /dev/null
@@ -1,18 +0,0 @@
-
get("/greet/{$name}");
-try {
- $client = new Sparrow('http://localhost:4647/');
- print($client->greet($argv[1] ? $argv[1] : 'Matt')->body . "\n");
-} catch(HalcyonError $e) {
- print("ERROR: " . $e->getMessage() . "\n");
diff --git a/clients/php/lib/halcyon.php b/clients/php/lib/halcyon.php
deleted file mode 100644
index 05c2800..0000000
--- a/clients/php/lib/halcyon.php
+++ /dev/null
@@ -1,99 +0,0 @@
-// MIT License applies to this library
-class Halcyon {
- const VERSION = "0.1.0";
- private $uri = array('host' => 'localhost', 'port' => 4647, 'scheme' => 'http', 'original' => 'http://localhost:4647/');
- private $headers = array(
- 'Content-Type' => 'application/json',
- 'User-Agent' => 'JSON/1.2.1 Compatible (en-US) Halcyon::Client/0.5.0',
- 'Connection' => 'close'
- );
- public function __construct($uri = null, $headers = null) {
- if($uri) $this->uri = array_merge(parse_url($uri), array('original' => $uri));
- if(isset($headers)) {
- foreach($headers as $key => $value) {
- $this->header($key, $value);
- }
- }
- public function header($key, $value) {
- $this->headers[$key] = $value;
- protected function get($path, $headers = array()) {
- return $this->request(array(
- 'method' => 'GET',
- 'path' => $path
- ), $headers);
- protected function post($path, $data, $headers = array()) {
- return $this->request(array(
- 'method' => 'POST',
- 'path' => $path,
- 'body' => $data
- ), array_merge($headers, array('Content-type' => 'application/x-www-form-urlencoded', 'Content-length' => strlen(http_build_query($data)))));
- protected function delete($path, $headers = array()) {
- return $this->request(array(
- 'method' => 'DELETE',
- 'path' => $path
- ), $headers);
- protected function put($path, $data, $headers = array()) {
- return $this->request(array(
- 'method' => 'PUT',
- 'path' => $path,
- 'body' => $data
- ), array_merge($headers, array('Content-type' => 'application/x-www-form-urlencoded', 'Content-length' => strlen(http_build_query($data)))));
- private function request($request, $headers = array()) {
- $host = $this->uri['host'];
- if($this->uri['scheme'] == 'https') $host = "ssl://{$host}";
- $connection = fsockopen($host, $this->uri['port']);
- if($connection) {
- // connected
- $req = "{$request['method']} {$request['path']} HTTP/1.1\r\n";
- foreach(array_merge($this->headers, $headers) as $key => $value) {
- if($value == null) continue;
- $req .= "{$key}: {$value}\r\n";
- }
- $req .= "\r\n";
- if($request['body']) $req .= http_build_query($request['body']);
- if(fwrite($connection, $req)) {
- $response = '';
- while(!feof($connection)) {
- $response .= trim(@fgets($connection, 4096))."\n"; // throw new HalcyonError("Error receiving response."));
- }
- fclose($connection); // throw new HalcyonError("Error closing connection.");
- $response = end(split("\n\n", $response, 2));
- return json_decode($response);
- } else {
- throw new HalcyonError("Request failed to send.");
- }
- } else {
- // connection failed
- throw new HalcyonError("Unable to connect to server {$this->uri['host']}:{$this->uri['port']}.");
- }
痴情的啄木鸟 · MLKL靶点介绍及实验小贴士| Abcam中文官网 4 月前 |