diff options
Diffstat (limited to 'src/org/apache/http/client/utils')
-rw-r--r-- | src/org/apache/http/client/utils/CloneUtils.java | 75 | ||||
-rw-r--r-- | src/org/apache/http/client/utils/URIUtils.java | 209 | ||||
-rw-r--r-- | src/org/apache/http/client/utils/URLEncodedUtils.java | 191 | ||||
-rw-r--r-- | src/org/apache/http/client/utils/package.html | 40 |
4 files changed, 515 insertions, 0 deletions
diff --git a/src/org/apache/http/client/utils/CloneUtils.java b/src/org/apache/http/client/utils/CloneUtils.java new file mode 100644 index 0000000..fec534b --- /dev/null +++ b/src/org/apache/http/client/utils/CloneUtils.java @@ -0,0 +1,75 @@ +/* + * $HeadURL:$ + * $Revision:$ + * $Date:$ + * + * ==================================================================== + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * <http://www.apache.org/>. + * + */ +package org.apache.http.client.utils; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * A collection of utilities to workaround limitations of Java clone framework. + */ +public class CloneUtils { + + public static Object clone(final Object obj) throws CloneNotSupportedException { + if (obj == null) { + return null; + } + if (obj instanceof Cloneable) { + Class<?> clazz = obj.getClass (); + Method m; + try { + m = clazz.getMethod("clone", (Class[]) null); + } catch (NoSuchMethodException ex) { + throw new NoSuchMethodError(ex.getMessage()); + } + try { + return m.invoke(obj, (Object []) null); + } catch (InvocationTargetException ex) { + Throwable cause = ex.getCause(); + if (cause instanceof CloneNotSupportedException) { + throw ((CloneNotSupportedException) cause); + } else { + throw new Error("Unexpected exception", cause); + } + } catch (IllegalAccessException ex) { + throw new IllegalAccessError(ex.getMessage()); + } + } else { + throw new CloneNotSupportedException(); + } + } + + /** + * This class should not be instantiated. + */ + private CloneUtils() { + } + +} diff --git a/src/org/apache/http/client/utils/URIUtils.java b/src/org/apache/http/client/utils/URIUtils.java new file mode 100644 index 0000000..1cbb9af --- /dev/null +++ b/src/org/apache/http/client/utils/URIUtils.java @@ -0,0 +1,209 @@ +/* + * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/client/utils/URIUtils.java $ + * $Revision: 653041 $ + * $Date: 2008-05-03 03:39:28 -0700 (Sat, 03 May 2008) $ + * + * ==================================================================== + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * <http://www.apache.org/>. + * + */ +package org.apache.http.client.utils; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.http.HttpHost; + +/** + * A collection of utilities for {@link URI URIs}, to workaround + * bugs within the class or for ease-of-use features. + */ +public class URIUtils { + + /** + * Constructs a {@link URI} using all the parameters. This should be + * used instead of + * {@link URI#URI(String, String, String, int, String, String, String)} + * or any of the other URI multi-argument URI constructors. + * + * See <a + * href="https://issues.apache.org/jira/browse/HTTPCLIENT-730">HTTPCLIENT-730</a> + * for more information. + * + * @param scheme + * Scheme name + * @param host + * Host name + * @param port + * Port number + * @param path + * Path + * @param query + * Query + * @param fragment + * Fragment + * + * @throws URISyntaxException + * If both a scheme and a path are given but the path is + * relative, if the URI string constructed from the given + * components violates RFC 2396, or if the authority + * component of the string is present but cannot be parsed + * as a server-based authority + */ + public static URI createURI( + final String scheme, + final String host, + int port, + final String path, + final String query, + final String fragment) throws URISyntaxException { + + StringBuilder buffer = new StringBuilder(); + if (host != null) { + if (scheme != null) { + buffer.append(scheme); + buffer.append("://"); + } + buffer.append(host); + if (port > 0) { + buffer.append(':'); + buffer.append(port); + } + } + if (path == null || !path.startsWith("/")) { + buffer.append('/'); + } + if (path != null) { + buffer.append(path); + } + if (query != null) { + buffer.append('?'); + buffer.append(query); + } + if (fragment != null) { + buffer.append('#'); + buffer.append(fragment); + } + return new URI(buffer.toString()); + } + + /** + * A convenience method for creating a new {@link URI} whose scheme, host + * and port are taken from the target host, but whose path, query and + * fragment are taken from the existing URI. The fragment is only used if + * dropFragment is false. + * + * @param uri + * Contains the path, query and fragment to use. + * @param target + * Contains the scheme, host and port to use. + * @param dropFragment + * True if the fragment should not be copied. + * + * @throws URISyntaxException + * If the resulting URI is invalid. + */ + public static URI rewriteURI( + final URI uri, + final HttpHost target, + boolean dropFragment) throws URISyntaxException { + if (uri == null) { + throw new IllegalArgumentException("URI may nor be null"); + } + if (target != null) { + return URIUtils.createURI( + target.getSchemeName(), + target.getHostName(), + target.getPort(), + uri.getRawPath(), + uri.getRawQuery(), + dropFragment ? null : uri.getRawFragment()); + } else { + return URIUtils.createURI( + null, + null, + -1, + uri.getRawPath(), + uri.getRawQuery(), + dropFragment ? null : uri.getRawFragment()); + } + } + + /** + * A convenience method for + * {@link URIUtils#rewriteURI(URI, HttpHost, boolean)} that always keeps the + * fragment. + */ + public static URI rewriteURI( + final URI uri, + final HttpHost target) throws URISyntaxException { + return rewriteURI(uri, target, false); + } + + /** + * Resolves a URI reference against a base URI. Work-around for bug in + * java.net.URI (<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>) + * + * @param baseURI the base URI + * @param reference the URI reference + * @return the resulting URI + */ + public static URI resolve(final URI baseURI, final String reference) { + return URIUtils.resolve(baseURI, URI.create(reference)); + } + + /** + * Resolves a URI reference against a base URI. Work-around for bug in + * java.net.URI (<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>) + * + * @param baseURI the base URI + * @param reference the URI reference + * @return the resulting URI + */ + public static URI resolve(final URI baseURI, URI reference){ + if (baseURI == null) { + throw new IllegalArgumentException("Base URI may nor be null"); + } + if (reference == null) { + throw new IllegalArgumentException("Reference URI may nor be null"); + } + boolean emptyReference = reference.toString().length() == 0; + if (emptyReference) { + reference = URI.create("#"); + } + URI resolved = baseURI.resolve(reference); + if (emptyReference) { + String resolvedString = resolved.toString(); + resolved = URI.create(resolvedString.substring(0, + resolvedString.indexOf('#'))); + } + return resolved; + } + + /** + * This class should not be instantiated. + */ + private URIUtils() { + } + +} diff --git a/src/org/apache/http/client/utils/URLEncodedUtils.java b/src/org/apache/http/client/utils/URLEncodedUtils.java new file mode 100644 index 0000000..8b08f90 --- /dev/null +++ b/src/org/apache/http/client/utils/URLEncodedUtils.java @@ -0,0 +1,191 @@ +/* + * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/client/utils/URLEncodedUtils.java $ + * $Revision: 655107 $ + * $Date: 2008-05-10 08:20:42 -0700 (Sat, 10 May 2008) $ + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * <http://www.apache.org/>. + * + */ + +package org.apache.http.client.utils; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Scanner; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; + +/** + * A collection of utilities for encoding URLs. + */ +public class URLEncodedUtils { + + public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; + private static final String PARAMETER_SEPARATOR = "&"; + private static final String NAME_VALUE_SEPARATOR = "="; + + /** + * Returns a list of {@link NameValuePair NameValuePairs} as built from the + * URI's query portion. For example, a URI of + * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three + * NameValuePairs, one for a=1, one for b=2, and one for c=3. + * <p> + * This is typically useful while parsing an HTTP PUT. + * + * @param uri + * uri to parse + * @param encoding + * encoding to use while parsing the query + */ + public static List <NameValuePair> parse (final URI uri, final String encoding) { + List <NameValuePair> result = Collections.emptyList(); + final String query = uri.getRawQuery(); + if (query != null && query.length() > 0) { + result = new ArrayList <NameValuePair>(); + parse(result, new Scanner(query), encoding); + } + return result; + } + + /** + * Returns a list of {@link NameValuePair NameValuePairs} as parsed from an + * {@link HttpEntity}. The encoding is taken from the entity's + * Content-Encoding header. + * <p> + * This is typically used while parsing an HTTP POST. + * + * @param entity + * The entity to parse + * @throws IOException + * If there was an exception getting the entity's data. + */ + public static List <NameValuePair> parse ( + final HttpEntity entity) throws IOException { + List <NameValuePair> result = Collections.emptyList(); + if (isEncoded(entity)) { + final String content = EntityUtils.toString(entity); + final Header encoding = entity.getContentEncoding(); + if (content != null && content.length() > 0) { + result = new ArrayList <NameValuePair>(); + parse(result, new Scanner(content), + encoding != null ? encoding.getValue() : null); + } + } + return result; + } + + /** + * Returns true if the entity's Content-Type header is + * <code>application/x-www-form-urlencoded</code>. + */ + public static boolean isEncoded (final HttpEntity entity) { + final Header contentType = entity.getContentType(); + return (contentType != null && contentType.getValue().equalsIgnoreCase(CONTENT_TYPE)); + } + + /** + * Adds all parameters within the Scanner to the list of + * <code>parameters</code>, as encoded by <code>encoding</code>. For + * example, a scanner containing the string <code>a=1&b=2&c=3</code> would + * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the + * list of parameters. + * + * @param parameters + * List to add parameters to. + * @param scanner + * Input that contains the parameters to parse. + * @param encoding + * Encoding to use when decoding the parameters. + */ + public static void parse ( + final List <NameValuePair> parameters, + final Scanner scanner, + final String encoding) { + scanner.useDelimiter(PARAMETER_SEPARATOR); + while (scanner.hasNext()) { + final String[] nameValue = scanner.next().split(NAME_VALUE_SEPARATOR); + if (nameValue.length == 0 || nameValue.length > 2) + throw new IllegalArgumentException("bad parameter"); + + final String name = decode(nameValue[0], encoding); + String value = null; + if (nameValue.length == 2) + value = decode(nameValue[1], encoding); + parameters.add(new BasicNameValuePair(name, value)); + } + } + + /** + * Returns a String that is suitable for use as an <code>application/x-www-form-urlencoded</code> + * list of parameters in an HTTP PUT or HTTP POST. + * + * @param parameters The parameters to include. + * @param encoding The encoding to use. + */ + public static String format ( + final List <? extends NameValuePair> parameters, + final String encoding) { + final StringBuilder result = new StringBuilder(); + for (final NameValuePair parameter : parameters) { + final String encodedName = encode(parameter.getName(), encoding); + final String value = parameter.getValue(); + final String encodedValue = value != null ? encode(value, encoding) : ""; + if (result.length() > 0) + result.append(PARAMETER_SEPARATOR); + result.append(encodedName); + result.append(NAME_VALUE_SEPARATOR); + result.append(encodedValue); + } + return result.toString(); + } + + private static String decode (final String content, final String encoding) { + try { + return URLDecoder.decode(content, + encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET); + } catch (UnsupportedEncodingException problem) { + throw new IllegalArgumentException(problem); + } + } + + private static String encode (final String content, final String encoding) { + try { + return URLEncoder.encode(content, + encoding != null ? encoding : HTTP.DEFAULT_CONTENT_CHARSET); + } catch (UnsupportedEncodingException problem) { + throw new IllegalArgumentException(problem); + } + } + +} diff --git a/src/org/apache/http/client/utils/package.html b/src/org/apache/http/client/utils/package.html new file mode 100644 index 0000000..7abeb93 --- /dev/null +++ b/src/org/apache/http/client/utils/package.html @@ -0,0 +1,40 @@ +<html> +<head> +<!-- +/* + * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/client/utils/package.html $ + * $Revision: 555193 $ + * $Date: 2007-07-11 00:36:47 -0700 (Wed, 11 Jul 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 + * <http://www.apache.org/>. + * + */ +--> +</head> +<body> +Helpers and utility classes for <i>HttpClient</i>. + +</body> +</html> |