code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link RFC2965Spec} instances.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li>
* </ul>
*
* @since 4.0
*/
@Immutable
public class RFC2965SpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
boolean singleHeader = params.getBooleanParameter(
CookieSpecPNames.SINGLE_COOKIE_HEADER, false);
return new RFC2965Spec(patterns, singleHeader);
} else {
return new RFC2965Spec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* <tt>"CommentURL"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965CommentUrlAttributeHandler implements CookieAttributeHandler {
public RFC2965CommentUrlAttributeHandler() {
super();
}
public void parse(final SetCookie cookie, final String commenturl)
throws MalformedCookieException {
if (cookie instanceof SetCookie2) {
SetCookie2 cookie2 = (SetCookie2) cookie;
cookie2.setCommentURL(commenturl);
}
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
return true;
}
} | Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that ignores all cookies.
*
* @since 4.1
*/
@Immutable
public class IgnoreSpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
return new IgnoreSpec();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Locale;
import java.util.StringTokenizer;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
*
* @since 4.0
*/
@Immutable
public class NetscapeDomainHandler extends BasicDomainHandler {
public NetscapeDomainHandler() {
super();
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
super.validate(cookie, origin);
// Perform Netscape Cookie draft specific validation
String host = origin.getHost();
String domain = cookie.getDomain();
if (host.contains(".")) {
int domainParts = new StringTokenizer(domain, ".").countTokens();
if (isSpecialDomain(domain)) {
if (domainParts < 2) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" violates the Netscape cookie specification for "
+ "special domains");
}
} else {
if (domainParts < 3) {
throw new CookieRestrictionViolationException("Domain attribute \""
+ domain
+ "\" 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(Locale.ENGLISH);
return ucDomain.endsWith(".COM")
|| ucDomain.endsWith(".EDU")
|| ucDomain.endsWith(".NET")
|| ucDomain.endsWith(".GOV")
|| ucDomain.endsWith(".MIL")
|| ucDomain.endsWith(".ORG")
|| ucDomain.endsWith(".INT");
}
@Override
public boolean match(Cookie cookie, CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String host = origin.getHost();
String domain = cookie.getDomain();
if (domain == null) {
return false;
}
return host.endsWith(domain);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.io.Serializable;
import java.util.Date;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* Default implementation of {@link SetCookie2}.
*
* @since 4.0
*/
@NotThreadSafe
public class BasicClientCookie2 extends BasicClientCookie implements SetCookie2, Serializable {
private static final long serialVersionUID = -7744598295706617057L;
private String commentURL;
private int[] ports;
private boolean discard;
/**
* Default Constructor taking a name and a value. The value may be null.
*
* @param name The name.
* @param value The value.
*/
public BasicClientCookie2(final String name, final String value) {
super(name, value);
}
@Override
public int[] getPorts() {
return this.ports;
}
public void setPorts(final int[] ports) {
this.ports = ports;
}
@Override
public String getCommentURL() {
return this.commentURL;
}
public void setCommentURL(final String commentURL) {
this.commentURL = commentURL;
}
public void setDiscard(boolean discard) {
this.discard = discard;
}
@Override
public boolean isPersistent() {
return !this.discard && super.isPersistent();
}
@Override
public boolean isExpired(final Date date) {
return this.discard || super.isExpired(date);
}
@Override
public Object clone() throws CloneNotSupportedException {
BasicClientCookie2 clone = (BasicClientCookie2) super.clone();
if (this.ports != null) {
clone.ports = this.ports.clone();
}
return clone;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link BrowserCompatSpec} instances.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
* </ul>
*
* @since 4.0
*/
@Immutable
public class BrowserCompatSpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
return new BrowserCompatSpec(patterns);
} else {
return new BrowserCompatSpec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.message.BasicHeaderElement;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
*
* @since 4.0
*/
@Immutable
public class NetscapeDraftHeaderParser {
public final static NetscapeDraftHeaderParser DEFAULT = new NetscapeDraftHeaderParser();
public NetscapeDraftHeaderParser() {
super();
}
public HeaderElement parseHeader(
final CharArrayBuffer buffer,
final ParserCursor cursor) throws ParseException {
if (buffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
if (cursor == null) {
throw new IllegalArgumentException("Parser cursor may not be null");
}
NameValuePair nvp = parseNameValuePair(buffer, cursor);
List<NameValuePair> params = new ArrayList<NameValuePair>();
while (!cursor.atEnd()) {
NameValuePair param = parseNameValuePair(buffer, cursor);
params.add(param);
}
return new BasicHeaderElement(
nvp.getName(),
nvp.getValue(), params.toArray(new NameValuePair[params.size()]));
}
private NameValuePair parseNameValuePair(
final CharArrayBuffer buffer, final ParserCursor cursor) {
boolean terminated = false;
int pos = cursor.getPos();
int indexFrom = cursor.getPos();
int indexTo = cursor.getUpperBound();
// Find name
String name = null;
while (pos < indexTo) {
char ch = buffer.charAt(pos);
if (ch == '=') {
break;
}
if (ch == ';') {
terminated = true;
break;
}
pos++;
}
if (pos == indexTo) {
terminated = true;
name = buffer.substringTrimmed(indexFrom, indexTo);
} else {
name = buffer.substringTrimmed(indexFrom, pos);
pos++;
}
if (terminated) {
cursor.updatePos(pos);
return new BasicNameValuePair(name, null);
}
// Find value
String value = null;
int i1 = pos;
while (pos < indexTo) {
char ch = buffer.charAt(pos);
if (ch == ';') {
terminated = true;
break;
}
pos++;
}
int i2 = pos;
// Trim leading white spaces
while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) {
i1++;
}
// Trim trailing white spaces
while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) {
i2--;
}
value = buffer.substring(i1, i2);
if (terminated) {
pos++;
}
cursor.updatePos(pos);
return new BasicNameValuePair(name, value);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collection;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.CookieSpecFactory;
import org.apache.ogt.http.cookie.params.CookieSpecPNames;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link CookieSpecFactory} implementation that creates and initializes
* {@link RFC2109Spec} instances.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
* <li>{@link org.apache.ogt.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li>
* </ul>
*
* @since 4.0
*/
@Immutable
public class RFC2109SpecFactory implements CookieSpecFactory {
public CookieSpec newInstance(final HttpParams params) {
if (params != null) {
String[] patterns = null;
Collection<?> param = (Collection<?>) params.getParameter(
CookieSpecPNames.DATE_PATTERNS);
if (param != null) {
patterns = new String[param.size()];
patterns = param.toArray(patterns);
}
boolean singleHeader = params.getBooleanParameter(
CookieSpecPNames.SINGLE_COOKIE_HEADER, false);
return new RFC2109Spec(patterns, singleHeader);
} else {
return new RFC2109Spec();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
* Cookie management functions shared by all specification.
*
*
* @since 4.0
*/
@NotThreadSafe // AbstractCookieSpec is not thread-safe
public abstract class CookieSpecBase extends AbstractCookieSpec {
protected static String getDefaultPath(final CookieOrigin origin) {
String defaultPath = origin.getPath();
int lastSlashIndex = defaultPath.lastIndexOf('/');
if (lastSlashIndex >= 0) {
if (lastSlashIndex == 0) {
//Do not remove the very first slash
lastSlashIndex = 1;
}
defaultPath = defaultPath.substring(0, lastSlashIndex);
}
return defaultPath;
}
protected static String getDefaultDomain(final CookieOrigin origin) {
return origin.getHost();
}
protected List<Cookie> parse(final HeaderElement[] elems, final CookieOrigin origin)
throws MalformedCookieException {
List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
for (HeaderElement headerelement : elems) {
String name = headerelement.getName();
String value = headerelement.getValue();
if (name == null || name.length() == 0) {
throw new MalformedCookieException("Cookie name may not be empty");
}
BasicClientCookie cookie = new BasicClientCookie(name, value);
cookie.setPath(getDefaultPath(origin));
cookie.setDomain(getDefaultDomain(origin));
// cycle through the parameters
NameValuePair[] attribs = headerelement.getParameters();
for (int j = attribs.length - 1; j >= 0; j--) {
NameValuePair attrib = attribs[j];
String s = attrib.getName().toLowerCase(Locale.ENGLISH);
cookie.setAttribute(s, attrib.getValue());
CookieAttributeHandler handler = findAttribHandler(s);
if (handler != null) {
handler.parse(cookie, attrib.getValue());
}
}
cookies.add(cookie);
}
return cookies;
}
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
for (CookieAttributeHandler handler: getAttribHandlers()) {
handler.validate(cookie, origin);
}
}
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
for (CookieAttributeHandler handler: getAttribHandlers()) {
if (!handler.match(cookie, origin)) {
return false;
}
}
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicSecureHandler extends AbstractCookieAttributeHandler {
public BasicSecureHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
cookie.setSecure(true);
}
@Override
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
return !cookie.isSecure() || origin.isSecure();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.Collections;
import java.util.List;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
/**
* CookieSpec that ignores all cookies
*
* @since 4.1
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class IgnoreSpec extends CookieSpecBase {
public int getVersion() {
return 0;
}
public List<Cookie> parse(Header header, CookieOrigin origin)
throws MalformedCookieException {
return Collections.emptyList();
}
public List<Header> formatCookies(List<Cookie> cookies) {
return Collections.emptyList();
}
public Header getVersionHeader() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SM;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Cookie specification that strives to closely mimic (mis)behavior of
* common web browser applications such as Microsoft Internet Explorer
* and Mozilla FireFox.
*
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class BrowserCompatSpec extends CookieSpecBase {
@Deprecated
protected static final String[] DATE_PATTERNS = new String[] {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.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",
};
private static final String[] DEFAULT_DATE_PATTERNS = new String[] {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.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",
};
private final String[] datepatterns;
/** Default constructor */
public BrowserCompatSpec(final String[] datepatterns) {
super();
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
} else {
this.datepatterns = DEFAULT_DATE_PATTERNS;
}
registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler());
registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
this.datepatterns));
}
/** Default constructor */
public BrowserCompatSpec() {
this(null);
}
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
String headername = header.getName();
if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
HeaderElement[] helems = header.getElements();
boolean versioned = false;
boolean netscape = false;
for (HeaderElement helem: helems) {
if (helem.getParameterByName("version") != null) {
versioned = true;
}
if (helem.getParameterByName("expires") != null) {
netscape = true;
}
}
if (netscape || !versioned) {
// Need to parse the header again, because Netscape style cookies do not correctly
// support multiple header elements (comma cannot be treated as an element separator)
NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
CharArrayBuffer buffer;
ParserCursor cursor;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
cursor = new ParserCursor(
((FormattedHeader) header).getValuePos(),
buffer.length());
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedCookieException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
cursor = new ParserCursor(0, buffer.length());
}
helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) };
}
return parse(helems, origin);
}
public List<Header> formatCookies(final List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookies may not be null");
}
if (cookies.isEmpty()) {
throw new IllegalArgumentException("List of cookies may not be empty");
}
CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
buffer.append(SM.COOKIE);
buffer.append(": ");
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
if (i > 0) {
buffer.append("; ");
}
buffer.append(cookie.getName());
buffer.append("=");
String s = cookie.getValue();
if (s != null) {
buffer.append(s);
}
}
List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
public int getVersion() {
return 0;
}
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "compatibility";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicCommentHandler extends AbstractCookieAttributeHandler {
public BasicCommentHandler() {
super();
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
cookie.setComment(value);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SM;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* This {@link CookieSpec} implementation conforms to the original draft
* specification published by Netscape Communications. It should be avoided
* unless absolutely necessary for compatibility with legacy code.
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class NetscapeDraftSpec extends CookieSpecBase {
protected static final String EXPIRES_PATTERN = "EEE, dd-MMM-yy HH:mm:ss z";
private final String[] datepatterns;
/** Default constructor */
public NetscapeDraftSpec(final String[] datepatterns) {
super();
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
} else {
this.datepatterns = new String[] { EXPIRES_PATTERN };
}
registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new NetscapeDomainHandler());
registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
this.datepatterns));
}
/** Default constructor */
public NetscapeDraftSpec() {
this(null);
}
/**
* Parses the Set-Cookie value into an array of <tt>Cookie</tt>s.
*
* <p>Syntax of the Set-Cookie HTTP Response Header:</p>
*
* <p>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.</p>
*
* <PRE>
* Set-Cookie: NAME=VALUE; expires=DATE; path=PATH; domain=DOMAIN_NAME; secure
* </PRE>
*
* <p>Please note that the Netscape draft specification does not fully conform to the HTTP
* header format. Comma character if present in <code>Set-Cookie</code> will not be treated
* as a header element separator</p>
*
* @see <a href="http://web.archive.org/web/20020803110822/http://wp.netscape.com/newsref/std/cookie_spec.html">
* The Cookie Spec.</a>
*
* @param header the <tt>Set-Cookie</tt> received from the server
* @return an array of <tt>Cookie</tt>s parsed from the Set-Cookie value
* @throws MalformedCookieException if an exception occurs during parsing
*/
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
CharArrayBuffer buffer;
ParserCursor cursor;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
cursor = new ParserCursor(
((FormattedHeader) header).getValuePos(),
buffer.length());
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedCookieException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
cursor = new ParserCursor(0, buffer.length());
}
return parse(new HeaderElement[] { parser.parseHeader(buffer, cursor) }, origin);
}
public List<Header> formatCookies(final List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookies may not be null");
}
if (cookies.isEmpty()) {
throw new IllegalArgumentException("List of cookies may not be empty");
}
CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
buffer.append(SM.COOKIE);
buffer.append(": ");
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
if (i > 0) {
buffer.append("; ");
}
buffer.append(cookie.getName());
String s = cookie.getValue();
if (s != null) {
buffer.append("=");
buffer.append(s);
}
}
List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
public int getVersion() {
return 0;
}
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "netscape";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
/**
*
* @since 4.0
*/
@Immutable
public class BasicExpiresHandler extends AbstractCookieAttributeHandler {
/** Valid date patterns */
private final String[] datepatterns;
public BasicExpiresHandler(final String[] datepatterns) {
if (datepatterns == null) {
throw new IllegalArgumentException("Array of date patterns may not be null");
}
this.datepatterns = datepatterns;
}
public void parse(final SetCookie cookie, final String value)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (value == null) {
throw new MalformedCookieException("Missing value for expires attribute");
}
try {
cookie.setExpiryDate(DateUtils.parseDate(value, this.datepatterns));
} catch (DateParseException dpe) {
throw new MalformedCookieException("Unable to parse expires attribute: "
+ value);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookiePathComparator;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.CookieSpec;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SM;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* RFC 2109 compliant {@link CookieSpec} implementation. This is an older
* version of the official HTTP state management specification superseded
* by RFC 2965.
*
* @see RFC2965Spec
*
* @since 4.0
*/
@NotThreadSafe // superclass is @NotThreadSafe
public class RFC2109Spec extends CookieSpecBase {
private final static CookiePathComparator PATH_COMPARATOR = new CookiePathComparator();
private final static String[] DATE_PATTERNS = {
DateUtils.PATTERN_RFC1123,
DateUtils.PATTERN_RFC1036,
DateUtils.PATTERN_ASCTIME
};
private final String[] datepatterns;
private final boolean oneHeader;
/** Default constructor */
public RFC2109Spec(final String[] datepatterns, boolean oneHeader) {
super();
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
} else {
this.datepatterns = DATE_PATTERNS;
}
this.oneHeader = oneHeader;
registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2109VersionHandler());
registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2109DomainHandler());
registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
this.datepatterns));
}
/** Default constructor */
public RFC2109Spec() {
this(null, false);
}
public List<Cookie> parse(final Header header, final CookieOrigin origin)
throws MalformedCookieException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE)) {
throw new MalformedCookieException("Unrecognized cookie header '"
+ header.toString() + "'");
}
HeaderElement[] elems = header.getElements();
return parse(elems, origin);
}
@Override
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
String name = cookie.getName();
if (name.indexOf(' ') != -1) {
throw new CookieRestrictionViolationException("Cookie name may not contain blanks");
}
if (name.startsWith("$")) {
throw new CookieRestrictionViolationException("Cookie name may not start with $");
}
super.validate(cookie, origin);
}
public List<Header> formatCookies(List<Cookie> cookies) {
if (cookies == null) {
throw new IllegalArgumentException("List of cookies may not be null");
}
if (cookies.isEmpty()) {
throw new IllegalArgumentException("List of cookies may not be empty");
}
if (cookies.size() > 1) {
// Create a mutable copy and sort the copy.
cookies = new ArrayList<Cookie>(cookies);
Collections.sort(cookies, PATH_COMPARATOR);
}
if (this.oneHeader) {
return doFormatOneHeader(cookies);
} else {
return doFormatManyHeaders(cookies);
}
}
private List<Header> doFormatOneHeader(final List<Cookie> cookies) {
int version = Integer.MAX_VALUE;
// Pick the lowest common denominator
for (Cookie cookie : cookies) {
if (cookie.getVersion() < version) {
version = cookie.getVersion();
}
}
CharArrayBuffer buffer = new CharArrayBuffer(40 * cookies.size());
buffer.append(SM.COOKIE);
buffer.append(": ");
buffer.append("$Version=");
buffer.append(Integer.toString(version));
for (Cookie cooky : cookies) {
buffer.append("; ");
Cookie cookie = cooky;
formatCookieAsVer(buffer, cookie, version);
}
List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
private List<Header> doFormatManyHeaders(final List<Cookie> cookies) {
List<Header> headers = new ArrayList<Header>(cookies.size());
for (Cookie cookie : cookies) {
int version = cookie.getVersion();
CharArrayBuffer buffer = new CharArrayBuffer(40);
buffer.append("Cookie: ");
buffer.append("$Version=");
buffer.append(Integer.toString(version));
buffer.append("; ");
formatCookieAsVer(buffer, cookie, version);
headers.add(new BufferedHeader(buffer));
}
return headers;
}
/**
* Return a name/value string suitable for sending in a <tt>"Cookie"</tt>
* header as defined in RFC 2109 for backward compatibility with cookie
* version 0
* @param buffer The char array buffer to use for output
* @param name The cookie name
* @param value The cookie value
* @param version The cookie version
*/
protected void formatParamAsVer(final CharArrayBuffer buffer,
final String name, final String value, int version) {
buffer.append(name);
buffer.append("=");
if (value != null) {
if (version > 0) {
buffer.append('\"');
buffer.append(value);
buffer.append('\"');
} else {
buffer.append(value);
}
}
}
/**
* Return a string suitable for sending in a <tt>"Cookie"</tt> header
* as defined in RFC 2109 for backward compatibility with cookie version 0
* @param buffer The char array buffer to use for output
* @param cookie The {@link Cookie} to be formatted as string
* @param version The version to use.
*/
protected void formatCookieAsVer(final CharArrayBuffer buffer,
final Cookie cookie, int version) {
formatParamAsVer(buffer, cookie.getName(), cookie.getValue(), version);
if (cookie.getPath() != null) {
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.PATH_ATTR)) {
buffer.append("; ");
formatParamAsVer(buffer, "$Path", cookie.getPath(), version);
}
}
if (cookie.getDomain() != null) {
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
buffer.append("; ");
formatParamAsVer(buffer, "$Domain", cookie.getDomain(), version);
}
}
}
public int getVersion() {
return 1;
}
public Header getVersionHeader() {
return null;
}
@Override
public String toString() {
return "rfc2109";
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.cookie;
import java.util.StringTokenizer;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.cookie.ClientCookie;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.cookie.CookieAttributeHandler;
import org.apache.ogt.http.cookie.CookieOrigin;
import org.apache.ogt.http.cookie.CookieRestrictionViolationException;
import org.apache.ogt.http.cookie.MalformedCookieException;
import org.apache.ogt.http.cookie.SetCookie;
import org.apache.ogt.http.cookie.SetCookie2;
/**
* <tt>"Port"</tt> cookie attribute handler for RFC 2965 cookie spec.
*
* @since 4.0
*/
@Immutable
public class RFC2965PortAttributeHandler implements CookieAttributeHandler {
public RFC2965PortAttributeHandler() {
super();
}
/**
* 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 static 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;
}
/**
* Returns <tt>true</tt> if the given port exists in the given
* ports list.
*
* @param port port of host where cookie was received from or being sent to.
* @param ports port list
* @return true returns <tt>true</tt> if the given port exists in
* the given ports list; <tt>false</tt> otherwise.
*/
private static boolean portMatch(int port, int[] ports) {
boolean portInList = false;
for (int i = 0, len = ports.length; i < len; i++) {
if (port == ports[i]) {
portInList = true;
break;
}
}
return portInList;
}
/**
* Parse cookie port attribute.
*/
public void parse(final SetCookie cookie, final String portValue)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (cookie instanceof SetCookie2) {
SetCookie2 cookie2 = (SetCookie2) cookie;
if (portValue != null && portValue.trim().length() > 0) {
int[] ports = parsePortAttribute(portValue);
cookie2.setPorts(ports);
}
}
}
/**
* Validate cookie port attribute. If the Port attribute was specified
* in header, the request port must be in cookie's port list.
*/
public void validate(final Cookie cookie, final CookieOrigin origin)
throws MalformedCookieException {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
int port = origin.getPort();
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
if (!portMatch(port, cookie.getPorts())) {
throw new CookieRestrictionViolationException(
"Port attribute violates RFC 2965: "
+ "Request port not found in cookie's port list.");
}
}
}
/**
* Match cookie port attribute. If the Port attribute is not specified
* in header, the cookie can be sent to any port. Otherwise, the request port
* must be in the cookie's port list.
*/
public boolean match(final Cookie cookie, final CookieOrigin origin) {
if (cookie == null) {
throw new IllegalArgumentException("Cookie may not be null");
}
if (origin == null) {
throw new IllegalArgumentException("Cookie origin may not be null");
}
int port = origin.getPort();
if (cookie instanceof ClientCookie
&& ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
if (cookie.getPorts() == null) {
// Invalid cookie state: port not specified
return false;
}
if (!portMatch(port, cookie.getPorts())) {
return false;
}
}
return true;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
/**
* Abstract NTLM authentication engine. The engine can be used to
* generate Type1 messages and Type3 messages in response to a
* Type2 challenge.
*
* @since 4.0
*/
public interface NTLMEngine {
/**
* Generates a Type1 message given the domain and workstation.
*
* @param domain Optional Windows domain name. Can be <code>null</code>.
* @param workstation Optional Windows workstation name. Can be
* <code>null</code>.
* @return Type1 message
* @throws NTLMEngineException
*/
String generateType1Msg(
String domain,
String workstation) throws NTLMEngineException;
/**
* Generates a Type3 message given the user credentials and the
* authentication challenge.
*
* @param username Windows user name
* @param password Password
* @param domain Windows domain name
* @param workstation Windows workstation name
* @param challenge Type2 challenge.
* @return Type3 response.
* @throws NTLMEngineException
*/
String generateType3Msg(
String username,
String password,
String domain,
String workstation,
String challenge) throws NTLMEngineException;
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.security.Key;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.util.EncodingUtils;
/**
* Provides an implementation for NTLMv1, NTLMv2, and NTLM2 Session forms of the NTLM
* authentication protocol.
*
* @since 4.1
*/
final class NTLMEngineImpl implements NTLMEngine {
// Flags we use
protected final static int FLAG_UNICODE_ENCODING = 0x00000001;
protected final static int FLAG_TARGET_DESIRED = 0x00000004;
protected final static int FLAG_NEGOTIATE_SIGN = 0x00000010;
protected final static int FLAG_NEGOTIATE_SEAL = 0x00000020;
protected final static int FLAG_NEGOTIATE_NTLM = 0x00000200;
protected final static int FLAG_NEGOTIATE_ALWAYS_SIGN = 0x00008000;
protected final static int FLAG_NEGOTIATE_NTLM2 = 0x00080000;
protected final static int FLAG_NEGOTIATE_128 = 0x20000000;
protected final static int FLAG_NEGOTIATE_KEY_EXCH = 0x40000000;
/** Secure random generator */
private static final java.security.SecureRandom RND_GEN;
static {
java.security.SecureRandom rnd = null;
try {
rnd = java.security.SecureRandom.getInstance("SHA1PRNG");
} catch (Exception e) {
}
RND_GEN = rnd;
}
/** Character encoding */
static final String DEFAULT_CHARSET = "ASCII";
/** The character set to use for encoding the credentials */
private String credentialCharset = DEFAULT_CHARSET;
/** The signature string as bytes in the default encoding */
private static byte[] SIGNATURE;
static {
byte[] bytesWithoutNull = EncodingUtils.getBytes("NTLMSSP", "ASCII");
SIGNATURE = new byte[bytesWithoutNull.length + 1];
System.arraycopy(bytesWithoutNull, 0, SIGNATURE, 0, bytesWithoutNull.length);
SIGNATURE[bytesWithoutNull.length] = (byte) 0x00;
}
/**
* 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.
*/
final String getResponseFor(String message, String username, String password,
String host, String domain) throws NTLMEngineException {
final String response;
if (message == null || message.trim().equals("")) {
response = getType1Message(host, domain);
} else {
Type2Message t2m = new Type2Message(message);
response = getType3Message(username, password, host, domain, t2m.getChallenge(), t2m
.getFlags(), t2m.getTarget(), t2m.getTargetInfo());
}
return response;
}
/**
* 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.
*/
String getType1Message(String host, String domain) throws NTLMEngineException {
return new Type1Message(domain, host).getResponse();
}
/**
* 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 NTLMEngineException
* If {@encrypt(byte[],byte[])} fails.
*/
String getType3Message(String user, String password, String host, String domain,
byte[] nonce, int type2Flags, String target, byte[] targetInformation)
throws NTLMEngineException {
return new Type3Message(domain, host, user, password, nonce, type2Flags, target,
targetInformation).getResponse();
}
/**
* @return Returns the credentialCharset.
*/
String getCredentialCharset() {
return credentialCharset;
}
/**
* @param credentialCharset
* The credentialCharset to set.
*/
void setCredentialCharset(String credentialCharset) {
this.credentialCharset = credentialCharset;
}
/** Strip dot suffix from a name */
private static String stripDotSuffix(String value) {
int index = value.indexOf(".");
if (index != -1)
return value.substring(0, index);
return value;
}
/** Convert host to standard form */
private static String convertHost(String host) {
return stripDotSuffix(host);
}
/** Convert domain to standard form */
private static String convertDomain(String domain) {
return stripDotSuffix(domain);
}
private static int readULong(byte[] src, int index) throws NTLMEngineException {
if (src.length < index + 4)
throw new NTLMEngineException("NTLM authentication - buffer too small for DWORD");
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8)
| ((src[index + 2] & 0xff) << 16) | ((src[index + 3] & 0xff) << 24);
}
private static int readUShort(byte[] src, int index) throws NTLMEngineException {
if (src.length < index + 2)
throw new NTLMEngineException("NTLM authentication - buffer too small for WORD");
return (src[index] & 0xff) | ((src[index + 1] & 0xff) << 8);
}
private static byte[] readSecurityBuffer(byte[] src, int index) throws NTLMEngineException {
int length = readUShort(src, index);
int offset = readULong(src, index + 4);
if (src.length < offset + length)
throw new NTLMEngineException(
"NTLM authentication - buffer too small for data item");
byte[] buffer = new byte[length];
System.arraycopy(src, offset, buffer, 0, length);
return buffer;
}
/** Calculate a challenge block */
private static byte[] makeRandomChallenge() throws NTLMEngineException {
if (RND_GEN == null) {
throw new NTLMEngineException("Random generator not available");
}
byte[] rval = new byte[8];
synchronized (RND_GEN) {
RND_GEN.nextBytes(rval);
}
return rval;
}
/** Calculate an NTLM2 challenge block */
private static byte[] makeNTLM2RandomChallenge() throws NTLMEngineException {
if (RND_GEN == null) {
throw new NTLMEngineException("Random generator not available");
}
byte[] rval = new byte[24];
synchronized (RND_GEN) {
RND_GEN.nextBytes(rval);
}
// 8-byte challenge, padded with zeros to 24 bytes.
Arrays.fill(rval, 8, 24, (byte) 0x00);
return rval;
}
/**
* Calculates the LM Response for the given challenge, using the specified
* password.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
*
* @return The LM Response.
*/
static byte[] getLMResponse(String password, byte[] challenge)
throws NTLMEngineException {
byte[] lmHash = lmHash(password);
return lmResponse(lmHash, challenge);
}
/**
* Calculates the NTLM Response for the given challenge, using the specified
* password.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
*
* @return The NTLM Response.
*/
static byte[] getNTLMResponse(String password, byte[] challenge)
throws NTLMEngineException {
byte[] ntlmHash = ntlmHash(password);
return lmResponse(ntlmHash, challenge);
}
/**
* Calculates the NTLMv2 Response for the given challenge, using the
* specified authentication target, username, password, target information
* block, and client challenge.
*
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The user's password.
* @param targetInformation
* The target information block from the Type 2 message.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The NTLMv2 Response.
*/
static byte[] getNTLMv2Response(String target, String user, String password,
byte[] challenge, byte[] clientChallenge, byte[] targetInformation)
throws NTLMEngineException {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
byte[] blob = createBlob(clientChallenge, targetInformation);
return lmv2Response(ntlmv2Hash, challenge, blob);
}
/**
* Calculates the LMv2 Response for the given challenge, using the specified
* authentication target, username, password, and client challenge.
*
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The LMv2 Response.
*/
static byte[] getLMv2Response(String target, String user, String password,
byte[] challenge, byte[] clientChallenge) throws NTLMEngineException {
byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
return lmv2Response(ntlmv2Hash, challenge, clientChallenge);
}
/**
* Calculates the NTLM2 Session Response for the given challenge, using the
* specified password and client challenge.
*
* @param password
* The user's password.
* @param challenge
* The Type 2 challenge from the server.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The NTLM2 Session Response. This is placed in the NTLM response
* field of the Type 3 message; the LM response field contains the
* client challenge, null-padded to 24 bytes.
*/
static byte[] getNTLM2SessionResponse(String password, byte[] challenge,
byte[] clientChallenge) throws NTLMEngineException {
try {
byte[] ntlmHash = ntlmHash(password);
// Look up MD5 algorithm (was necessary on jdk 1.4.2)
// This used to be needed, but java 1.5.0_07 includes the MD5
// algorithm (finally)
// Class x = Class.forName("gnu.crypto.hash.MD5");
// Method updateMethod = x.getMethod("update",new
// Class[]{byte[].class});
// Method digestMethod = x.getMethod("digest",new Class[0]);
// Object mdInstance = x.newInstance();
// updateMethod.invoke(mdInstance,new Object[]{challenge});
// updateMethod.invoke(mdInstance,new Object[]{clientChallenge});
// byte[] digest = (byte[])digestMethod.invoke(mdInstance,new
// Object[0]);
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(challenge);
md5.update(clientChallenge);
byte[] digest = md5.digest();
byte[] sessionHash = new byte[8];
System.arraycopy(digest, 0, sessionHash, 0, 8);
return lmResponse(ntlmHash, sessionHash);
} catch (Exception e) {
if (e instanceof NTLMEngineException)
throw (NTLMEngineException) e;
throw new NTLMEngineException(e.getMessage(), e);
}
}
/**
* Creates the LM Hash of the user's password.
*
* @param password
* The password.
*
* @return The LM Hash of the given password, used in the calculation of the
* LM Response.
*/
private static byte[] lmHash(String password) throws NTLMEngineException {
try {
byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
int length = Math.min(oemPassword.length, 14);
byte[] keyBytes = new byte[14];
System.arraycopy(oemPassword, 0, keyBytes, 0, length);
Key lowKey = createDESKey(keyBytes, 0);
Key highKey = createDESKey(keyBytes, 7);
byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowHash = des.doFinal(magicConstant);
des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highHash = des.doFinal(magicConstant);
byte[] lmHash = new byte[16];
System.arraycopy(lowHash, 0, lmHash, 0, 8);
System.arraycopy(highHash, 0, lmHash, 8, 8);
return lmHash;
} catch (Exception e) {
throw new NTLMEngineException(e.getMessage(), e);
}
}
/**
* Creates the NTLM Hash of the user's password.
*
* @param password
* The password.
*
* @return The NTLM Hash of the given password, used in the calculation of
* the NTLM Response and the NTLMv2 and LMv2 Hashes.
*/
private static byte[] ntlmHash(String password) throws NTLMEngineException {
try {
byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
MD4 md4 = new MD4();
md4.update(unicodePassword);
return md4.getOutput();
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e);
}
}
/**
* Creates the NTLMv2 Hash of the user's password.
*
* @param target
* The authentication target (i.e., domain).
* @param user
* The username.
* @param password
* The password.
*
* @return The NTLMv2 Hash, used in the calculation of the NTLMv2 and LMv2
* Responses.
*/
private static byte[] ntlmv2Hash(String target, String user, String password)
throws NTLMEngineException {
try {
byte[] ntlmHash = ntlmHash(password);
HMACMD5 hmacMD5 = new HMACMD5(ntlmHash);
// Upper case username, mixed case target!!
hmacMD5.update(user.toUpperCase().getBytes("UnicodeLittleUnmarked"));
hmacMD5.update(target.getBytes("UnicodeLittleUnmarked"));
return hmacMD5.getOutput();
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported! " + e.getMessage(), e);
}
}
/**
* Creates the LM Response from the given hash and Type 2 challenge.
*
* @param hash
* The LM or NTLM Hash.
* @param challenge
* The server challenge from the Type 2 message.
*
* @return The response (either LM or NTLM, depending on the provided hash).
*/
private static byte[] lmResponse(byte[] hash, byte[] challenge) throws NTLMEngineException {
try {
byte[] keyBytes = new byte[21];
System.arraycopy(hash, 0, keyBytes, 0, 16);
Key lowKey = createDESKey(keyBytes, 0);
Key middleKey = createDESKey(keyBytes, 7);
Key highKey = createDESKey(keyBytes, 14);
Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
des.init(Cipher.ENCRYPT_MODE, lowKey);
byte[] lowResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, middleKey);
byte[] middleResponse = des.doFinal(challenge);
des.init(Cipher.ENCRYPT_MODE, highKey);
byte[] highResponse = des.doFinal(challenge);
byte[] lmResponse = new byte[24];
System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
System.arraycopy(highResponse, 0, lmResponse, 16, 8);
return lmResponse;
} catch (Exception e) {
throw new NTLMEngineException(e.getMessage(), e);
}
}
/**
* Creates the LMv2 Response from the given hash, client data, and Type 2
* challenge.
*
* @param hash
* The NTLMv2 Hash.
* @param clientData
* The client data (blob or client challenge).
* @param challenge
* The server challenge from the Type 2 message.
*
* @return The response (either NTLMv2 or LMv2, depending on the client
* data).
*/
private static byte[] lmv2Response(byte[] hash, byte[] challenge, byte[] clientData)
throws NTLMEngineException {
HMACMD5 hmacMD5 = new HMACMD5(hash);
hmacMD5.update(challenge);
hmacMD5.update(clientData);
byte[] mac = hmacMD5.getOutput();
byte[] lmv2Response = new byte[mac.length + clientData.length];
System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
System.arraycopy(clientData, 0, lmv2Response, mac.length, clientData.length);
return lmv2Response;
}
/**
* Creates the NTLMv2 blob from the given target information block and
* client challenge.
*
* @param targetInformation
* The target information block from the Type 2 message.
* @param clientChallenge
* The random 8-byte client challenge.
*
* @return The blob, used in the calculation of the NTLMv2 Response.
*/
private static byte[] createBlob(byte[] clientChallenge, byte[] targetInformation) {
byte[] blobSignature = new byte[] { (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00 };
byte[] reserved = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
byte[] unknown1 = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 };
long time = System.currentTimeMillis();
time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
time *= 10000; // tenths of a microsecond.
// convert to little-endian byte array.
byte[] timestamp = new byte[8];
for (int i = 0; i < 8; i++) {
timestamp[i] = (byte) time;
time >>>= 8;
}
byte[] blob = new byte[blobSignature.length + reserved.length + timestamp.length + 8
+ unknown1.length + targetInformation.length];
int offset = 0;
System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
offset += blobSignature.length;
System.arraycopy(reserved, 0, blob, offset, reserved.length);
offset += reserved.length;
System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
offset += timestamp.length;
System.arraycopy(clientChallenge, 0, blob, offset, 8);
offset += 8;
System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
offset += unknown1.length;
System.arraycopy(targetInformation, 0, blob, offset, targetInformation.length);
return blob;
}
/**
* Creates a DES encryption key from the given key material.
*
* @param bytes
* A byte array containing the DES key material.
* @param offset
* The offset in the given byte array at which the 7-byte key
* material starts.
*
* @return A DES encryption key created from the key material starting at
* the specified offset in the given byte array.
*/
private static Key createDESKey(byte[] bytes, int offset) {
byte[] keyBytes = new byte[7];
System.arraycopy(bytes, offset, keyBytes, 0, 7);
byte[] material = new byte[8];
material[0] = keyBytes[0];
material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
material[7] = (byte) (keyBytes[6] << 1);
oddParity(material);
return new SecretKeySpec(material, "DES");
}
/**
* Applies odd parity to the given byte array.
*
* @param bytes
* The data whose parity bits are to be adjusted for odd parity.
*/
private static void oddParity(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^ (b >>> 4) ^ (b >>> 3)
^ (b >>> 2) ^ (b >>> 1)) & 0x01) == 0;
if (needsParity) {
bytes[i] |= (byte) 0x01;
} else {
bytes[i] &= (byte) 0xfe;
}
}
}
/** NTLM message generation, base class */
static class NTLMMessage {
/** The current response */
private byte[] messageContents = null;
/** The current output position */
private int currentOutputPosition = 0;
/** Constructor to use when message contents are not yet known */
NTLMMessage() {
}
/** Constructor to use when message contents are known */
NTLMMessage(String messageBody, int expectedType) throws NTLMEngineException {
messageContents = Base64.decodeBase64(EncodingUtils.getBytes(messageBody,
DEFAULT_CHARSET));
// Look for NTLM message
if (messageContents.length < SIGNATURE.length)
throw new NTLMEngineException("NTLM message decoding error - packet too short");
int i = 0;
while (i < SIGNATURE.length) {
if (messageContents[i] != SIGNATURE[i])
throw new NTLMEngineException(
"NTLM message expected - instead got unrecognized bytes");
i++;
}
// Check to be sure there's a type 2 message indicator next
int type = readULong(SIGNATURE.length);
if (type != expectedType)
throw new NTLMEngineException("NTLM type " + Integer.toString(expectedType)
+ " message expected - instead got type " + Integer.toString(type));
currentOutputPosition = messageContents.length;
}
/**
* Get the length of the signature and flags, so calculations can adjust
* offsets accordingly.
*/
protected int getPreambleLength() {
return SIGNATURE.length + 4;
}
/** Get the message length */
protected int getMessageLength() {
return currentOutputPosition;
}
/** Read a byte from a position within the message buffer */
protected byte readByte(int position) throws NTLMEngineException {
if (messageContents.length < position + 1)
throw new NTLMEngineException("NTLM: Message too short");
return messageContents[position];
}
/** Read a bunch of bytes from a position in the message buffer */
protected void readBytes(byte[] buffer, int position) throws NTLMEngineException {
if (messageContents.length < position + buffer.length)
throw new NTLMEngineException("NTLM: Message too short");
System.arraycopy(messageContents, position, buffer, 0, buffer.length);
}
/** Read a ushort from a position within the message buffer */
protected int readUShort(int position) throws NTLMEngineException {
return NTLMEngineImpl.readUShort(messageContents, position);
}
/** Read a ulong from a position within the message buffer */
protected int readULong(int position) throws NTLMEngineException {
return NTLMEngineImpl.readULong(messageContents, position);
}
/** Read a security buffer from a position within the message buffer */
protected byte[] readSecurityBuffer(int position) throws NTLMEngineException {
return NTLMEngineImpl.readSecurityBuffer(messageContents, position);
}
/**
* Prepares the object to create a response of the given length.
*
* @param length
* the maximum length of the response to prepare, not
* including the type and the signature (which this method
* adds).
*/
protected void prepareResponse(int maxlength, int messageType) {
messageContents = new byte[maxlength];
currentOutputPosition = 0;
addBytes(SIGNATURE);
addULong(messageType);
}
/**
* Adds the given byte to the response.
*
* @param b
* the byte to add.
*/
protected void addByte(byte b) {
messageContents[currentOutputPosition] = b;
currentOutputPosition++;
}
/**
* Adds the given bytes to the response.
*
* @param bytes
* the bytes to add.
*/
protected void addBytes(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
messageContents[currentOutputPosition] = bytes[i];
currentOutputPosition++;
}
}
/** Adds a USHORT to the response */
protected void addUShort(int value) {
addByte((byte) (value & 0xff));
addByte((byte) (value >> 8 & 0xff));
}
/** Adds a ULong to the response */
protected void addULong(int value) {
addByte((byte) (value & 0xff));
addByte((byte) (value >> 8 & 0xff));
addByte((byte) (value >> 16 & 0xff));
addByte((byte) (value >> 24 & 0xff));
}
/**
* Returns the response that has been generated after shrinking the
* array if required and base64 encodes the response.
*
* @return The response as above.
*/
String getResponse() {
byte[] resp;
if (messageContents.length > currentOutputPosition) {
byte[] tmp = new byte[currentOutputPosition];
for (int i = 0; i < currentOutputPosition; i++) {
tmp[i] = messageContents[i];
}
resp = tmp;
} else {
resp = messageContents;
}
return EncodingUtils.getAsciiString(Base64.encodeBase64(resp));
}
}
/** Type 1 message assembly class */
static class Type1Message extends NTLMMessage {
protected byte[] hostBytes;
protected byte[] domainBytes;
/** Constructor. Include the arguments the message will need */
Type1Message(String domain, String host) throws NTLMEngineException {
super();
try {
// Strip off domain name from the host!
host = convertHost(host);
// Use only the base domain name!
domain = convertDomain(domain);
hostBytes = host.getBytes("UnicodeLittleUnmarked");
domainBytes = domain.toUpperCase().getBytes("UnicodeLittleUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode unsupported: " + e.getMessage(), e);
}
}
/**
* Getting the response involves building the message before returning
* it
*/
@Override
String getResponse() {
// Now, build the message. Calculate its length first, including
// signature or type.
int finalLength = 32 + hostBytes.length + domainBytes.length;
// Set up the response. This will initialize the signature, message
// type, and flags.
prepareResponse(finalLength, 1);
// Flags. These are the complete set of flags we support.
addULong(FLAG_NEGOTIATE_NTLM | FLAG_NEGOTIATE_NTLM2 | FLAG_NEGOTIATE_SIGN
| FLAG_NEGOTIATE_SEAL |
/*
* FLAG_NEGOTIATE_ALWAYS_SIGN | FLAG_NEGOTIATE_KEY_EXCH |
*/
FLAG_UNICODE_ENCODING | FLAG_TARGET_DESIRED | FLAG_NEGOTIATE_128);
// Domain length (two times).
addUShort(domainBytes.length);
addUShort(domainBytes.length);
// Domain offset.
addULong(hostBytes.length + 32);
// Host length (two times).
addUShort(hostBytes.length);
addUShort(hostBytes.length);
// Host offset (always 32).
addULong(32);
// Host String.
addBytes(hostBytes);
// Domain String.
addBytes(domainBytes);
return super.getResponse();
}
}
/** Type 2 message class */
static class Type2Message extends NTLMMessage {
protected byte[] challenge;
protected String target;
protected byte[] targetInfo;
protected int flags;
Type2Message(String message) throws NTLMEngineException {
super(message, 2);
// Parse out the rest of the info we need from the message
// The nonce is the 8 bytes starting from the byte in position 24.
challenge = new byte[8];
readBytes(challenge, 24);
flags = readULong(20);
if ((flags & FLAG_UNICODE_ENCODING) == 0)
throw new NTLMEngineException(
"NTLM type 2 message has flags that make no sense: "
+ Integer.toString(flags));
// Do the target!
target = null;
// The TARGET_DESIRED flag is said to not have understood semantics
// in Type2 messages, so use the length of the packet to decide
// how to proceed instead
if (getMessageLength() >= 12 + 8) {
byte[] bytes = readSecurityBuffer(12);
if (bytes.length != 0) {
try {
target = new String(bytes, "UnicodeLittleUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException(e.getMessage(), e);
}
}
}
// Do the target info!
targetInfo = null;
// TARGET_DESIRED flag cannot be relied on, so use packet length
if (getMessageLength() >= 40 + 8) {
byte[] bytes = readSecurityBuffer(40);
if (bytes.length != 0) {
targetInfo = bytes;
}
}
}
/** Retrieve the challenge */
byte[] getChallenge() {
return challenge;
}
/** Retrieve the target */
String getTarget() {
return target;
}
/** Retrieve the target info */
byte[] getTargetInfo() {
return targetInfo;
}
/** Retrieve the response flags */
int getFlags() {
return flags;
}
}
/** Type 3 message assembly class */
static class Type3Message extends NTLMMessage {
// Response flags from the type2 message
protected int type2Flags;
protected byte[] domainBytes;
protected byte[] hostBytes;
protected byte[] userBytes;
protected byte[] lmResp;
protected byte[] ntResp;
/** Constructor. Pass the arguments we will need */
Type3Message(String domain, String host, String user, String password, byte[] nonce,
int type2Flags, String target, byte[] targetInformation)
throws NTLMEngineException {
// Save the flags
this.type2Flags = type2Flags;
// Strip off domain name from the host!
host = convertHost(host);
// Use only the base domain name!
domain = convertDomain(domain);
// Use the new code to calculate the responses, including v2 if that
// seems warranted.
try {
if (targetInformation != null && target != null) {
byte[] clientChallenge = makeRandomChallenge();
ntResp = getNTLMv2Response(target, user, password, nonce, clientChallenge,
targetInformation);
lmResp = getLMv2Response(target, user, password, nonce, clientChallenge);
} else {
if ((type2Flags & FLAG_NEGOTIATE_NTLM2) != 0) {
// NTLM2 session stuff is requested
byte[] clientChallenge = makeNTLM2RandomChallenge();
ntResp = getNTLM2SessionResponse(password, nonce, clientChallenge);
lmResp = clientChallenge;
// All the other flags we send (signing, sealing, key
// exchange) are supported, but they don't do anything
// at all in an
// NTLM2 context! So we're done at this point.
} else {
ntResp = getNTLMResponse(password, nonce);
lmResp = getLMResponse(password, nonce);
}
}
} catch (NTLMEngineException e) {
// This likely means we couldn't find the MD4 hash algorithm -
// fail back to just using LM
ntResp = new byte[0];
lmResp = getLMResponse(password, nonce);
}
try {
domainBytes = domain.toUpperCase().getBytes("UnicodeLittleUnmarked");
hostBytes = host.getBytes("UnicodeLittleUnmarked");
userBytes = user.getBytes("UnicodeLittleUnmarked");
} catch (java.io.UnsupportedEncodingException e) {
throw new NTLMEngineException("Unicode not supported: " + e.getMessage(), e);
}
}
/** Assemble the response */
@Override
String getResponse() {
int ntRespLen = ntResp.length;
int lmRespLen = lmResp.length;
int domainLen = domainBytes.length;
int hostLen = hostBytes.length;
int userLen = userBytes.length;
// Calculate the layout within the packet
int lmRespOffset = 64;
int ntRespOffset = lmRespOffset + lmRespLen;
int domainOffset = ntRespOffset + ntRespLen;
int userOffset = domainOffset + domainLen;
int hostOffset = userOffset + userLen;
int sessionKeyOffset = hostOffset + hostLen;
int finalLength = sessionKeyOffset + 0;
// Start the response. Length includes signature and type
prepareResponse(finalLength, 3);
// LM Resp Length (twice)
addUShort(lmRespLen);
addUShort(lmRespLen);
// LM Resp Offset
addULong(lmRespOffset);
// NT Resp Length (twice)
addUShort(ntRespLen);
addUShort(ntRespLen);
// NT Resp Offset
addULong(ntRespOffset);
// Domain length (twice)
addUShort(domainLen);
addUShort(domainLen);
// Domain offset.
addULong(domainOffset);
// User Length (twice)
addUShort(userLen);
addUShort(userLen);
// User offset
addULong(userOffset);
// Host length (twice)
addUShort(hostLen);
addUShort(hostLen);
// Host offset
addULong(hostOffset);
// 4 bytes of zeros - not sure what this is
addULong(0);
// Message length
addULong(finalLength);
// Flags. Currently: NEGOTIATE_NTLM + UNICODE_ENCODING +
// TARGET_DESIRED + NEGOTIATE_128
addULong(FLAG_NEGOTIATE_NTLM | FLAG_UNICODE_ENCODING | FLAG_TARGET_DESIRED
| FLAG_NEGOTIATE_128 | (type2Flags & FLAG_NEGOTIATE_NTLM2)
| (type2Flags & FLAG_NEGOTIATE_SIGN) | (type2Flags & FLAG_NEGOTIATE_SEAL)
| (type2Flags & FLAG_NEGOTIATE_KEY_EXCH)
| (type2Flags & FLAG_NEGOTIATE_ALWAYS_SIGN));
// Add the actual data
addBytes(lmResp);
addBytes(ntResp);
addBytes(domainBytes);
addBytes(userBytes);
addBytes(hostBytes);
return super.getResponse();
}
}
static void writeULong(byte[] buffer, int value, int offset) {
buffer[offset] = (byte) (value & 0xff);
buffer[offset + 1] = (byte) (value >> 8 & 0xff);
buffer[offset + 2] = (byte) (value >> 16 & 0xff);
buffer[offset + 3] = (byte) (value >> 24 & 0xff);
}
static int F(int x, int y, int z) {
return ((x & y) | (~x & z));
}
static int G(int x, int y, int z) {
return ((x & y) | (x & z) | (y & z));
}
static int H(int x, int y, int z) {
return (x ^ y ^ z);
}
static int rotintlft(int val, int numbits) {
return ((val << numbits) | (val >>> (32 - numbits)));
}
/**
* Cryptography support - MD4. The following class was based loosely on the
* RFC and on code found at http://www.cs.umd.edu/~harry/jotp/src/md.java.
* Code correctness was verified by looking at MD4.java from the jcifs
* library (http://jcifs.samba.org). It was massaged extensively to the
* final form found here by Karl Wright (kwright@metacarta.com).
*/
static class MD4 {
protected int A = 0x67452301;
protected int B = 0xefcdab89;
protected int C = 0x98badcfe;
protected int D = 0x10325476;
protected long count = 0L;
protected byte[] dataBuffer = new byte[64];
MD4() {
}
void update(byte[] input) {
// We always deal with 512 bits at a time. Correspondingly, there is
// a buffer 64 bytes long that we write data into until it gets
// full.
int curBufferPos = (int) (count & 63L);
int inputIndex = 0;
while (input.length - inputIndex + curBufferPos >= dataBuffer.length) {
// We have enough data to do the next step. Do a partial copy
// and a transform, updating inputIndex and curBufferPos
// accordingly
int transferAmt = dataBuffer.length - curBufferPos;
System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
count += transferAmt;
curBufferPos = 0;
inputIndex += transferAmt;
processBuffer();
}
// If there's anything left, copy it into the buffer and leave it.
// We know there's not enough left to process.
if (inputIndex < input.length) {
int transferAmt = input.length - inputIndex;
System.arraycopy(input, inputIndex, dataBuffer, curBufferPos, transferAmt);
count += transferAmt;
curBufferPos += transferAmt;
}
}
byte[] getOutput() {
// Feed pad/length data into engine. This must round out the input
// to a multiple of 512 bits.
int bufferIndex = (int) (count & 63L);
int padLen = (bufferIndex < 56) ? (56 - bufferIndex) : (120 - bufferIndex);
byte[] postBytes = new byte[padLen + 8];
// Leading 0x80, specified amount of zero padding, then length in
// bits.
postBytes[0] = (byte) 0x80;
// Fill out the last 8 bytes with the length
for (int i = 0; i < 8; i++) {
postBytes[padLen + i] = (byte) ((count * 8) >>> (8 * i));
}
// Update the engine
update(postBytes);
// Calculate final result
byte[] result = new byte[16];
writeULong(result, A, 0);
writeULong(result, B, 4);
writeULong(result, C, 8);
writeULong(result, D, 12);
return result;
}
protected void processBuffer() {
// Convert current buffer to 16 ulongs
int[] d = new int[16];
for (int i = 0; i < 16; i++) {
d[i] = (dataBuffer[i * 4] & 0xff) + ((dataBuffer[i * 4 + 1] & 0xff) << 8)
+ ((dataBuffer[i * 4 + 2] & 0xff) << 16)
+ ((dataBuffer[i * 4 + 3] & 0xff) << 24);
}
// Do a round of processing
int AA = A;
int BB = B;
int CC = C;
int DD = D;
round1(d);
round2(d);
round3(d);
A += AA;
B += BB;
C += CC;
D += DD;
}
protected void round1(int[] d) {
A = rotintlft((A + F(B, C, D) + d[0]), 3);
D = rotintlft((D + F(A, B, C) + d[1]), 7);
C = rotintlft((C + F(D, A, B) + d[2]), 11);
B = rotintlft((B + F(C, D, A) + d[3]), 19);
A = rotintlft((A + F(B, C, D) + d[4]), 3);
D = rotintlft((D + F(A, B, C) + d[5]), 7);
C = rotintlft((C + F(D, A, B) + d[6]), 11);
B = rotintlft((B + F(C, D, A) + d[7]), 19);
A = rotintlft((A + F(B, C, D) + d[8]), 3);
D = rotintlft((D + F(A, B, C) + d[9]), 7);
C = rotintlft((C + F(D, A, B) + d[10]), 11);
B = rotintlft((B + F(C, D, A) + d[11]), 19);
A = rotintlft((A + F(B, C, D) + d[12]), 3);
D = rotintlft((D + F(A, B, C) + d[13]), 7);
C = rotintlft((C + F(D, A, B) + d[14]), 11);
B = rotintlft((B + F(C, D, A) + d[15]), 19);
}
protected void round2(int[] d) {
A = rotintlft((A + G(B, C, D) + d[0] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[4] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[8] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[12] + 0x5a827999), 13);
A = rotintlft((A + G(B, C, D) + d[1] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[5] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[9] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[13] + 0x5a827999), 13);
A = rotintlft((A + G(B, C, D) + d[2] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[6] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[10] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[14] + 0x5a827999), 13);
A = rotintlft((A + G(B, C, D) + d[3] + 0x5a827999), 3);
D = rotintlft((D + G(A, B, C) + d[7] + 0x5a827999), 5);
C = rotintlft((C + G(D, A, B) + d[11] + 0x5a827999), 9);
B = rotintlft((B + G(C, D, A) + d[15] + 0x5a827999), 13);
}
protected void round3(int[] d) {
A = rotintlft((A + H(B, C, D) + d[0] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[8] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[4] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[12] + 0x6ed9eba1), 15);
A = rotintlft((A + H(B, C, D) + d[2] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[10] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[6] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[14] + 0x6ed9eba1), 15);
A = rotintlft((A + H(B, C, D) + d[1] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[9] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[5] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[13] + 0x6ed9eba1), 15);
A = rotintlft((A + H(B, C, D) + d[3] + 0x6ed9eba1), 3);
D = rotintlft((D + H(A, B, C) + d[11] + 0x6ed9eba1), 9);
C = rotintlft((C + H(D, A, B) + d[7] + 0x6ed9eba1), 11);
B = rotintlft((B + H(C, D, A) + d[15] + 0x6ed9eba1), 15);
}
}
/**
* Cryptography support - HMACMD5 - algorithmically based on various web
* resources by Karl Wright
*/
static class HMACMD5 {
protected byte[] ipad;
protected byte[] opad;
protected MessageDigest md5;
HMACMD5(byte[] key) throws NTLMEngineException {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception ex) {
// Umm, the algorithm doesn't exist - throw an
// NTLMEngineException!
throw new NTLMEngineException(
"Error getting md5 message digest implementation: " + ex.getMessage(), ex);
}
// Initialize the pad buffers with the key
ipad = new byte[64];
opad = new byte[64];
int keyLength = key.length;
if (keyLength > 64) {
// Use MD5 of the key instead, as described in RFC 2104
md5.update(key);
key = md5.digest();
keyLength = key.length;
}
int i = 0;
while (i < keyLength) {
ipad[i] = (byte) (key[i] ^ (byte) 0x36);
opad[i] = (byte) (key[i] ^ (byte) 0x5c);
i++;
}
while (i < 64) {
ipad[i] = (byte) 0x36;
opad[i] = (byte) 0x5c;
i++;
}
// Very important: update the digest with the ipad buffer
md5.reset();
md5.update(ipad);
}
/** Grab the current digest. This is the "answer". */
byte[] getOutput() {
byte[] digest = md5.digest();
md5.update(opad);
return md5.digest(digest);
}
/** Update by adding a complete array */
void update(byte[] input) {
md5.update(input);
}
/** Update the algorithm */
void update(byte[] input, int offset, int length) {
md5.update(input, offset, length);
}
}
public String generateType1Msg(
final String domain,
final String workstation) throws NTLMEngineException {
return getType1Message(workstation, domain);
}
public String generateType3Msg(
final String username,
final String password,
final String domain,
final String workstation,
final String challenge) throws NTLMEngineException {
Type2Message t2m = new Type2Message(challenge);
return getType3Message(
username,
password,
workstation,
domain,
t2m.getChallenge(),
t2m.getFlags(),
t2m.getTarget(),
t2m.getTargetInfo());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link NTLMScheme} instances configured to use the default {@link NTLMEngine}
* implementation.
*
* @since 4.1
*/
@Immutable
public class NTLMSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new NTLMScheme(new NTLMEngineImpl());
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.impl.auth;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication
* scheme.
*
* @since 4.1
*/
public class NegotiateScheme extends AuthSchemeBase {
enum State {
UNINITIATED,
CHALLENGE_RECEIVED,
TOKEN_GENERATED,
FAILED,
}
private final Log log = LogFactory.getLog(getClass());
/** Authentication process state */
private State state;
/**
* Default constructor for the Negotiate authentication scheme.
*
*/
public NegotiateScheme(final SpnegoTokenGenerator spengoGenerator, boolean stripPort) {
super();
this.state = State.UNINITIATED;
}
public NegotiateScheme(final SpnegoTokenGenerator spengoGenerator) {
this(spengoGenerator, false);
}
public NegotiateScheme() {
this(null, false);
}
/**
* Tests if the Negotiate authentication process has been completed.
*
* @return <tt>true</tt> if authorization has been processed,
* <tt>false</tt> otherwise.
*
*/
public boolean isComplete() {
return this.state == State.TOKEN_GENERATED || this.state == State.FAILED;
}
/**
* Returns textual designation of the Negotiate authentication scheme.
*
* @return <code>Negotiate</code>
*/
public String getSchemeName() {
return "Negotiate";
}
@Deprecated
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
return authenticate(credentials, request, null);
}
/**
* Produces Negotiate authorization Header based on token created by
* processChallenge.
*
* @param credentials Never used be the Negotiate scheme but must be provided to
* satisfy common-httpclient API. Credentials from JAAS will be used instead.
* @param request The request being authenticated
*
* @throws AuthenticationException if authorisation string cannot
* be generated due to an authentication failure
*
* @return an Negotiate authorisation Header
*/
@Override
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
if (state != State.CHALLENGE_RECEIVED) {
throw new IllegalStateException(
"Negotiation authentication process has not been initiated");
}
state = State.FAILED;
throw new AuthenticationException();
}
/**
* Returns the authentication parameter with the given name, if available.
*
* <p>There are no valid parameters for Negotiate authentication so this
* method always returns <tt>null</tt>.</p>
*
* @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;
}
/**
* The concept of an authentication realm is not supported by the Negotiate
* authentication scheme. Always returns <code>null</code>.
*
* @return <code>null</code>
*/
public String getRealm() {
return null;
}
/**
* Returns <tt>true</tt>.
* Negotiate authentication scheme is connection based.
*
* @return <tt>true</tt>.
*/
public boolean isConnectionBased() {
return true;
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer,
int beginIndex, int endIndex) throws MalformedChallengeException {
String challenge = buffer.substringTrimmed(beginIndex, endIndex);
if (log.isDebugEnabled()) {
log.debug("Received challenge '" + challenge + "' from the auth server");
}
log.debug("Authentication already attempted");
state = State.FAILED;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link DigestScheme} instances.
*
* @since 4.0
*/
@Immutable
public class DigestSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new DigestScheme();
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.params.AuthParams;
import org.apache.ogt.http.message.BasicHeaderValueFormatter;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.EncodingUtils;
/**
* Digest authentication scheme as defined in RFC 2617.
* Both MD5 (default) and MD5-sess are supported.
* Currently only qop=auth or no qop is supported. qop=auth-int
* is unsupported. If auth and auth-int are provided, auth is
* used.
* <p>
* Credential charset is configured via the
* {@link org.apache.ogt.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}
* parameter of the HTTP request.
* <p>
* Since the digest username is included as clear text in the generated
* Authentication header, the charset of the username must be compatible
* with the
* {@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET
* http element charset}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe
public class DigestScheme extends RFC2617Scheme {
/**
* Hexa values used when creating 32 character long digest in HTTP DigestScheme
* in case of authentication.
*
* @see #encode(byte[])
*/
private static final char[] HEXADECIMAL = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'
};
/** Whether the digest authentication process is complete */
private boolean complete;
private static final int QOP_MISSING = 0;
private static final int QOP_AUTH_INT = 1;
private static final int QOP_AUTH = 2;
private int qopVariant = QOP_MISSING;
private String lastNonce;
private long nounceCount;
private String cnonce;
private String nc;
/**
* Default constructor for the digest authetication scheme.
*/
public DigestScheme() {
super();
this.complete = false;
}
/**
* Processes the Digest challenge.
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
@Override
public void processChallenge(
final Header header) throws MalformedChallengeException {
super.processChallenge(header);
if (getParameter("realm") == null) {
throw new MalformedChallengeException("missing realm in challange");
}
if (getParameter("nonce") == null) {
throw new MalformedChallengeException("missing nonce in challange");
}
boolean unsupportedQop = false;
// qop parsing
String qop = getParameter("qop");
if (qop != null) {
StringTokenizer tok = new StringTokenizer(qop,",");
while (tok.hasMoreTokens()) {
String variant = tok.nextToken().trim();
if (variant.equals("auth")) {
qopVariant = QOP_AUTH;
break; //that's our favourite, because auth-int is unsupported
} else if (variant.equals("auth-int")) {
qopVariant = QOP_AUTH_INT;
} else {
unsupportedQop = true;
}
}
}
if (unsupportedQop && (qopVariant == QOP_MISSING)) {
throw new MalformedChallengeException("None of the qop methods is supported");
}
this.complete = true;
}
/**
* Tests if the Digest authentication process has been completed.
*
* @return <tt>true</tt> if Digest authorization has been processed,
* <tt>false</tt> otherwise.
*/
public boolean isComplete() {
String s = getParameter("stale");
if ("true".equalsIgnoreCase(s)) {
return false;
} else {
return this.complete;
}
}
/**
* Returns textual designation of the digest authentication scheme.
*
* @return <code>digest</code>
*/
public String getSchemeName() {
return "digest";
}
/**
* Returns <tt>false</tt>. Digest authentication scheme is request based.
*
* @return <tt>false</tt>.
*/
public boolean isConnectionBased() {
return false;
}
public void overrideParamter(final String name, final String value) {
getParameters().put(name, value);
}
private String getCnonce() {
if (this.cnonce == null) {
this.cnonce = createCnonce();
}
return this.cnonce;
}
private String getNc() {
if (this.nc == null) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%08x", this.nounceCount);
this.nc = sb.toString();
}
return this.nc;
}
/**
* 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 request The request being authenticated
*
* @throws org.apache.ogt.http.auth.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
*/
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
// Add method name and request-URI to the parameter map
getParameters().put("methodname", request.getRequestLine().getMethod());
getParameters().put("uri", request.getRequestLine().getUri());
String charset = getParameter("charset");
if (charset == null) {
charset = AuthParams.getCredentialCharset(request.getParams());
getParameters().put("charset", charset);
}
String digest = createDigest(credentials);
return createDigestHeader(credentials, digest);
}
private static MessageDigest createMessageDigest(
final String digAlg) throws UnsupportedDigestAlgorithmException {
try {
return MessageDigest.getInstance(digAlg);
} catch (Exception e) {
throw new UnsupportedDigestAlgorithmException(
"Unsupported algorithm in HTTP Digest authentication: "
+ digAlg);
}
}
/**
* Creates an MD5 response digest.
*
* @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 Credentials credentials) throws AuthenticationException {
// Collecting required tokens
String uri = getParameter("uri");
String realm = getParameter("realm");
String nonce = getParameter("nonce");
String method = getParameter("methodname");
String algorithm = getParameter("algorithm");
if (uri == null) {
throw new IllegalStateException("URI may not be null");
}
if (realm == null) {
throw new IllegalStateException("Realm may not be null");
}
if (nonce == null) {
throw new IllegalStateException("Nonce may not be null");
}
// Reset
this.cnonce = null;
this.nc = null;
// 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) {
throw new AuthenticationException(
"Unsupported qop in HTTP Digest authentication");
}
String digAlg = algorithm;
if (digAlg.equalsIgnoreCase("MD5-sess")) {
digAlg = "MD5";
}
if (nonce.equals(this.lastNonce)) {
this.nounceCount++;
} else {
this.nounceCount = 1;
this.lastNonce = nonce;
}
MessageDigest digester = createMessageDigest(digAlg);
String uname = credentials.getUserPrincipal().getName();
String pwd = credentials.getPassword();
// 3.2.2.2: Calculating digest
StringBuilder tmp = new StringBuilder(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.equalsIgnoreCase("MD5-sess")) {
// H( unq(username-value) ":" unq(realm-value) ":" passwd )
// ":" unq(nonce-value)
// ":" unq(cnonce-value)
algorithm = "MD5";
String cnonce = getCnonce();
String tmp2 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
StringBuilder tmp3 = new StringBuilder(
tmp2.length() + nonce.length() + cnonce.length() + 2);
tmp3.append(tmp2);
tmp3.append(':');
tmp3.append(nonce);
tmp3.append(':');
tmp3.append(cnonce);
a1 = tmp3.toString();
}
String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));
String a2 = null;
if (qopVariant == QOP_AUTH_INT) {
// 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 hasha2 = encode(digester.digest(EncodingUtils.getAsciiBytes(a2)));
// 3.2.2.1
String serverDigestValue;
if (qopVariant == QOP_MISSING) {
StringBuilder tmp2 = new StringBuilder(
hasha1.length() + nonce.length() + hasha1.length());
tmp2.append(hasha1);
tmp2.append(':');
tmp2.append(nonce);
tmp2.append(':');
tmp2.append(hasha2);
serverDigestValue = tmp2.toString();
} else {
String qopOption = getQopVariantString();
String cnonce = getCnonce();
String nc = getNc();
StringBuilder tmp2 = new StringBuilder(hasha1.length() + nonce.length()
+ nc.length() + cnonce.length() + qopOption.length() + hasha2.length() + 5);
tmp2.append(hasha1);
tmp2.append(':');
tmp2.append(nonce);
tmp2.append(':');
tmp2.append(nc);
tmp2.append(':');
tmp2.append(cnonce);
tmp2.append(':');
tmp2.append(qopOption);
tmp2.append(':');
tmp2.append(hasha2);
serverDigestValue = tmp2.toString();
}
String serverDigest =
encode(digester.digest(EncodingUtils.getAsciiBytes(serverDigestValue)));
return serverDigest;
}
/**
* Creates digest-response header as defined in RFC2617.
*
* @param credentials User credentials
* @param digest The response tag's value as String.
*
* @return The digest-response as String.
*/
private Header createDigestHeader(
final Credentials credentials,
final String digest) {
CharArrayBuffer buffer = new CharArrayBuffer(128);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Digest ");
String uri = getParameter("uri");
String realm = getParameter("realm");
String nonce = getParameter("nonce");
String opaque = getParameter("opaque");
String response = digest;
String algorithm = getParameter("algorithm");
String uname = credentials.getUserPrincipal().getName();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
params.add(new BasicNameValuePair("username", uname));
params.add(new BasicNameValuePair("realm", realm));
params.add(new BasicNameValuePair("nonce", nonce));
params.add(new BasicNameValuePair("uri", uri));
params.add(new BasicNameValuePair("response", response));
if (qopVariant != QOP_MISSING) {
params.add(new BasicNameValuePair("qop", getQopVariantString()));
params.add(new BasicNameValuePair("nc", getNc()));
params.add(new BasicNameValuePair("cnonce", getCnonce()));
}
if (algorithm != null) {
params.add(new BasicNameValuePair("algorithm", algorithm));
}
if (opaque != null) {
params.add(new BasicNameValuePair("opaque", opaque));
}
for (int i = 0; i < params.size(); i++) {
BasicNameValuePair param = params.get(i);
if (i > 0) {
buffer.append(", ");
}
boolean noQuotes = "nc".equals(param.getName()) ||
"qop".equals(param.getName());
BasicHeaderValueFormatter.DEFAULT
.formatNameValuePair(buffer, param, !noQuotes);
}
return new BufferedHeader(buffer);
}
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
* <CODE>String</CODE> according to RFC 2617.
*
* @param binaryData array containing the digest
* @return encoded MD5, or <CODE>null</CODE> if encoding failed
*/
private static String encode(byte[] binaryData) {
int n = binaryData.length;
char[] buffer = new char[n * 2];
for (int i = 0; i < n; i++) {
int low = (binaryData[i] & 0x0f);
int high = ((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 UnsupportedDigestAlgorithmException if MD5 algorithm is not supported.
*/
public static String createCnonce() {
String cnonce;
MessageDigest md5Helper = createMessageDigest("MD5");
cnonce = Long.toString(System.currentTimeMillis());
cnonce = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(cnonce)));
return cnonce;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.InvalidCredentialsException;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.NTCredentials;
import org.apache.ogt.http.impl.auth.AuthSchemeBase;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* NTLM is a proprietary authentication scheme developed by Microsoft
* and optimized for Windows platforms.
*
* @since 4.0
*/
@NotThreadSafe
public class NTLMScheme extends AuthSchemeBase {
enum State {
UNINITIATED,
CHALLENGE_RECEIVED,
MSG_TYPE1_GENERATED,
MSG_TYPE2_RECEVIED,
MSG_TYPE3_GENERATED,
FAILED,
}
private final NTLMEngine engine;
private State state;
private String challenge;
public NTLMScheme(final NTLMEngine engine) {
super();
if (engine == null) {
throw new IllegalArgumentException("NTLM engine may not be null");
}
this.engine = engine;
this.state = State.UNINITIATED;
this.challenge = null;
}
public String getSchemeName() {
return "ntlm";
}
public String getParameter(String name) {
// String parameters not supported
return null;
}
public String getRealm() {
// NTLM does not support the concept of an authentication realm
return null;
}
public boolean isConnectionBased() {
return true;
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer,
int beginIndex, int endIndex) throws MalformedChallengeException {
String challenge = buffer.substringTrimmed(beginIndex, endIndex);
if (challenge.length() == 0) {
if (this.state == State.UNINITIATED) {
this.state = State.CHALLENGE_RECEIVED;
} else {
this.state = State.FAILED;
}
this.challenge = null;
} else {
this.state = State.MSG_TYPE2_RECEVIED;
this.challenge = challenge;
}
}
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
NTCredentials ntcredentials = null;
try {
ntcredentials = (NTCredentials) credentials;
} catch (ClassCastException e) {
throw new InvalidCredentialsException(
"Credentials cannot be used for NTLM authentication: "
+ credentials.getClass().getName());
}
String response = null;
if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) {
response = this.engine.generateType1Msg(
ntcredentials.getDomain(),
ntcredentials.getWorkstation());
this.state = State.MSG_TYPE1_GENERATED;
} else if (this.state == State.MSG_TYPE2_RECEVIED) {
response = this.engine.generateType3Msg(
ntcredentials.getUserName(),
ntcredentials.getPassword(),
ntcredentials.getDomain(),
ntcredentials.getWorkstation(),
this.challenge);
this.state = State.MSG_TYPE3_GENERATED;
} else {
throw new AuthenticationException("Unexpected state: " + this.state);
}
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (isProxy()) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": NTLM ");
buffer.append(response);
return new BufferedHeader(buffer);
}
public boolean isComplete() {
return this.state == State.MSG_TYPE3_GENERATED || this.state == State.FAILED;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.InvalidCredentialsException;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.auth.params.AuthParams;
import org.apache.ogt.http.message.BufferedHeader;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.EncodingUtils;
/**
* Basic authentication scheme as defined in RFC 2617.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
* </ul>
*
* @since 4.0
*/
@NotThreadSafe
public class BasicScheme extends RFC2617Scheme {
/** Whether the basic authentication process is complete */
private boolean complete;
/**
* Default constructor for the basic authentication scheme.
*/
public BasicScheme() {
super();
this.complete = false;
}
/**
* Returns textual designation of the basic authentication scheme.
*
* @return <code>basic</code>
*/
public String getSchemeName() {
return "basic";
}
/**
* Processes the Basic challenge.
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
@Override
public void processChallenge(
final Header header) throws MalformedChallengeException {
super.processChallenge(header);
this.complete = true;
}
/**
* Tests if the Basic authentication process has been completed.
*
* @return <tt>true</tt> if Basic authorization has been processed,
* <tt>false</tt> otherwise.
*/
public boolean isComplete() {
return this.complete;
}
/**
* Returns <tt>false</tt>. Basic authentication scheme is request based.
*
* @return <tt>false</tt>.
*/
public boolean isConnectionBased() {
return false;
}
/**
* Produces basic authorization header for the given set of {@link Credentials}.
*
* @param credentials The set of credentials to be used for authentication
* @param request The request 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
*/
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
String charset = AuthParams.getCredentialCharset(request.getParams());
return authenticate(credentials, charset, isProxy());
}
/**
* Returns a basic <tt>Authorization</tt> header value for the given
* {@link Credentials} and charset.
*
* @param credentials The credentials to encode.
* @param charset The charset to use for encoding the credentials
*
* @return a basic authorization header
*/
public static Header authenticate(
final Credentials credentials,
final String charset,
boolean proxy) {
if (credentials == null) {
throw new IllegalArgumentException("Credentials may not be null");
}
if (charset == null) {
throw new IllegalArgumentException("charset may not be null");
}
StringBuilder tmp = new StringBuilder();
tmp.append(credentials.getUserPrincipal().getName());
tmp.append(":");
tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());
byte[] base64password = Base64.encodeBase64(
EncodingUtils.getBytes(tmp.toString(), charset));
CharArrayBuffer buffer = new CharArrayBuffer(32);
if (proxy) {
buffer.append(AUTH.PROXY_AUTH_RESP);
} else {
buffer.append(AUTH.WWW_AUTH_RESP);
}
buffer.append(": Basic ");
buffer.append(base64password, 0, base64password.length);
return new BufferedHeader(buffer);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.message.BasicHeaderValueParser;
import org.apache.ogt.http.message.HeaderValueParser;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract authentication scheme class that lays foundation for all
* RFC 2617 compliant authentication schemes and provides capabilities common
* to all authentication schemes defined in RFC 2617.
*
* @since 4.0
*/
@NotThreadSafe // AuthSchemeBase, params
public abstract class RFC2617Scheme extends AuthSchemeBase {
/**
* Authentication parameter map.
*/
private Map<String, String> params;
/**
* Default constructor for RFC2617 compliant authentication schemes.
*/
public RFC2617Scheme() {
super();
}
@Override
protected void parseChallenge(
final CharArrayBuffer buffer, int pos, int len) throws MalformedChallengeException {
HeaderValueParser parser = BasicHeaderValueParser.DEFAULT;
ParserCursor cursor = new ParserCursor(pos, buffer.length());
HeaderElement[] elements = parser.parseElements(buffer, cursor);
if (elements.length == 0) {
throw new MalformedChallengeException("Authentication challenge is empty");
}
this.params = new HashMap<String, String>(elements.length);
for (HeaderElement element : elements) {
this.params.put(element.getName(), element.getValue());
}
}
/**
* Returns authentication parameters map. Keys in the map are lower-cased.
*
* @return the map of authentication parameters
*/
protected Map<String, String> getParameters() {
if (this.params == null) {
this.params = new HashMap<String, String>();
}
return this.params;
}
/**
* Returns authentication parameter with the given name, if available.
*
* @param name The name of the parameter to be returned
*
* @return the parameter with the given name
*/
public String getParameter(final String name) {
if (name == null) {
throw new IllegalArgumentException("Parameter name may not be null");
}
if (this.params == null) {
return null;
}
return this.params.get(name.toLowerCase(Locale.ENGLISH));
}
/**
* Returns authentication realm. The realm may not be null.
*
* @return the authentication realm
*/
public String getRealm() {
return getParameter("realm");
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import java.io.IOException;
/**
* Abstract SPNEGO token generator. Implementations should take an Kerberos ticket and transform
* into a SPNEGO token.
* <p>
* Implementations of this interface are expected to be thread-safe.
*
* @since 4.1
*/
public interface SpnegoTokenGenerator {
byte [] generateSpnegoDERObject(byte [] kerberosTicket) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link BasicScheme} instances.
*
* @since 4.0
*/
@Immutable
public class BasicSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new BasicScheme();
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
/**
* Authentication credentials required to respond to a authentication
* challenge are invalid
*
*
* @since 4.0
*/
@Immutable
public class UnsupportedDigestAlgorithmException extends RuntimeException {
private static final long serialVersionUID = 319558534317118022L;
/**
* Creates a new UnsupportedAuthAlgoritmException with a <tt>null</tt> detail message.
*/
public UnsupportedDigestAlgorithmException() {
super();
}
/**
* Creates a new UnsupportedAuthAlgoritmException with the specified message.
*
* @param message the exception detail message
*/
public UnsupportedDigestAlgorithmException(String message) {
super(message);
}
/**
* Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public UnsupportedDigestAlgorithmException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthenticationException;
/**
* Signals NTLM protocol failure.
*
*
* @since 4.0
*/
@Immutable
public class NTLMEngineException extends AuthenticationException {
private static final long serialVersionUID = 6027981323731768824L;
public NTLMEngineException() {
super();
}
/**
* Creates a new NTLMEngineException with the specified message.
*
* @param message the exception detail message
*/
public NTLMEngineException(String message) {
super(message);
}
/**
* Creates a new NTLMEngineException with the specified detail message and cause.
*
* @param message the exception detail message
* @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt>
* if the cause is unavailable, unknown, or not a <tt>Throwable</tt>
*/
public NTLMEngineException(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.annotation.Immutable;
import org.apache.ogt.http.auth.AuthScheme;
import org.apache.ogt.http.auth.AuthSchemeFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) authentication
* scheme factory.
*
* @since 4.1
*/
@Immutable
public class NegotiateSchemeFactory implements AuthSchemeFactory {
private final SpnegoTokenGenerator spengoGenerator;
private final boolean stripPort;
public NegotiateSchemeFactory(final SpnegoTokenGenerator spengoGenerator, boolean stripPort) {
super();
this.spengoGenerator = spengoGenerator;
this.stripPort = stripPort;
}
public NegotiateSchemeFactory(final SpnegoTokenGenerator spengoGenerator) {
this(spengoGenerator, false);
}
public NegotiateSchemeFactory() {
this(null, false);
}
public AuthScheme newInstance(final HttpParams params) {
return new NegotiateScheme(this.spengoGenerator, this.stripPort);
}
public boolean isStripPort() {
return stripPort;
}
public SpnegoTokenGenerator getSpengoGenerator() {
return spengoGenerator;
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.auth;
import org.apache.ogt.http.FormattedHeader;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.annotation.NotThreadSafe;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.auth.AuthenticationException;
import org.apache.ogt.http.auth.ContextAwareAuthScheme;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.MalformedChallengeException;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract authentication scheme class that serves as a basis
* for all authentication schemes supported by HttpClient. This class
* defines the generic way of parsing an authentication challenge. It
* does not make any assumptions regarding the format of the challenge
* nor does it impose any specific way of responding to that challenge.
*
*
* @since 4.0
*/
@NotThreadSafe // proxy
public abstract class AuthSchemeBase implements ContextAwareAuthScheme {
/**
* Flag whether authenticating against a proxy.
*/
private boolean proxy;
public AuthSchemeBase() {
super();
}
/**
* Processes the given challenge token. Some authentication schemes
* may involve multiple challenge-response exchanges. Such schemes must be able
* to maintain the state information when dealing with sequential challenges
*
* @param header the challenge header
*
* @throws MalformedChallengeException is thrown if the authentication challenge
* is malformed
*/
public void processChallenge(final Header header) throws MalformedChallengeException {
if (header == null) {
throw new IllegalArgumentException("Header may not be null");
}
String authheader = header.getName();
if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) {
this.proxy = false;
} else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) {
this.proxy = true;
} else {
throw new MalformedChallengeException("Unexpected header name: " + authheader);
}
CharArrayBuffer buffer;
int pos;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader) header).getBuffer();
pos = ((FormattedHeader) header).getValuePos();
} else {
String s = header.getValue();
if (s == null) {
throw new MalformedChallengeException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
pos = 0;
}
while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
int beginIndex = pos;
while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) {
pos++;
}
int endIndex = pos;
String s = buffer.substring(beginIndex, endIndex);
if (!s.equalsIgnoreCase(getSchemeName())) {
throw new MalformedChallengeException("Invalid scheme identifier: " + s);
}
parseChallenge(buffer, pos, buffer.length());
}
@SuppressWarnings("deprecation")
public Header authenticate(
final Credentials credentials,
final HttpRequest request,
final HttpContext context) throws AuthenticationException {
return authenticate(credentials, request);
}
protected abstract void parseChallenge(
CharArrayBuffer buffer, int beginIndex, int endIndex) throws MalformedChallengeException;
/**
* Returns <code>true</code> if authenticating against a proxy, <code>false</code>
* otherwise.
*
* @return <code>true</code> if authenticating against a proxy, <code>false</code>
* otherwise
*/
public boolean isProxy() {
return this.proxy;
}
@Override
public String toString() {
return getSchemeName();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a direct connection using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
* @since 4.0
*/
public class ManagerConnectDirect {
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args) throws Exception {
HttpHost target = new HttpHost("www.apache.org", 80, "http");
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target);
HttpRoute route = new HttpRoute
(target, null, supportedSchemes.getScheme(target).isLayered());
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, params);
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println("closing connection");
conn.close();
} finally {
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception ex) {
System.out.println("problem during shutdown");
ex.printStackTrace();
}
}
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a direct connection using
* {@link ClientConnectionOperator ClientConnectionOperator}.
* This exemplifies the <i>opening</i> of the connection only.
* The subsequent message exchange in this example should not
* be used as a template.
*
* @since 4.0
*/
public class OperatorConnectDirect {
public static void main(String[] args) throws Exception {
HttpHost target = new HttpHost("jakarta.apache.org", 80, "http");
// some general setup
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
// one operator can be used for many connections
ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
OperatedClientConnection conn = scop.createConnection();
try {
System.out.println("opening connection to " + target);
scop.openConnection(conn, target, null, ctx, params);
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
} finally {
System.out.println("closing connection");
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionOperator;
import org.apache.ogt.http.conn.OperatedClientConnection;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.ssl.SSLSocketFactory;
import org.apache.ogt.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionOperator ClientConnectionOperator}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
* @since 4.0
*/
public class OperatorConnectProxy {
public static void main(String[] args) throws Exception {
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
// some general setup
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http",
80, PlainSocketFactory.getSocketFactory()));
supportedSchemes.register(new Scheme("https",
443, SSLSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
// one operator can be used for many connections
ClientConnectionOperator scop = new DefaultClientConnectionOperator(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
OperatedClientConnection conn = scop.createConnection();
try {
System.out.println("opening connection to " + proxy);
scop.openConnection(conn, proxy, null, ctx, params);
// Creates a request to tunnel a connection.
// For details see RFC 2817, section 5.2
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority,
HttpVersion.HTTP_1_1);
// In a real application, request interceptors should be used
// to add the required headers.
connect.addHeader("Host", authority);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
printResponseHeader(connected);
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
// Now we have a tunnel to the target. As we will be creating a
// layered TLS/SSL socket immediately afterwards, updating the
// connection with the new target is optional - but good style.
// The scheme part of the target is already "https", though the
// connection is not yet switched to the TLS/SSL protocol.
conn.update(null, target, false, params);
System.out.println("layering secure connection");
scop.updateSecureConnection(conn, target, ctx, params);
// finally we have the secure connection and can send the request
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
printResponseHeader(rsp);
System.out.println("----------------------------------------");
} finally {
System.out.println("closing connection");
conn.close();
}
}
private final static void printResponseHeader(HttpResponse rsp) {
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i=0; i<headers.length; i++) {
System.out.println(headers[i]);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.conn;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.ssl.SSLSocketFactory;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
/**
* How to open a secure connection through a proxy using
* {@link ClientConnectionManager ClientConnectionManager}.
* This exemplifies the <i>opening</i> of the connection only.
* The message exchange, both subsequently and for tunnelling,
* should not be used as a template.
*
* @since 4.0
*/
public class ManagerConnectProxy {
/**
* Main entry point to this example.
*
* @param args ignored
*/
public final static void main(String[] args) throws Exception {
// make sure to use a proxy that supports CONNECT
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8666, "http");
// Register the "http" and "https" protocol schemes, they are
// required by the default operator to look up socket factories.
SchemeRegistry supportedSchemes = new SchemeRegistry();
supportedSchemes.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
supportedSchemes.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
// Prepare parameters.
// Since this example doesn't use the full core framework,
// only few parameters are actually required.
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUseExpectContinue(params, false);
ClientConnectionManager clcm = new ThreadSafeClientConnManager(supportedSchemes);
HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);
req.addHeader("Host", target.getHostName());
HttpContext ctx = new BasicHttpContext();
System.out.println("preparing route to " + target + " via " + proxy);
HttpRoute route = new HttpRoute
(target, null, proxy,
supportedSchemes.getScheme(target).isLayered());
System.out.println("requesting connection for " + route);
ClientConnectionRequest connRequest = clcm.requestConnection(route, null);
ManagedClientConnection conn = connRequest.getConnection(0, null);
try {
System.out.println("opening connection");
conn.open(route, ctx, params);
String authority = target.getHostName() + ":" + target.getPort();
HttpRequest connect = new BasicHttpRequest("CONNECT", authority, HttpVersion.HTTP_1_1);
connect.addHeader("Host", authority);
System.out.println("opening tunnel to " + target);
conn.sendRequestHeader(connect);
// there is no request entity
conn.flush();
System.out.println("receiving confirmation for tunnel");
HttpResponse connected = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(connected.getStatusLine());
Header[] headers = connected.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
int status = connected.getStatusLine().getStatusCode();
if ((status < 200) || (status > 299)) {
System.out.println("unexpected status code " + status);
System.exit(1);
}
System.out.println("receiving response body (ignored)");
conn.receiveResponseEntity(connected);
conn.tunnelTarget(false, params);
System.out.println("layering secure connection");
conn.layerProtocol(ctx, params);
// finally we have the secure connection and can send the request
System.out.println("sending request");
conn.sendRequestHeader(req);
// there is no request entity
conn.flush();
System.out.println("receiving response header");
HttpResponse rsp = conn.receiveResponseHeader();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println("closing connection");
conn.close();
} finally {
if (conn.isOpen()) {
System.out.println("shutting down connection");
try {
conn.shutdown();
} catch (Exception ex) {
System.out.println("problem during shutdown");
ex.printStackTrace();
}
}
System.out.println("releasing connection");
clcm.releaseConnection(conn, -1, null);
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.ssl.SSLSocketFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* This example demonstrates how to create secure connections with a custom SSL
* context.
*/
public class ClientCustomSSL {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("my.keystore"));
try {
trustStore.load(instream, "nopassword".toCharArray());
} finally {
try { instream.close(); } catch (Exception ignore) {}
}
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", 443, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);
HttpGet httpget = new HttpGet("https://localhost/");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import java.security.Principal;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpUriRequest;
import org.apache.ogt.http.client.params.AuthPolicy;
import org.apache.ogt.http.impl.auth.NegotiateSchemeFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* Kerberos auth example.
*
* <p><b>Information</b></p>
* <p>For the best compatibility use Java >= 1.6 as it supports SPNEGO authentication more
completely.</p>
* <p><em>NegotiateSchemeFactory</em> kas two custom methods</p>
* <p><em>#setStripPort(boolean)</em> - default is false, with strip the port off the Kerberos
* service name if true. Found useful with JBoss Negotiation. Can be used with Java >= 1.5</p>
* <p><em>#setSpengoGenerator(SpnegoTokenGenerator)</em> - default is null, class to use to wrap
* kerberos token. An example is in contrib - <em>org.apache.ogt.http.contrib.auth.BouncySpnegoTokenGenerator</em>.
* Requires use of <a href="http://www.bouncycastle.org/java.html">bouncy castle libs</a>.
* Useful with Java 1.5.
* </p>
* <p><b>Addtional Config Files</b></p>
* <p>Two files control how Java uses/configures Kerberos. Very basic examples are below. There
* is a large amount of information on the web.</p>
* <p><a href="http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html">http://java.sun.com/j2se/1.5.0/docs/guide/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html</a>
* <p><b>krb5.conf</b></p>
* <pre>
* [libdefaults]
* default_realm = AD.EXAMPLE.NET
* udp_preference_limit = 1
* [realms]
* AD.EXAMPLE.NET = {
* kdc = AD.EXAMPLE.NET
* }
* DEV.EXAMPLE.NET = {
* kdc = DEV.EXAMPLE.NET
* }
* [domain_realms]
* .ad.example.net = AD.EXAMPLE.NET
* ad.example.net = AD.EXAMPLE.NET
* .dev.example.net = DEV.EXAMPLE.NET
* dev.example.net = DEV.EXAMPLE.NET
* gb.dev.example.net = DEV.EXAMPLE.NET
* .gb.dev.example.net = DEV.EXAMPLE.NET
* </pre>
* <b>login.conf</b>
* <pre>
*com.sun.security.jgss.login {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
*
*com.sun.security.jgss.initiate {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
*
*com.sun.security.jgss.accept {
* com.sun.security.auth.module.Krb5LoginModule required client=TRUE useTicketCache=true debug=true;
*};
* </pre>
* <p><b>Windows specific configuration</b></p>
* <p>
* The registry key <em>allowtgtsessionkey</em> should be added, and set correctly, to allow
* session keys to be sent in the Kerberos Ticket-Granting Ticket.
* </p>
* <p>
* On the Windows Server 2003 and Windows 2000 SP4, here is the required registry setting:
* </p>
* <pre>
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\Parameters
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
* <p>
* Here is the location of the registry setting on Windows XP SP2:
* </p>
* <pre>
* HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\Kerberos\
* Value Name: allowtgtsessionkey
* Value Type: REG_DWORD
* Value: 0x01
* </pre>
*
* @since 4.1
*/
public class ClientKerberosAuthentication {
public static void main(String[] args) throws Exception {
System.setProperty("java.security.auth.login.config", "login.conf");
System.setProperty("java.security.krb5.conf", "krb5.conf");
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
NegotiateSchemeFactory nsf = new NegotiateSchemeFactory();
// nsf.setStripPort(false);
// nsf.setSpengoGenerator(new BouncySpnegoTokenGenerator());
httpclient.getAuthSchemes().register(AuthPolicy.SPNEGO, nsf);
Credentials use_jaas_creds = new Credentials() {
public String getPassword() {
return null;
}
public Principal getUserPrincipal() {
return null;
}
};
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
HttpUriRequest request = new HttpGet("http://kerberoshost/");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
System.out.println("----------------------------------------");
// This ensures the connection gets released back to the manager
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.client.ResponseHandler;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.BasicResponseHandler;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This example demonstrates the use of the {@link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.concurrent.TimeUnit;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.util.EntityUtils;
/**
* Example demonstrating how to evict expired and idle connections
* from the connection pool.
*/
public class ClientEvictExpiredConnections {
public static void main(String[] args) throws Exception {
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);
try {
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://jakarta.apache.org/",
"http://jakarta.apache.org/commons/",
"http://jakarta.apache.org/commons/httpclient/",
"http://svn.apache.org/viewvc/jakarta/httpcomponents/"
};
IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
connEvictor.start();
for (int i = 0; i < urisToGet.length; i++) {
String requestURI = urisToGet[i];
HttpGet req = new HttpGet(requestURI);
System.out.println("executing request " + requestURI);
HttpResponse rsp = httpclient.execute(req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
EntityUtils.consume(entity);
}
// Sleep 10 sec and let the connection evictor do its job
Thread.sleep(20000);
// Shut down the evictor thread
connEvictor.shutdown();
connEvictor.join();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
public static class IdleConnectionEvictor extends Thread {
private final ClientConnectionManager connMgr;
private volatile boolean shutdown;
public IdleConnectionEvictor(ClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 5 sec
connMgr.closeIdleConnections(5, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
// terminate
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.File;
import java.io.FileInputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.entity.InputStreamEntity;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* Example how to use unbuffered chunk-encoded POST request.
*/
public class ClientChunkEncodedPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
File file = new File(args[0]);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
// It may be more appropriate to use FileEntity class in this particular
// instance but we are using a more generic InputStreamEntity to demonstrate
// the capability to stream out data from any arbitrary source
//
// FileEntity entity = new FileEntity(file, "binary/octet-stream");
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
EntityUtils.consume(resEntity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request directly using {@link HttpClient}.
*
* @since 4.0
*/
public class ClientExecuteDirect {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.params.ConnRoutePNames;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request via proxy using {@link HttpClient}.
*
* @since 4.0
*/
public class ClientExecuteProxy {
public static void main(String[] args)throws Exception {
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpHost target = new HttpHost("issues.apache.org", 443, "https");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via " + proxy);
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.params.ConnRoutePNames;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request
* over a secure connection tunneled through an authenticating proxy.
*/
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 8080),
new UsernamePasswordCredentials("username", "password"));
HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");
HttpHost proxy = new HttpHost("localhost", 8080);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This example demonstrates how to abort an HTTP method before its normal completion.
*/
public class ClientAbortMethod {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");
// Do not feel like reading the response body
// Call abort on the request object
httpget.abort();
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.entity.HttpEntityWrapper;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* Demonstration of the use of protocol interceptors to transparently
* modify properties of HTTP messages sent / received by the HTTP client.
* <p/>
* In this particular case HTTP client is made capable of transparent content
* GZIP compression by adding two protocol interceptors: a request interceptor
* that adds 'Accept-Encoding: gzip' header to all outgoing requests and
* a response interceptor that automatically expands compressed response
* entities by wrapping them with a uncompressing decorator class. The use of
* protocol interceptors makes content compression completely transparent to
* the consumer of the {@link org.apache.ogt.http.client.HttpClient HttpClient}
* interface.
*/
public class ClientGZipContentCompression {
public final static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
if (!request.containsHeader("Accept-Encoding")) {
request.addHeader("Accept-Encoding", "gzip");
}
}
});
httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(response.getLastHeader("Content-Encoding"));
System.out.println(response.getLastHeader("Content-Length"));
System.out.println("----------------------------------------");
HttpEntity entity = response.getEntity();
if (entity != null) {
String content = EntityUtils.toString(entity);
System.out.println(content);
System.out.println("----------------------------------------");
System.out.println("Uncompressed size: "+content.length());
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
/**
* This example demonstrates the recommended way of using API to make sure
* the underlying connection gets released back to the connection manager.
*/
public class ClientConnectionRelease {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("http://www.apache.org/");
// Execute HTTP request
System.out.println("executing request " + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("----------------------------------------");
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to bother about connection release
if (entity != null) {
InputStream instream = entity.getContent();
try {
instream.read();
// do something useful with the response
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection immediately.
httpget.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
try { instream.close(); } catch (Exception ignore) {}
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example that performs GETs from multiple threads.
*
*/
public class ClientMultiThreadedExecution {
public static void main(String[] args) throws Exception {
// Create an HttpClient with the ThreadSafeClientConnManager.
// This connection manager must be used if more than one thread will
// be using the HttpClient.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
cm.setMaxTotal(100);
HttpClient httpclient = new DefaultHttpClient(cm);
try {
// create an array of URIs to perform GETs on
String[] urisToGet = {
"http://hc.apache.org/",
"http://hc.apache.org/httpcomponents-core-ga/",
"http://hc.apache.org/httpcomponents-client-ga/",
"http://svn.apache.org/viewvc/httpcomponents/"
};
// create a thread for each URI
GetThread[] threads = new GetThread[urisToGet.length];
for (int i = 0; i < threads.length; i++) {
HttpGet httpget = new HttpGet(urisToGet[i]);
threads[i] = new GetThread(httpclient, httpget, i + 1);
}
// start the threads
for (int j = 0; j < threads.length; j++) {
threads[j].start();
}
// join the threads
for (int j = 0; j < threads.length; j++) {
threads[j].join();
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
/**
* A thread that performs a GET.
*/
static class GetThread extends Thread {
private final HttpClient httpClient;
private final HttpContext context;
private final HttpGet httpget;
private final int id;
public GetThread(HttpClient httpClient, HttpGet httpget, int id) {
this.httpClient = httpClient;
this.context = new BasicHttpContext();
this.httpget = httpget;
this.id = id;
}
/**
* Executes the GetMethod and prints some status information.
*/
@Override
public void run() {
System.out.println(id + " - about to get something from " + httpget.getURI());
try {
// execute the method
HttpResponse response = httpClient.execute(httpget, context);
System.out.println(id + " - get executed");
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
System.out.println(id + " - " + bytes.length + " bytes read");
}
} catch (Exception e) {
httpget.abort();
System.out.println(id + " - error: " + e);
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.EntityUtils;
/**
* How to send a request via SOCKS proxy using {@link HttpClient}.
*
* @since 4.1
*/
public class ClientExecuteSOCKS {
public static void main(String[] args)throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getParams().setParameter("socks.host", "mysockshost");
httpclient.getParams().setParameter("socks.port", 1234);
httpclient.getConnectionManager().getSchemeRegistry().register(
new Scheme("http", 80, new MySchemeSocketFactory()));
HttpHost target = new HttpHost("www.apache.org", 80, "http");
HttpGet req = new HttpGet("/");
System.out.println("executing request to " + target + " via SOCKS proxy");
HttpResponse rsp = httpclient.execute(target, req);
HttpEntity entity = rsp.getEntity();
System.out.println("----------------------------------------");
System.out.println(rsp.getStatusLine());
Header[] headers = rsp.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
static class MySchemeSocketFactory implements SchemeSocketFactory {
public Socket createSocket(final HttpParams params) throws IOException {
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
String proxyHost = (String) params.getParameter("socks.host");
Integer proxyPort = (Integer) params.getParameter("socks.port");
InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
public Socket connectSocket(
final Socket socket,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
if (remoteAddress == null) {
throw new IllegalArgumentException("Remote address may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
Socket sock;
if (socket != null) {
sock = socket;
} else {
sock = createSocket(params);
}
if (localAddress != null) {
sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
sock.bind(localAddress);
}
int timeout = HttpConnectionParams.getConnectionTimeout(params);
try {
sock.connect(remoteAddress, timeout);
} catch (SocketTimeoutException ex) {
throw new ConnectTimeoutException("Connect to " + remoteAddress.getHostName() + "/"
+ remoteAddress.getAddress() + " timed out");
}
return sock;
}
public boolean isSecure(final Socket sock) throws IllegalArgumentException {
return false;
}
}
} | Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.AuthState;
import org.apache.ogt.http.auth.Credentials;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientInteractiveAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
// Create local execution context
HttpContext localContext = new BasicHttpContext();
HttpGet httpget = new HttpGet("http://localhost/test");
boolean trying = true;
while (trying) {
System.out.println("executing request " + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget, localContext);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
// Consume response content
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
int sc = response.getStatusLine().getStatusCode();
AuthState authState = null;
if (sc == HttpStatus.SC_UNAUTHORIZED) {
// Target host authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
}
if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
// Proxy authentication required
authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
}
if (authState != null) {
System.out.println("----------------------------------------");
AuthScope authScope = authState.getAuthScope();
System.out.println("Please provide credentials");
System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
System.out.println(" Realm: " + authScope.getRealm());
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter username: ");
String user = console.readLine();
System.out.print("Enter password: ");
String password = console.readLine();
if (user != null && user.length() > 0) {
Credentials creds = new UsernamePasswordCredentials(user, password);
httpclient.getCredentialsProvider().setCredentials(authScope, creds);
trying = true;
} else {
trying = false;
}
} else {
trying = false;
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.auth.BasicScheme;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using BASIC scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
*/
public class ClientPreemptiveBasicAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local
// auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.AuthCache;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.impl.auth.DigestScheme;
import org.apache.ogt.http.impl.client.BasicAuthCache;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* An example of HttpClient can be customized to authenticate
* preemptively using DIGEST scheme.
* <b/>
* Generally, preemptive authentication can be considered less
* secure than a response to an authentication challenge
* and therefore discouraged.
*/
public class ClientPreemptiveDigestAuthentication {
public static void main(String[] args) throws Exception {
HttpHost targetHost = new HttpHost("localhost", 80, "http");
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("username", "password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local
// auth cache
DigestScheme digestAuth = new DigestScheme();
// Suppose we already know the realm name
digestAuth.overrideParamter("realm", "some realm");
// Suppose we already know the expected nonce value
digestAuth.overrideParamter("nonce", "whatever");
authCache.put(targetHost, digestAuth);
// Add AuthCache to the execution context
BasicHttpContext localcontext = new BasicHttpContext();
localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
HttpGet httpget = new HttpGet("/");
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("to target: " + targetHost);
for (int i = 0; i < 3; i++) {
HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.ogt.http.examples.client;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.auth.AuthScope;
import org.apache.ogt.http.auth.UsernamePasswordCredentials;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.List;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.CookieStore;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.protocol.ClientContext;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.impl.client.BasicCookieStore;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.util.EntityUtils;
/**
* This example demonstrates the use of a local HTTP context populated with
* custom attributes.
*/
public class ClientCustomContext {
public final static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
System.out.println("Local cookie: " + cookies.get(i));
}
// Consume response content
EntityUtils.consume(entity);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.client;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.client.entity.UrlEncodedFormEntity;
import org.apache.ogt.http.client.methods.HttpGet;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.cookie.Cookie;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.message.BasicNameValuePair;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.EntityUtils;
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
System.out.println("Login form get: " + response.getStatusLine());
EntityUtils.consume(entity);
System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.conn.ssl;
/**
* Some X509 certificates to test against.
* <p/>
* Note: some of these certificates have Japanese Kanji in the "subjectAlt"
* field (UTF8). Not sure how realistic that is since international characters
* in DNS names usually get translated into ASCII using "xn--" style DNS
* entries. "xn--i8s592g.co.jp" is what FireFox actually uses when trying to
* find 花子.co.jp. So would the CN in the certificate contain
* "xn--i8s592g.co.jp" in ASCII, or "花子.co.jp" in UTF8? (Both?)
*
* @since 11-Dec-2006
*/
public class CertificatesToPlayWith {
/**
* CN=foo.com
*/
public final static byte[] X509_FOO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aQMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzE0MVoXDTI4MTEwNTE1MzE0MVowgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
"hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
"FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
"yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQC3jRmEya6sQCkmieULcvx8zz1euCk9\n" +
"fSez7BEtki8+dmfMXe3K7sH0lI8f4jJR0rbSCjpmCQLYmzC3NxBKeJOW0RcjNBpO\n" +
"c2JlGO9auXv2GDP4IYiXElLJ6VSqc8WvDikv0JmCCWm0Zga+bZbR/EWN5DeEtFdF\n" +
"815CLpJZNcYwiYwGy/CVQ7w2TnXlG+mraZOz+owr+cL6J/ZesbdEWfjoS1+cUEhE\n" +
"HwlNrAu8jlZ2UqSgskSWlhYdMTAP9CPHiUv9N7FcT58Itv/I4fKREINQYjDpvQcx\n" +
"SaTYb9dr5sB4WLNglk7zxDtM80H518VvihTcP7FHL+Gn6g4j5fkI98+S\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=花子.co.jp
*/
public final static byte[] X509_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIESzCCAzOgAwIBAgIJAIz+EYMBU6aTMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1NDIxNVoXDTI4MTEwNTE1NDIxNVowgakx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEVMBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkB\n" +
"FhZqdWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n" +
"MIIBCgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjU\n" +
"g4pNjYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQc\n" +
"wHf0ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t\n" +
"7iu1JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAn\n" +
"AxK6q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArD\n" +
"qUYxqJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwG\n" +
"CWCGSAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV\n" +
"HQ4EFgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLS\n" +
"rNuzA1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBALJ27i3okV/KvlDp6KMID3gd\n" +
"ITl68PyItzzx+SquF8gahMh016NX73z/oVZoVUNdftla8wPUB1GwIkAnGkhQ9LHK\n" +
"spBdbRiCj0gMmLCsX8SrjFvr7cYb2cK6J/fJe92l1tg/7Y4o7V/s4JBe/cy9U9w8\n" +
"a0ctuDmEBCgC784JMDtT67klRfr/2LlqWhlOEq7pUFxRLbhpquaAHSOjmIcWnVpw\n" +
"9BsO7qe46hidgn39hKh1WjKK2VcL/3YRsC4wUi0PBtFW6ScMCuMhgIRXSPU55Rae\n" +
"UIlOdPjjr1SUNWGId1rD7W16Scpwnknn310FNxFMHVI0GTGFkNdkilNCFJcIoRA=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=foo.com, subjectAlt=bar.com
*/
public final static byte[] X509_FOO_BAR = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEXDCCA0SgAwIBAgIJAIz+EYMBU6aRMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzYyOVoXDTI4MTEwNTE1MzYyOVowgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCG\n" +
"SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
"FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
"A1LKh6YNPg0wEgYDVR0RBAswCYIHYmFyLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEA\n" +
"dQyprNZBmVnvuVWjV42sey/PTfkYShJwy1j0/jcFZR/ypZUovpiHGDO1DgL3Y3IP\n" +
"zVQ26uhUsSw6G0gGRiaBDe/0LUclXZoJzXX1qpS55OadxW73brziS0sxRgGrZE/d\n" +
"3g5kkio6IED47OP6wYnlmZ7EKP9cqjWwlnvHnnUcZ2SscoLNYs9rN9ccp8tuq2by\n" +
"88OyhKwGjJfhOudqfTNZcDzRHx4Fzm7UsVaycVw4uDmhEHJrAsmMPpj/+XRK9/42\n" +
"2xq+8bc6HojdtbCyug/fvBZvZqQXSmU8m8IVcMmWMz0ZQO8ee3QkBHMZfCy7P/kr\n" +
"VbWx/uETImUu+NZg22ewEw==\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=foo.com, subjectAlt=bar.com, subjectAlt=花子.co.jp
* (hanako.co.jp in kanji)
*/
public final static byte[] X509_FOO_BAR_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEajCCA1KgAwIBAgIJAIz+EYMBU6aSMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE1MzgxM1oXDTI4MTEwNTE1MzgxM1owgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxMHZm9vLmNvbTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaOBnjCBmzAJBgNVHRMEAjAAMCwGCWCG\n" +
"SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
"FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
"A1LKh6YNPg0wIAYDVR0RBBkwF4IHYmFyLmNvbYIM6Iqx5a2QLmNvLmpwMA0GCSqG\n" +
"SIb3DQEBBQUAA4IBAQBeZs7ZIYyKtdnVxVvdLgwySEPOE4pBSXii7XYv0Q9QUvG/\n" +
"++gFGQh89HhABzA1mVUjH5dJTQqSLFvRfqTHqLpxSxSWqMHnvRM4cPBkIRp/XlMK\n" +
"PlXadYtJLPTgpbgvulA1ickC9EwlNYWnowZ4uxnfsMghW4HskBqaV+PnQ8Zvy3L0\n" +
"12c7Cg4mKKS5pb1HdRuiD2opZ+Hc77gRQLvtWNS8jQvd/iTbh6fuvTKfAOFoXw22\n" +
"sWIKHYrmhCIRshUNohGXv50m2o+1w9oWmQ6Dkq7lCjfXfUB4wIbggJjpyEtbNqBt\n" +
"j4MC2x5rfsLKKqToKmNE7pFEgqwe8//Aar1b+Qj+\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=*.foo.com
*/
public final static byte[] X509_WILD_FOO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIESDCCAzCgAwIBAgIJAIz+EYMBU6aUMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTU1NVoXDTI4MTEwNTE2MTU1NVowgaYx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
"dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
"CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
"jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
"ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
"JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
"q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
"qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCG\n" +
"SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4E\n" +
"FgQUnxR3vz86tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuz\n" +
"A1LKh6YNPg0wDQYJKoZIhvcNAQEFBQADggEBAH0ipG6J561UKUfgkeW7GvYwW98B\n" +
"N1ZooWX+JEEZK7+Pf/96d3Ij0rw9ACfN4bpfnCq0VUNZVSYB+GthQ2zYuz7tf/UY\n" +
"A6nxVgR/IjG69BmsBl92uFO7JTNtHztuiPqBn59pt+vNx4yPvno7zmxsfI7jv0ww\n" +
"yfs+0FNm7FwdsC1k47GBSOaGw38kuIVWqXSAbL4EX9GkryGGOKGNh0qvAENCdRSB\n" +
"G9Z6tyMbmfRY+dLSh3a9JwoEcBUso6EWYBakLbq4nG/nvYdYvG9ehrnLVwZFL82e\n" +
"l3Q/RK95bnA6cuRClGusLad0e6bjkBzx/VQ3VarDEpAkTLUGVAa0CLXtnyc=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=*.co.jp
*/
public final static byte[] X509_WILD_CO_JP = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIERjCCAy6gAwIBAgIJAIz+EYMBU6aVMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTYzMFoXDTI4MTEwNTE2MTYzMFowgaQx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAxQHKi5jby5qcDElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n" +
"ggEBAMhjr5aCPoyp0R1iroWAfnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2B\n" +
"lYho4O84X244QrZTRl8kQbYtxnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRy\n" +
"zerA/ZtrlUqf+lKo0uWcocxeRc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY\n" +
"07hNKXAb2odnVqgzcYiDkLV8ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8\n" +
"BqnGd87xQU3FVZI4tbtkB+KzjD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiV\n" +
"JTxpTKqym93whYk93l3ocEe55c0CAwEAAaN7MHkwCQYDVR0TBAIwADAsBglghkgB\n" +
"hvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0OBBYE\n" +
"FJ8Ud78/OrbKOIJCSBYs2tDLXofYMB8GA1UdIwQYMBaAFHua2o+QmU5S0qzbswNS\n" +
"yoemDT4NMA0GCSqGSIb3DQEBBQUAA4IBAQA0sWglVlMx2zNGvUqFC73XtREwii53\n" +
"CfMM6mtf2+f3k/d8KXhLNySrg8RRlN11zgmpPaLtbdTLrmG4UdAHHYr8O4y2BBmE\n" +
"1cxNfGxxechgF8HX10QV4dkyzp6Z1cfwvCeMrT5G/V1pejago0ayXx+GPLbWlNeZ\n" +
"S+Kl0m3p+QplXujtwG5fYcIpaGpiYraBLx3Tadih39QN65CnAh/zRDhLCUzKyt9l\n" +
"UGPLEUDzRHMPHLnSqT1n5UU5UDRytbjJPXzF+l/+WZIsanefWLsxnkgAuZe/oMMF\n" +
"EJMryEzOjg4Tfuc5qM0EXoPcQ/JlheaxZ40p2IyHqbsWV4MRYuFH4bkM\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=*.foo.com, subjectAlt=*.bar.com, subjectAlt=*.花子.co.jp
* (*.hanako.co.jp in kanji)
*/
public final static byte[] X509_WILD_FOO_BAR_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEcDCCA1igAwIBAgIJAIz+EYMBU6aWMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTczMVoXDTI4MTEwNTE2MTczMVowgaYx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIEwhNYXJ5bGFuZDEUMBIGA1UEBxMLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoTDmh0dHBjb21wb25lbnRzMRowGAYDVQQLExF0ZXN0IGNl\n" +
"cnRpZmljYXRlczESMBAGA1UEAxQJKi5mb28uY29tMSUwIwYJKoZIhvcNAQkBFhZq\n" +
"dWxpdXNkYXZpZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
"CgKCAQEAyGOvloI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pN\n" +
"jYGViGjg7zhfbjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0\n" +
"ZHLN6sD9m2uVSp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1\n" +
"JVjTuE0pcBvah2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6\n" +
"q/wGqcZ3zvFBTcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYx\n" +
"qJUlPGlMqrKb3fCFiT3eXehwR7nlzQIDAQABo4GiMIGfMAkGA1UdEwQCMAAwLAYJ\n" +
"YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud\n" +
"DgQWBBSfFHe/Pzq2yjiCQkgWLNrQy16H2DAfBgNVHSMEGDAWgBR7mtqPkJlOUtKs\n" +
"27MDUsqHpg0+DTAkBgNVHREEHTAbggkqLmJhci5jb22CDiou6Iqx5a2QLmNvLmpw\n" +
"MA0GCSqGSIb3DQEBBQUAA4IBAQBobWC+D5/lx6YhX64CwZ26XLjxaE0S415ajbBq\n" +
"DK7lz+Rg7zOE3GsTAMi+ldUYnhyz0wDiXB8UwKXl0SDToB2Z4GOgqQjAqoMmrP0u\n" +
"WB6Y6dpkfd1qDRUzI120zPYgSdsXjHW9q2H77iV238hqIU7qCvEz+lfqqWEY504z\n" +
"hYNlknbUnR525ItosEVwXFBJTkZ3Yw8gg02c19yi8TAh5Li3Ad8XQmmSJMWBV4XK\n" +
"qFr0AIZKBlg6NZZFf/0dP9zcKhzSriW27bY0XfzA6GSiRDXrDjgXq6baRT6YwgIg\n" +
"pgJsDbJtZfHnV1nd3M6zOtQPm1TIQpNmMMMd/DPrGcUQerD3\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* CN=foo.com, CN=bar.com, CN=花子.co.jp
*/
public final static byte[] X509_THREE_CNS_FOO_BAR_HANAKO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEbzCCA1egAwIBAgIJAIz+EYMBU6aXMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MTk0NVoXDTI4MTEwNTE2MTk0NVowgc0x\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
"cnRpZmljYXRlczEQMA4GA1UEAwwHZm9vLmNvbTEQMA4GA1UEAwwHYmFyLmNvbTEV\n" +
"MBMGA1UEAwwM6Iqx5a2QLmNvLmpwMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyGOv\n" +
"loI+jKnRHWKuhYB+cTIEwZhagKJ0f3rIY8WNgujB7PlpgpjUg4pNjYGViGjg7zhf\n" +
"bjhCtlNGXyRBti3GcaHiBIIP5nyCNn+Ay8tSWGo5v5Zc8BQcwHf0ZHLN6sD9m2uV\n" +
"Sp/6UqjS5ZyhzF5FzvvUo3xw8fecdnStXQfHhkBnLpTjHE5t7iu1JVjTuE0pcBva\n" +
"h2dWqDNxiIOQtXyKW8Sag1YxaunxQGqRNykSFiEJindxOSAnAxK6q/wGqcZ3zvFB\n" +
"TcVVkji1u2QH4rOMP3PPxAIMkB8ONkdHTco1DmbE6BfDHArDqUYxqJUlPGlMqrKb\n" +
"3fCFiT3eXehwR7nlzQIDAQABo3sweTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQf\n" +
"Fh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86\n" +
"tso4gkJIFiza0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0w\n" +
"DQYJKoZIhvcNAQEFBQADggEBAGuZb8ai1NO2j4v3y9TLZvd5s0vh5/TE7n7RX+8U\n" +
"y37OL5k7x9nt0mM1TyAKxlCcY+9h6frue8MemZIILSIvMrtzccqNz0V1WKgA+Orf\n" +
"uUrabmn+CxHF5gpy6g1Qs2IjVYWA5f7FROn/J+Ad8gJYc1azOWCLQqSyfpNRLSvY\n" +
"EriQFEV63XvkJ8JrG62b+2OT2lqT4OO07gSPetppdlSa8NBSKP6Aro9RIX1ZjUZQ\n" +
"SpQFCfo02NO0uNRDPUdJx2huycdNb+AXHaO7eXevDLJ+QnqImIzxWiY6zLOdzjjI\n" +
"VBMkLHmnP7SjGSQ3XA4ByrQOxfOUTyLyE7NuemhHppuQPxE=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* subjectAlt=foo.com
*/
public final static byte[] X509_NO_CNS_FOO = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIESjCCAzKgAwIBAgIJAIz+EYMBU6aYMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxEjAQBgNVBAcTCVZhbmNvdXZlcjEWMBQGA1UE\n" +
"ChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9uc19zc2wxHTAbBgNVBAMU\n" +
"FGRlbW9faW50ZXJtZWRpYXRlX2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZp\n" +
"ZXNAZ21haWwuY29tMB4XDTA2MTIxMTE2MjYxMFoXDTI4MTEwNTE2MjYxMFowgZIx\n" +
"CzAJBgNVBAYTAlVTMREwDwYDVQQIDAhNYXJ5bGFuZDEUMBIGA1UEBwwLRm9yZXN0\n" +
"IEhpbGwxFzAVBgNVBAoMDmh0dHBjb21wb25lbnRzMRowGAYDVQQLDBF0ZXN0IGNl\n" +
"cnRpZmljYXRlczElMCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNv\n" +
"bTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMhjr5aCPoyp0R1iroWA\n" +
"fnEyBMGYWoCidH96yGPFjYLowez5aYKY1IOKTY2BlYho4O84X244QrZTRl8kQbYt\n" +
"xnGh4gSCD+Z8gjZ/gMvLUlhqOb+WXPAUHMB39GRyzerA/ZtrlUqf+lKo0uWcocxe\n" +
"Rc771KN8cPH3nHZ0rV0Hx4ZAZy6U4xxObe4rtSVY07hNKXAb2odnVqgzcYiDkLV8\n" +
"ilvEmoNWMWrp8UBqkTcpEhYhCYp3cTkgJwMSuqv8BqnGd87xQU3FVZI4tbtkB+Kz\n" +
"jD9zz8QCDJAfDjZHR03KNQ5mxOgXwxwKw6lGMaiVJTxpTKqym93whYk93l3ocEe5\n" +
"5c0CAwEAAaOBkDCBjTAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM\n" +
"IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUnxR3vz86tso4gkJIFiza\n" +
"0Mteh9gwHwYDVR0jBBgwFoAUe5raj5CZTlLSrNuzA1LKh6YNPg0wEgYDVR0RBAsw\n" +
"CYIHZm9vLmNvbTANBgkqhkiG9w0BAQUFAAOCAQEAjl78oMjzFdsMy6F1sGg/IkO8\n" +
"tF5yUgPgFYrs41yzAca7IQu6G9qtFDJz/7ehh/9HoG+oqCCIHPuIOmS7Sd0wnkyJ\n" +
"Y7Y04jVXIb3a6f6AgBkEFP1nOT0z6kjT7vkA5LJ2y3MiDcXuRNMSta5PYVnrX8aZ\n" +
"yiqVUNi40peuZ2R8mAUSBvWgD7z2qWhF8YgDb7wWaFjg53I36vWKn90ZEti3wNCw\n" +
"qAVqixM+J0qJmQStgAc53i2aTMvAQu3A3snvH/PHTBo+5UL72n9S1kZyNCsVf1Qo\n" +
"n8jKTiRriEM+fMFlcgQP284EBFzYHyCXFb9O/hMjK2+6mY9euMB1U1aFFzM/Bg==\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* Intermediate CA for all of these.
*/
public final static byte[] X509_INTERMEDIATE_CA = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEnDCCA4SgAwIBAgIJAJTNwZ6yNa5cMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
"BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
"hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjE0OTMx\n" +
"WhcNMDcxMTA1MjE0OTMxWjCBojELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRIw\n" +
"EAYDVQQHEwlWYW5jb3V2ZXIxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDASBgNV\n" +
"BAsUC2NvbW1vbnNfc3NsMR0wGwYDVQQDFBRkZW1vX2ludGVybWVkaWF0ZV9jYTEl\n" +
"MCMGCSqGSIb3DQEJARYWanVsaXVzZGF2aWVzQGdtYWlsLmNvbTCCASIwDQYJKoZI\n" +
"hvcNAQEBBQADggEPADCCAQoCggEBAL0S4y3vUO0EM6lwqOEfK8fvrUprIbsikXaG\n" +
"XzejcZ+T3l2Dc7t8WtBfRf78i4JypMqJQSijrUicj3H6mOMIReKaXm6ls4hA5d8w\n" +
"Lhmgiqsz/kW+gA8SeWGWRN683BD/RbQmzOls6ynBvap9jZlthXWBrSIlPCQoBLXY\n" +
"KVaxGzbL4ezaq+XFMKMQSm2uKwVmHHQNbfmZlPsuendBVomb/ked53Ab9IH6dwwN\n" +
"qJH9WIrvIzIVEXWlpvQ5MCqozM7u1akU+G8cazr8theGPCaYkzoXnigWua4OjdpV\n" +
"9z5ZDknhfBzG1AjapdG07FIirwWWgIyZXqZSD96ikmLtwT29qnsCAwEAAaOB7jCB\n" +
"6zAdBgNVHQ4EFgQUe5raj5CZTlLSrNuzA1LKh6YNPg0wgbsGA1UdIwSBszCBsIAU\n" +
"rN8eFIvMiRFXXgDqKumS0/W2AhOhgYykgYkwgYYxCzAJBgNVBAYTAkNBMQswCQYD\n" +
"VQQIEwJCQzEWMBQGA1UEChMNd3d3LmN1Y2JjLmNvbTEUMBIGA1UECxQLY29tbW9u\n" +
"c19zc2wxFTATBgNVBAMUDGRlbW9fcm9vdF9jYTElMCMGCSqGSIb3DQEJARYWanVs\n" +
"aXVzZGF2aWVzQGdtYWlsLmNvbYIJAJTNwZ6yNa5bMAwGA1UdEwQFMAMBAf8wDQYJ\n" +
"KoZIhvcNAQEFBQADggEBAIB4KMZvHD20pdKajFtMBpL7X4W4soq6EeTtjml3NYa9\n" +
"Qc52bsQEGNccKY9afYSBIndaQvFdtmz6HdoN+B8TjYShw2KhyjtKimGLpWYoi1YF\n" +
"e4aHdmA/Gp5xk8pZzR18FmooxC9RqBux+NAM2iTFSLgDtGIIj4sg2rbn6Bb6ZlQT\n" +
"1rg6VucXCA1629lNfMeNcu7CBNmUKIdaxHR/YJQallE0KfGRiOIWPrPj/VNk0YA6\n" +
"XFg0ocjqXJ2/N0N9rWVshMUaXgOh7m4D/5zga5/nuxDU+PoToA6mQ4bV6eCYqZbh\n" +
"aa1kQYtR9B4ZiG6pB82qVc2dCqStOH2FAEWos2gAVkQ=\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* Root CA for all of these.
*/
public final static byte[] X509_ROOT_CA = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIEgDCCA2igAwIBAgIJAJTNwZ6yNa5bMA0GCSqGSIb3DQEBBQUAMIGGMQswCQYD\n" +
"VQQGEwJDQTELMAkGA1UECBMCQkMxFjAUBgNVBAoTDXd3dy5jdWNiYy5jb20xFDAS\n" +
"BgNVBAsUC2NvbW1vbnNfc3NsMRUwEwYDVQQDFAxkZW1vX3Jvb3RfY2ExJTAjBgkq\n" +
"hkiG9w0BCQEWFmp1bGl1c2Rhdmllc0BnbWFpbC5jb20wHhcNMDYxMTA1MjEzNjQz\n" +
"WhcNMjYxMTA1MjEzNjQzWjCBhjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYw\n" +
"FAYDVQQKEw13d3cuY3VjYmMuY29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMG\n" +
"A1UEAxQMZGVtb19yb290X2NhMSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNA\n" +
"Z21haWwuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv+OnocmJ\n" +
"79UeO2hlCwK+Cle5uZWnU6uwJl+08z5cvebb5tT64WL9+psDbfgUH/Gm9JsuxKTg\n" +
"w1tZO/4duIgnaLNSx4HoqaTjwigd/hR3TsoGEPXTCkz1ikgTCOEDvl+iMid6aOrd\n" +
"mViE8HhscxKZ+h5FE7oHZyuT6gFoiaIXhFq+xK2w4ZwDz9L+paiwqywyUJJMnh9U\n" +
"jKorY+nua81N0oxpIhHPspCanDU4neMzCzYOZyLR/LqV5xORvHcFY84GWMz5hI25\n" +
"JbgaWJsYKuCAvNsnQwVoqKPGa7x1fn7x6oGsXJaCVt8weUwIj2xwg1lxMhrNaisH\n" +
"EvKpEAEnGGwWKQIDAQABo4HuMIHrMB0GA1UdDgQWBBSs3x4Ui8yJEVdeAOoq6ZLT\n" +
"9bYCEzCBuwYDVR0jBIGzMIGwgBSs3x4Ui8yJEVdeAOoq6ZLT9bYCE6GBjKSBiTCB\n" +
"hjELMAkGA1UEBhMCQ0ExCzAJBgNVBAgTAkJDMRYwFAYDVQQKEw13d3cuY3VjYmMu\n" +
"Y29tMRQwEgYDVQQLFAtjb21tb25zX3NzbDEVMBMGA1UEAxQMZGVtb19yb290X2Nh\n" +
"MSUwIwYJKoZIhvcNAQkBFhZqdWxpdXNkYXZpZXNAZ21haWwuY29tggkAlM3BnrI1\n" +
"rlswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAlPl3/8h1LttR1svC\n" +
"S8RXbHpAWIT2BEDhGHUNjSmgDQNkE/itf/FCEXh0tlU4bYdtBSOHzflbnzOyIPId\n" +
"VZeSWs33V38xDFy6KoVg1gT8JxkLmE5S1vWkpsHIlpw/U6r7KD0Kx9FYx5AiXjw0\n" +
"lzz/zlVNuO2U09KIDwDPVG1mBzQiMiSWj1U1pM4KxINkWQwDy/fvu/I983s8lW5z\n" +
"hf2WuFNzQN3fcMK5dpBE9NVIu27oYuGYh2sak34v+7T700W2ooBB71qFXtm9P5rl\n" +
"Yp9RCEsg3KEEPNTtCBs8fROeXvLDrP0cmBIqwGYDuRNCxFDTOdjv6YGdA8nLOjaH\n" +
"2dDk0g==\n" +
"-----END CERTIFICATE-----\n").getBytes();
/**
* Below is the private key for all the server certificates above (but
* not the intermediate CA or the root CA). All of those server certs
* came from the same private key.
*/
public final static String RSA_PUBLIC_MODULUS =
"00c863af96823e8ca9d11d62ae85807e713204c1985a80a2747f7ac863c5" +
"8d82e8c1ecf9698298d4838a4d8d81958868e0ef385f6e3842b653465f24" +
"41b62dc671a1e204820fe67c82367f80cbcb52586a39bf965cf0141cc077" +
"f46472cdeac0fd9b6b954a9ffa52a8d2e59ca1cc5e45cefbd4a37c70f1f7" +
"9c7674ad5d07c78640672e94e31c4e6dee2bb52558d3b84d29701bda8767" +
"56a83371888390b57c8a5bc49a8356316ae9f1406a913729121621098a77" +
"713920270312baabfc06a9c677cef1414dc5559238b5bb6407e2b38c3f73" +
"cfc4020c901f0e3647474dca350e66c4e817c31c0ac3a94631a895253c69" +
"4caab29bddf085893dde5de87047b9e5cd";
public final static String RSA_PUBLIC_EXPONENT = "65537";
public final static String RSA_PRIVATE_EXPONENT =
"577abd3295553d0efd4d38c13b62a6d03fa7b7e40cce4f1d5071877d96c6" +
"7a39a63f0f7ab21a89db8acae45587b3ef251309a70f74dc1ac02bde68f3" +
"8ed658e54e685ed370a18c054449512ea66a2252ed36e82b565b5159ec83" +
"f23df40ae189550a183865b25fd77789e960f0d8cedcd72f32d7a66edb4b" +
"a0a2baf3fbeb6c7d75f56ef0af9a7cff1c8c7f297d72eae7982164e50a89" +
"d450698cf598d39343201094241d2d180a95882a7111e58f4a5bdbc5c125" +
"a967dd6ed9ec614c5853e88e4c71e8b682a7cf89cb1d82b6fe78cc865084" +
"c8c5dfbb50c939df2b839c977b0245bfa3615e0592b527b1013d5b675ecb" +
"44e6b355c1df581f50997175166eef39";
public final static String RSA_PRIME1 =
"00fe759c4f0ce8b763880215e82767e7a937297668f4e4b1e119c6b22a3c" +
"a2c7b06c547d88d0aa45f645d7d3aeadaf7f8bc594deae0978529592977c" +
"b1ff890f05033a9e9e15551cad9fbf9c41d12139ccd99c1c3ac7b2197eff" +
"350d236bb900c1440953b64956e0a058ef824a2e16894af175177c77dbe1" +
"fef7d8b532608d2513";
public final static String RSA_PRIME2 =
"00c99a45878737a4cf73f9896680b75487f1b669b7686a6ba07103856f31" +
"db668c2c440c44cdd116f708f631c37a9adf119f5b5cb58ffe3dc62e20af" +
"af72693d936dc6bb3c5194996468389c1f094079b81522e94572b4ad7d39" +
"529178e9b8ebaeb1f0fdd83b8731c5223f1dea125341d1d64917f6b1a6ae" +
"c18d320510d79f859f";
public final static String RSA_EXPONENT1 =
"029febf0d4cd41b7011c2465b4a259bd6118486464c247236f44a169d61e" +
"47b9062508f674508d5031003ceabc57e714e600d71b2c75d5443db2da52" +
"6bb45a374f0537c5a1aab3150764ce93cf386c84346a6bd01f6732e42075" +
"c7a0e9e78a9e73b934e7d871d0f75673820089e129a1604438edcbbeb4e2" +
"106467da112ce389";
public final static String RSA_EXPONENT2 =
"00827e76650c946afcd170038d32e1f8386ab00d6be78d830efe382e45d4" +
"7ad4bd04e6231ee22e66740efbf52838134932c9f8c460cdccdec58a1424" +
"4427859192fd6ab6c58b74e97941b0eaf577f2a11713af5e5952af3ae124" +
"9a9a892e98410dfa2628d9af668a43b5302fb7d496c9b2fec69f595292b6" +
"e997f079b0f6314eb7";
public final static String RSA_COEFFICIENT =
"00e6b62add350f1a2a8968903ff76c31cf703b0d7326c4a620aef01225b7" +
"1640b3f2ec375208c5f7299863f6005b7799b6e529bb1133c8435bf5fdb5" +
"a786f6cd8a19ee7094a384e6557c600a38845a0960ddbfd1df18d0af5740" +
"001853788f1b5ccbf9affb4c52c9d2efdb8aab0183d86735b32737fb4e79" +
"2b8a9c7d91c7d175ae";
/**
* subjectAlt=IP Address:127.0.0.1, email:oleg@ural.ru, DNS:localhost.localdomain
*/
public final static byte[] X509_MULTIPLE_SUBJECT_ALT = (
"-----BEGIN CERTIFICATE-----\n" +
"MIIDcTCCAtqgAwIBAgIBATANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJDSDEL\n" +
"MAkGA1UECBMCWkgxDzANBgNVBAcTBlp1cmljaDETMBEGA1UEAxMKTXkgVGVzdCBD\n" +
"QTAeFw0wODEwMzExMTU3NDVaFw0wOTEwMzExMTU3NDVaMGkxCzAJBgNVBAYTAkNI\n" +
"MRAwDgYDVQQIEwdVbmtub3duMRAwDgYDVQQHEwdVbmtub3duMRAwDgYDVQQKEwdV\n" +
"bmtub3duMRAwDgYDVQQLEwdVbmtub3duMRIwEAYDVQQDEwlsb2NhbGhvc3QwggG4\n" +
"MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/\n" +
"gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQ\n" +
"IsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZ\n" +
"ndFIAccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5\n" +
"eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbh\n" +
"PBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+qFGQiaiD3+Fa5Z8G\n" +
"kotmXoB7VSVkAUw7/s9JKgOBhQACgYEA6ogAb/YLM1Rz9AoXKW4LA70VtFf7Mqqp\n" +
"divdu9f72WQc1vMKo1YMf3dQadkMfBYRvAAa1IXDnoiFCHhXnVRkWkoUBJyNebLB\n" +
"N92CZc0RVFZiMFgQMEh8UldnvAIi4cBk0/YuN3BGl4MzmquVIGrFovdWGqeaveOu\n" +
"Xcu4lKGJNiqjODA2MDQGA1UdEQQtMCuHBH8AAAGBDG9sZWdAdXJhbC5ydYIVbG9j\n" +
"YWxob3N0LmxvY2FsZG9tYWluMA0GCSqGSIb3DQEBBQUAA4GBAIgEwIoCSRkU3O7K\n" +
"USYaOYyfJB9hsvs6YpClvYXiQ/5kPGARP60pM62v4wC7wI9shEizokIAxY2+O3cC\n" +
"vwuJhNYaa2FJMELIwRN3XES8X8R6JHWbPaRjaAAPhczuEd8SZYy8yiVLmJTgw0gH\n" +
"BSW775NHlkjsscFVgXkNf0PobqJ9\n" +
"-----END CERTIFICATE-----").getBytes();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpExpectationVerifier;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
/**
* Local HTTP server for tests that require one.
* Based on the <code>ElementalHttpServer</code> example in HttpCore.
*/
public class LocalTestServer {
/**
* The local address to bind to.
* The host is an IP number rather than "localhost" to avoid surprises
* on hosts that map "localhost" to an IPv6 address or something else.
* The port is 0 to let the system pick one.
*/
public final static InetSocketAddress TEST_SERVER_ADDR =
new InetSocketAddress("127.0.0.1", 0);
/** The request handler registry. */
private final HttpRequestHandlerRegistry handlerRegistry;
private final HttpService httpservice;
/** Optional SSL context */
private final SSLContext sslcontext;
/** The server socket, while being served. */
private volatile ServerSocket servicedSocket;
/** The request listening thread, while listening. */
private volatile ListenerThread listenerThread;
/** Set of active worker threads */
private final Set<Worker> workers;
/** The number of connections this accepted. */
private final AtomicInteger acceptedConnections = new AtomicInteger(0);
/**
* Creates a new test server.
*
* @param proc the HTTP processors to be used by the server, or
* <code>null</code> to use a
* {@link #newProcessor default} processor
* @param reuseStrat the connection reuse strategy to be used by the
* server, or <code>null</code> to use
* {@link #newConnectionReuseStrategy() default}
* strategy.
* @param params the parameters to be used by the server, or
* <code>null</code> to use
* {@link #newDefaultParams default} parameters
* @param sslcontext optional SSL context if the server is to leverage
* SSL/TLS transport security
*/
public LocalTestServer(
final BasicHttpProcessor proc,
final ConnectionReuseStrategy reuseStrat,
final HttpResponseFactory responseFactory,
final HttpExpectationVerifier expectationVerifier,
final HttpParams params,
final SSLContext sslcontext) {
super();
this.handlerRegistry = new HttpRequestHandlerRegistry();
this.workers = Collections.synchronizedSet(new HashSet<Worker>());
this.httpservice = new HttpService(
proc != null ? proc : newProcessor(),
reuseStrat != null ? reuseStrat: newConnectionReuseStrategy(),
responseFactory != null ? responseFactory: newHttpResponseFactory(),
handlerRegistry,
expectationVerifier,
params != null ? params : newDefaultParams());
this.sslcontext = sslcontext;
}
/**
* Creates a new test server with SSL/TLS encryption.
*
* @param sslcontext SSL context
*/
public LocalTestServer(final SSLContext sslcontext) {
this(null, null, null, null, null, sslcontext);
}
/**
* Creates a new test server.
*
* @param proc the HTTP processors to be used by the server, or
* <code>null</code> to use a
* {@link #newProcessor default} processor
* @param params the parameters to be used by the server, or
* <code>null</code> to use
* {@link #newDefaultParams default} parameters
*/
public LocalTestServer(
BasicHttpProcessor proc,
HttpParams params) {
this(proc, null, null, null, params, null);
}
/**
* Obtains an HTTP protocol processor with default interceptors.
*
* @return a protocol processor for server-side use
*/
protected HttpProcessor newProcessor() {
return new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
}
/**
* Obtains a set of reasonable default parameters for a server.
*
* @return default parameters
*/
protected HttpParams newDefaultParams() {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER,
"LocalTestServer/1.1");
return params;
}
protected ConnectionReuseStrategy newConnectionReuseStrategy() {
return new DefaultConnectionReuseStrategy();
}
protected HttpResponseFactory newHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Returns the number of connections this test server has accepted.
*/
public int getAcceptedConnectionCount() {
return acceptedConnections.get();
}
/**
* {@link #register Registers} a set of default request handlers.
* <pre>
* URI pattern Handler
* ----------- -------
* /echo/* {@link EchoHandler EchoHandler}
* /random/* {@link RandomHandler RandomHandler}
* </pre>
*/
public void registerDefaultHandlers() {
handlerRegistry.register("/echo/*", new EchoHandler());
handlerRegistry.register("/random/*", new RandomHandler());
}
/**
* Registers a handler with the local registry.
*
* @param pattern the URL pattern to match
* @param handler the handler to apply
*/
public void register(String pattern, HttpRequestHandler handler) {
handlerRegistry.register(pattern, handler);
}
/**
* Unregisters a handler from the local registry.
*
* @param pattern the URL pattern
*/
public void unregister(String pattern) {
handlerRegistry.unregister(pattern);
}
/**
* Starts this test server.
*/
public void start() throws Exception {
if (servicedSocket != null) {
throw new IllegalStateException(this.toString() + " already running");
}
ServerSocket ssock;
if (sslcontext != null) {
SSLServerSocketFactory sf = sslcontext.getServerSocketFactory();
ssock = sf.createServerSocket();
} else {
ssock = new ServerSocket();
}
ssock.setReuseAddress(true); // probably pointless for port '0'
ssock.bind(TEST_SERVER_ADDR);
servicedSocket = ssock;
listenerThread = new ListenerThread();
listenerThread.setDaemon(false);
listenerThread.start();
}
/**
* Stops this test server.
*/
public void stop() throws Exception {
if (servicedSocket == null) {
return; // not running
}
ListenerThread t = listenerThread;
if (t != null) {
t.shutdown();
}
synchronized (workers) {
for (Iterator<Worker> it = workers.iterator(); it.hasNext(); ) {
Worker worker = it.next();
worker.shutdown();
}
}
}
public void awaitTermination(long timeMs) throws InterruptedException {
if (listenerThread != null) {
listenerThread.join(timeMs);
}
}
@Override
public String toString() {
ServerSocket ssock = servicedSocket; // avoid synchronization
StringBuilder sb = new StringBuilder(80);
sb.append("LocalTestServer/");
if (ssock == null)
sb.append("stopped");
else
sb.append(ssock.getLocalSocketAddress());
return sb.toString();
}
/**
* Obtains the local address the server is listening on
*
* @return the service address
*/
public InetSocketAddress getServiceAddress() {
ServerSocket ssock = servicedSocket; // avoid synchronization
if (ssock == null) {
throw new IllegalStateException("not running");
}
return (InetSocketAddress) ssock.getLocalSocketAddress();
}
/**
* The request listener.
* Accepts incoming connections and launches a service thread.
*/
class ListenerThread extends Thread {
private volatile Exception exception;
ListenerThread() {
super();
}
@Override
public void run() {
try {
while (!interrupted()) {
Socket socket = servicedSocket.accept();
acceptedConnections.incrementAndGet();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, httpservice.getParams());
// Start worker thread
Worker worker = new Worker(conn);
workers.add(worker);
worker.setDaemon(true);
worker.start();
}
} catch (Exception ex) {
this.exception = ex;
} finally {
try {
servicedSocket.close();
} catch (IOException ignore) {
}
}
}
public void shutdown() {
interrupt();
try {
servicedSocket.close();
} catch (IOException ignore) {
}
}
public Exception getException() {
return this.exception;
}
}
class Worker extends Thread {
private final HttpServerConnection conn;
private volatile Exception exception;
public Worker(final HttpServerConnection conn) {
this.conn = conn;
}
@Override
public void run() {
HttpContext context = new BasicHttpContext();
try {
while (this.conn.isOpen() && !Thread.interrupted()) {
httpservice.handleRequest(this.conn, context);
}
} catch (Exception ex) {
this.exception = ex;
} finally {
workers.remove(this);
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
public void shutdown() {
interrupt();
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
public Exception getException() {
return this.exception;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.util.Locale;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.util.EntityUtils;
/**
* A handler that echos the incoming request entity.
*
*
*
* <!-- empty lines to avoid 'svn diff' problems -->
*/
public class EchoHandler
implements HttpRequestHandler {
// public default constructor
/**
* Handles a request by echoing the incoming request entity.
* If there is no request entity, an empty document is returned.
*
* @param request the request
* @param response the response
* @param context the context
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
public void handle(final HttpRequest request,
final HttpResponse response,
final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!"GET".equals(method) &&
!"POST".equals(method) &&
!"PUT".equals(method)
) {
throw new MethodNotSupportedException
(method + " not supported by " + getClass().getName());
}
HttpEntity entity = null;
if (request instanceof HttpEntityEnclosingRequest)
entity = ((HttpEntityEnclosingRequest)request).getEntity();
// For some reason, just putting the incoming entity into
// the response will not work. We have to buffer the message.
byte[] data;
if (entity == null) {
data = new byte [0];
} else {
data = EntityUtils.toByteArray(entity);
}
ByteArrayEntity bae = new ByteArrayEntity(data);
if (entity != null) {
bae.setContentType(entity.getContentType());
}
entity = bae;
response.setStatusCode(HttpStatus.SC_OK);
response.setEntity(entity);
} // handle
} // class EchoHandler
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.net.InetSocketAddress;
import org.apache.ogt.http.HttpHost;
import org.junit.After;
/**
* Base class for tests using {@link LocalTestServer}. The server will not be started
* per default.
*/
public abstract class BasicServerTestBase {
/** The local server for testing. */
protected LocalTestServer localServer;
@After
public void tearDown() throws Exception {
if (localServer != null) {
localServer.stop();
}
}
/**
* Obtains the address of the local test server.
*
* @return the test server host, with a scheme name of "http"
*/
protected HttpHost getServerHttp() {
InetSocketAddress address = localServer.getServiceAddress();
return new HttpHost(
address.getHostName(),
address.getPort(),
"http");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.protocol.HttpContext;
public class ResponseBasicUnauthorized implements HttpResponseInterceptor {
public void process(
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
response.addHeader(AUTH.WWW_AUTH, "Basic realm=\"test realm\"");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.AbstractHttpEntity;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpRequestHandler;
/**
* A handler that generates random data.
*
*
*
* <!-- empty lines to avoid 'svn diff' problems -->
*/
public class RandomHandler
implements HttpRequestHandler {
// public default constructor
/**
* Handles a request by generating random data.
* The length of the response can be specified in the request URI
* as a number after the last /. For example /random/whatever/20
* will generate 20 random bytes in the printable ASCII range.
* If the request URI ends with /, a random number of random bytes
* is generated, but at least one.
*
* @param request the request
* @param response the response
* @param context the context
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
public void handle(final HttpRequest request,
final HttpResponse response,
final HttpContext context)
throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!"GET".equals(method) && !"HEAD".equals(method)) {
throw new MethodNotSupportedException
(method + " not supported by " + getClass().getName());
}
String uri = request.getRequestLine().getUri();
int slash = uri.lastIndexOf('/');
int length = -1;
if (slash < uri.length()-1) {
try {
// no more than Integer, 2 GB ought to be enough for anybody
length = Integer.parseInt(uri.substring(slash+1));
if (length < 0) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setReasonPhrase("LENGTH " + length);
}
} catch (NumberFormatException nfx) {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
response.setReasonPhrase(nfx.toString());
}
} else {
// random length, but make sure at least something is sent
length = 1 + (int)(Math.random() * 79.0);
}
if (length >= 0) {
response.setStatusCode(HttpStatus.SC_OK);
if (!"HEAD".equals(method)) {
RandomEntity entity = new RandomEntity(length);
entity.setContentType("text/plain; charset=US-ASCII");
response.setEntity(entity);
} else {
response.setHeader("Content-Type",
"text/plain; charset=US-ASCII");
response.setHeader("Content-Length",
String.valueOf(length));
}
}
} // handle
/**
* An entity that generates random data.
* This is an outgoing entity, it supports {@link #writeTo writeTo}
* but not {@link #getContent getContent}.
*/
public static class RandomEntity extends AbstractHttpEntity {
/** The range from which to generate random data. */
private final static byte[] RANGE;
static {
byte[] range = null;
try {
range = ("abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
).getBytes("US-ASCII");
} catch (UnsupportedEncodingException uex) {
// never, US-ASCII is guaranteed
}
RANGE = range;
}
/** The length of the random data to generate. */
protected final long length;
/**
* Creates a new entity generating the given amount of data.
*
* @param len the number of random bytes to generate,
* 0 to maxint
*/
public RandomEntity(long len) {
if (len < 0L)
throw new IllegalArgumentException
("Length must not be negative");
if (len > Integer.MAX_VALUE)
throw new IllegalArgumentException
("Length must not exceed Integer.MAX_VALUE");
length = len;
}
/**
* Tells that this entity is not streaming.
*
* @return false
*/
public final boolean isStreaming() {
return false;
}
/**
* Tells that this entity is repeatable, in a way.
* Repetitions will generate different random data,
* unless perchance the same random data is generated twice.
*
* @return <code>true</code>
*/
public boolean isRepeatable() {
return true;
}
/**
* Obtains the size of the random data.
*
* @return the number of random bytes to generate
*/
public long getContentLength() {
return length;
}
/**
* Not supported.
* This method throws an exception.
*
* @return never anything
*/
public InputStream getContent() {
throw new UnsupportedOperationException();
}
/**
* Generates the random content.
*
* @param out where to write the content to
*/
public void writeTo(OutputStream out) throws IOException {
final int blocksize = 2048;
int remaining = (int) length; // range checked in constructor
byte[] data = new byte[Math.min(remaining, blocksize)];
while (remaining > 0) {
final int end = Math.min(remaining, data.length);
double value = 0.0;
for (int i = 0; i < end; i++) {
// we get 5 random characters out of one random value
if (i%5 == 0) {
value = Math.random();
}
value = value * RANGE.length;
int d = (int) value;
value = value - d;
data[i] = RANGE[d];
}
out.write(data, 0, end);
out.flush();
remaining = remaining - end;
}
out.close();
} // writeTo
} // class RandomEntity
} // class RandomHandler
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.conn.scheme.PlainSocketFactory;
import org.apache.ogt.http.conn.scheme.Scheme;
import org.apache.ogt.http.conn.scheme.SchemeRegistry;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.BasicHttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.junit.Before;
/**
* Base class for tests using {@link LocalTestServer LocalTestServer}.
* Note that the test server will be {@link #setUp set up} before each
* individual tests and {@link #tearDown teared down} afterwards.
* Use this base class <i>exclusively</i> for tests that require the
* server. If you have some tests that require the server and others
* that don't, split them in two different classes.
*/
public abstract class ServerTestBase extends BasicServerTestBase {
/** The available schemes. */
protected SchemeRegistry supportedSchemes;
/** The default parameters for the client side. */
protected HttpParams defaultParams;
/** The HTTP processor for the client side. */
protected BasicHttpProcessor httpProcessor;
/** The default context for the client side. */
protected BasicHttpContext httpContext;
/** The request executor for the client side. */
protected HttpRequestExecutor httpExecutor;
/**
* Prepares the local server for testing.
* Derived classes that override this method MUST call
* the implementation here. That SHOULD be done at the
* beginning of the overriding method.
* <br/>
* Derived methods can modify for example the default parameters
* being set up, or the interceptors.
* <p>
* This method will re-use the helper objects from a previous run
* if they are still available. For example, the local test server
* will be re-started rather than re-created.
* {@link #httpContext httpContext} will always be re-created.
* Tests that modify the other helper objects should afterwards
* set the respective attributes to <code>null</code> in a
* <code>finally{}</code> block to force re-creation for
* subsequent tests.
* Of course that shouldn't be done with the test server,
* or only after shutting that down.
*
* @throws Exception in case of a problem
*/
@Before
public void setUp() throws Exception {
if (defaultParams == null) {
defaultParams = new SyncBasicHttpParams();
HttpProtocolParams.setVersion
(defaultParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset
(defaultParams, "UTF-8");
HttpProtocolParams.setUserAgent
(defaultParams, "TestAgent/1.1");
HttpProtocolParams.setUseExpectContinue
(defaultParams, false);
}
if (supportedSchemes == null) {
supportedSchemes = new SchemeRegistry();
SchemeSocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", 80, sf));
}
if (httpProcessor == null) {
httpProcessor = new BasicHttpProcessor();
httpProcessor.addInterceptor(new RequestContent());
httpProcessor.addInterceptor(new RequestConnControl()); // optional
}
// the context is created each time, it may get modified by test cases
httpContext = new BasicHttpContext(null);
if (httpExecutor == null) {
httpExecutor = new HttpRequestExecutor();
}
if (localServer == null) {
localServer = new LocalTestServer(null, null);
localServer.registerDefaultHandlers();
}
localServer.start();
} // setUp
/**
* Opens a connection to the given target using
* {@link #defaultParams default parameters}.
* Maps to {@link #connectTo(HttpHost,HttpParams)
* connectTo(target,defaultParams)}.
*
* @param target the target to connect to
*
* @return a new connection opened to the target
*
* @throws Exception in case of a problem
*/
protected DefaultHttpClientConnection connectTo(HttpHost target)
throws Exception {
return connectTo(target, defaultParams);
}
/**
* Opens a connection to the given target using the given parameters.
*
* @param target the target to connect to
*
* @return a new connection opened to the target
*
* @throws Exception in case of a problem
*/
protected DefaultHttpClientConnection connectTo(HttpHost target,
HttpParams params)
throws Exception {
Scheme schm = supportedSchemes.get(target.getSchemeName());
int port = schm.resolvePort(target.getPort());
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
InetSocketAddress address = new InetSocketAddress(
InetAddress.getByName(target.getHostName()), port);
Socket sock = schm.getSchemeSocketFactory().connectSocket(null, address, null, params);
conn.bind(sock, params);
return conn;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.protocol.HttpContext;
public class RequestBasicAuth implements HttpRequestInterceptor {
private final BasicAuthTokenExtractor authTokenExtractor;
public RequestBasicAuth() {
super();
this.authTokenExtractor = new BasicAuthTokenExtractor();
}
public void process(
final HttpRequest request,
final HttpContext context) throws HttpException, IOException {
context.setAttribute("creds", this.authTokenExtractor.extract(request));
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.localserver;
import org.apache.commons.codec.BinaryDecoder;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.auth.AUTH;
import org.apache.ogt.http.util.EncodingUtils;
public class BasicAuthTokenExtractor {
public String extract(final HttpRequest request) throws HttpException {
String auth = null;
Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);
if (h != null) {
String s = h.getValue();
if (s != null) {
auth = s.trim();
}
}
if (auth != null) {
int i = auth.indexOf(' ');
if (i == -1) {
throw new ProtocolException("Invalid Authorization header: " + auth);
}
String authscheme = auth.substring(0, i);
if (authscheme.equalsIgnoreCase("basic")) {
String s = auth.substring(i + 1).trim();
try {
byte[] credsRaw = EncodingUtils.getAsciiBytes(s);
BinaryDecoder codec = new Base64();
auth = EncodingUtils.getAsciiString(codec.decode(credsRaw));
} catch (DecoderException ex) {
throw new ProtocolException("Malformed BASIC credentials");
}
}
}
return auth;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.impl.io.AbstractSessionInputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionInputBuffer} mockup implementation.
*/
public class SessionInputBufferMockup extends AbstractSessionInputBuffer {
public static final int BUFFER_SIZE = 16;
public SessionInputBufferMockup(
final InputStream instream,
int buffersize,
final HttpParams params) {
super();
init(instream, buffersize, params);
}
public SessionInputBufferMockup(
final InputStream instream,
int buffersize) {
this(instream, buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
final HttpParams params) {
this(bytes, BUFFER_SIZE, params);
}
public SessionInputBufferMockup(
final byte[] bytes) {
this(bytes, BUFFER_SIZE, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize,
final HttpParams params) {
this(new ByteArrayInputStream(bytes), buffersize, params);
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize) {
this(new ByteArrayInputStream(bytes), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, params);
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), params);
}
public SessionInputBufferMockup(
final String s,
final String charset)
throws UnsupportedEncodingException {
this(s.getBytes(charset), new BasicHttpParams());
}
public boolean isDataAvailable(int timeout) throws IOException {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
/**
* {@link HttpConnection} mockup implementation.
*
*/
public class HttpConnectionMockup implements HttpConnection {
private boolean open = true;
public HttpConnectionMockup() {
super();
}
public void close() throws IOException {
this.open = false;
}
public void shutdown() throws IOException {
this.open = false;
}
public int getSocketTimeout() {
return 0;
}
public boolean isOpen() {
return this.open;
}
public boolean isStale() {
return false;
}
public void setSocketTimeout(int timeout) {
}
public HttpConnectionMetrics getMetrics() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.net.Socket;
import org.apache.ogt.http.conn.scheme.LayeredSchemeSocketFactory;
/**
* {@link LayeredSchemeSocketFactory} mockup implementation.
*/
public class SecureSocketFactoryMockup extends SocketFactoryMockup
implements LayeredSchemeSocketFactory {
/* A default instance of this mockup. */
public final static LayeredSchemeSocketFactory INSTANCE = new SecureSocketFactoryMockup("INSTANCE");
public SecureSocketFactoryMockup(String name) {
super(name);
}
// don't implement equals and hashcode, all instances are different!
@Override
public String toString() {
return "SecureSocketFactoryMockup." + mockup_name;
}
public Socket createLayeredSocket(Socket socket, String host, int port,
boolean autoClose) {
throw new UnsupportedOperationException("I'm a mockup!");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import org.apache.ogt.http.conn.ConnectTimeoutException;
import org.apache.ogt.http.conn.scheme.SchemeSocketFactory;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link SchemeSocketFactory} mockup implementation.
*/
public class SocketFactoryMockup implements SchemeSocketFactory {
/* A default instance of this mockup. */
public final static SchemeSocketFactory INSTANCE = new SocketFactoryMockup("INSTANCE");
/** The name of this mockup socket factory. */
protected final String mockup_name;
public SocketFactoryMockup(String name) {
mockup_name = (name != null) ? name : String.valueOf(hashCode());
}
// don't implement equals and hashcode, all instances are different!
@Override
public String toString() {
return "SocketFactoryMockup." + mockup_name;
}
public Socket createSocket(final HttpParams params) {
throw new UnsupportedOperationException("I'm a mockup!");
}
public Socket connectSocket(
Socket sock,
InetSocketAddress remoteAddress,
InetSocketAddress localAddress,
HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
throw new UnsupportedOperationException("I'm a mockup!");
}
public boolean isSecure(Socket sock) {
// no way that the argument is from *this* factory...
throw new IllegalArgumentException("I'm a mockup!");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.net.URI;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
/**
* Mockup of a {@link ProxySelector}.
* Always returns a fixed list.
*/
public class ProxySelectorMockup extends ProxySelector {
protected List<Proxy> proxyList;
/**
* Creates a mock proxy selector.
*
* @param proxies the list of proxies, or
* <code>null</code> for direct connections
*/
public ProxySelectorMockup(List<Proxy> proxies) {
if (proxies == null) {
proxies = new ArrayList<Proxy>(1);
proxies.add(Proxy.NO_PROXY);
} else if (proxies.isEmpty()) {
throw new IllegalArgumentException
("Proxy list must not be empty.");
}
proxyList = proxies;
}
/**
* Obtains the constructor argument.
*
* @param ignored not used by this mockup
*
* @return the list passed to the constructor,
* or a default list with "DIRECT" as the only element
*/
@Override
public List<Proxy> select(URI ignored) {
return proxyList;
}
/**
* Does nothing.
*/
@Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
// no body
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
/**
* Static helper methods.
*/
public final class Helper {
/** Disabled default constructor. */
private Helper() {
// no body
}
/**
* Executes a request.
*/
public static HttpResponse execute(HttpRequest req,
HttpClientConnection conn,
HttpHost target,
HttpRequestExecutor exec,
HttpProcessor proc,
HttpParams params,
HttpContext ctxt)
throws Exception {
ctxt.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
ctxt.setAttribute(ExecutionContext.HTTP_TARGET_HOST, target);
ctxt.setAttribute(ExecutionContext.HTTP_REQUEST, req);
req.setParams(new DefaultedHttpParams(req.getParams(), params));
exec.preProcess(req, proc, ctxt);
HttpResponse rsp = exec.execute(req, conn, ctxt);
rsp.setParams(new DefaultedHttpParams(rsp.getParams(), params));
exec.postProcess(rsp, proc, ctxt);
return rsp;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import java.io.IOException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.impl.conn.AbstractClientConnAdapter;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Mockup connection adapter.
*/
public class ClientConnAdapterMockup extends AbstractClientConnAdapter {
public ClientConnAdapterMockup(ClientConnectionManager mgr) {
super(mgr, null);
}
public void close() {
}
public HttpRoute getRoute() {
throw new UnsupportedOperationException("just a mockup");
}
public void layerProtocol(HttpContext context, HttpParams params) {
throw new UnsupportedOperationException("just a mockup");
}
public void open(HttpRoute route, HttpContext context, HttpParams params) throws IOException {
throw new UnsupportedOperationException("just a mockup");
}
public void shutdown() {
}
public void tunnelTarget(boolean secure, HttpParams params) {
throw new UnsupportedOperationException("just a mockup");
}
public void tunnelProxy(HttpHost next, boolean secure, HttpParams params) {
throw new UnsupportedOperationException("just a mockup");
}
public Object getState() {
throw new UnsupportedOperationException("just a mockup");
}
public void setState(Object state) {
throw new UnsupportedOperationException("just a mockup");
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn.tsccm;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import org.apache.ogt.http.impl.conn.tsccm.WaitingThread;
/**
* Thread to await something.
*/
public class AwaitThread extends Thread {
protected final WaitingThread wait_object;
protected final Lock wait_lock;
protected final Date wait_deadline;
protected volatile boolean waiting;
protected volatile Throwable exception;
/**
* Creates a new thread.
* When this thread is started, it will wait on the argument object.
*/
public AwaitThread(WaitingThread where, Lock lck, Date deadline) {
wait_object = where;
wait_lock = lck;
wait_deadline = deadline;
}
/**
* This method is executed when the thread is started.
*/
@Override
public void run() {
try {
wait_lock.lock();
waiting = true;
wait_object.await(wait_deadline);
} catch (Throwable dart) {
exception = dart;
} finally {
waiting = false;
wait_lock.unlock();
}
// terminate
}
public Throwable getException() {
return exception;
}
public boolean isWaiting() {
try {
wait_lock.lock();
return waiting;
} finally {
wait_lock.unlock();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import java.util.concurrent.TimeUnit;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.ClientConnectionRequest;
import org.apache.ogt.http.conn.ManagedClientConnection;
import org.apache.ogt.http.conn.routing.HttpRoute;
/**
* Thread to get a connection from a connection manager.
* Used by connection manager tests.
* Code based on HttpClient 3.x class <code>TestHttpConnectionManager</code>.
*/
public class GetConnThread extends Thread {
protected final HttpRoute conn_route;
protected final long conn_timeout;
protected final ClientConnectionRequest conn_request;
protected volatile ManagedClientConnection connection;
protected volatile Throwable exception;
/**
* Creates a new thread for requesting a connection from the given manager.
*
* When this thread is started, it will try to obtain a connection.
* The timeout is in milliseconds.
*/
public GetConnThread(ClientConnectionManager mgr,
HttpRoute route, long timeout) {
this(mgr.requestConnection(route, null), route, timeout);
}
/**
* Creates a new for requesting a connection from the given request object.
*
* When this thread is started, it will try to obtain a connection.
* The timeout is in milliseconds.
*/
public GetConnThread(ClientConnectionRequest connectionRequest,
HttpRoute route, long timeout) {
conn_route = route;
conn_timeout = timeout;
conn_request = connectionRequest;
}
/**
* This method is executed when the thread is started.
*/
@Override
public void run() {
try {
connection = conn_request.getConnection
(conn_timeout, TimeUnit.MILLISECONDS);
} catch (Throwable dart) {
exception = dart;
}
// terminate
}
public Throwable getException() {
return exception;
}
public ManagedClientConnection getConnection() {
return connection;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.conn;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.conn.ClientConnectionManager;
import org.apache.ogt.http.conn.routing.HttpRoute;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.util.EntityUtils;
/**
* Executes a request from a new thread.
*
*/
public class ExecReqThread extends GetConnThread {
protected final ClientConnectionManager conn_manager;
protected final RequestSpec request_spec;
protected volatile HttpResponse response;
protected volatile byte[] response_data;
/**
* Executes a request.
* This involves the following steps:
* <ol>
* <li>obtain a connection (see base class)</li>
* <li>open the connection</li>
* <li>prepare context and request</li>
* <li>execute request to obtain the response</li>
* <li>consume the response entity (if there is one)</li>
* <li>release the connection</li>
* </ol>
*/
public ExecReqThread(ClientConnectionManager mgr,
HttpRoute route, long timeout,
RequestSpec reqspec) {
super(mgr, route, timeout);
this.conn_manager = mgr;
request_spec = reqspec;
}
public HttpResponse getResponse() {
return response;
}
public byte[] getResponseData() {
return response_data;
}
/**
* This method is invoked when the thread is started.
* It invokes the base class implementation.
*/
@Override
public void run() {
super.run(); // obtain connection
if (connection == null)
return; // problem obtaining connection
try {
request_spec.context.setAttribute
(ExecutionContext.HTTP_CONNECTION, connection);
doOpenConnection();
HttpRequest request = (HttpRequest) request_spec.context.
getAttribute(ExecutionContext.HTTP_REQUEST);
request_spec.executor.preProcess
(request, request_spec.processor, request_spec.context);
response = request_spec.executor.execute
(request, connection, request_spec.context);
request_spec.executor.postProcess
(response, request_spec.processor, request_spec.context);
doConsumeResponse();
} catch (Throwable dart) {
dart.printStackTrace(System.out);
if (exception != null)
exception = dart;
} finally {
conn_manager.releaseConnection(connection, -1, null);
}
}
/**
* Opens the connection after it has been obtained.
*/
protected void doOpenConnection() throws Exception {
connection.open
(conn_route, request_spec.context, request_spec.params);
}
/**
* Reads the response entity, if there is one.
*/
protected void doConsumeResponse() throws Exception {
if (response.getEntity() != null)
response_data = EntityUtils.toByteArray(response.getEntity());
}
/**
* Helper class collecting request data.
* The request and target are expected in the context.
*/
public static class RequestSpec {
public HttpRequestExecutor executor;
public HttpProcessor processor;
public HttpContext context;
public HttpParams params;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.auth;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.impl.cookie.DateUtils;
import org.apache.http.message.BasicHeader;
/**
* Implementation of Amazon S3 authentication. This scheme must be used
* preemptively only.
* <p>
* Reference Document: {@link http
* ://docs.amazonwebservices.com/AmazonS3/latest/index
* .html?RESTAuthentication.html}
*/
public class AWSScheme implements AuthScheme {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
public static final String NAME = "AWS";
public AWSScheme() {
}
public Header authenticate(
final Credentials credentials,
final HttpRequest request) throws AuthenticationException {
// If the Date header has not been provided add it as it is required
if (request.getFirstHeader("Date") == null) {
Header dateHeader = new BasicHeader("Date", DateUtils.formatDate(new Date()));
request.addHeader(dateHeader);
}
String canonicalizedAmzHeaders = getCanonicalizedAmzHeaders(request.getAllHeaders());
String canonicalizedResource = getCanonicalizedResource(request.getRequestLine().getUri(),
(request.getFirstHeader("Host") != null ? request.getFirstHeader("Host").getValue()
: null));
String contentMD5 = request.getFirstHeader("Content-MD5") != null ? request.getFirstHeader(
"Content-MD5").getValue() : "";
String contentType = request.getFirstHeader("Content-Type") != null ? request
.getFirstHeader("Content-Type").getValue() : "";
String date = request.getFirstHeader("Date").getValue();
String method = request.getRequestLine().getMethod();
StringBuilder toSign = new StringBuilder();
toSign.append(method).append("\n");
toSign.append(contentMD5).append("\n");
toSign.append(contentType).append("\n");
toSign.append(date).append("\n");
toSign.append(canonicalizedAmzHeaders);
toSign.append(canonicalizedResource);
String signature = calculateRFC2104HMAC(toSign.toString(), credentials.getPassword());
String headerValue = NAME + " " + credentials.getUserPrincipal().getName() + ":" + signature.trim();
return new BasicHeader("Authorization", headerValue);
}
/**
* Computes RFC 2104-compliant HMAC signature.
*
* @param data
* The data to be signed.
* @param key
* The signing key.
* @return The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws RuntimeException
* when signature generation fails
*/
private static String calculateRFC2104HMAC(
final String data,
final String key) throws AuthenticationException {
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
return Base64.encodeBase64String(rawHmac);
} catch (InvalidKeyException ex) {
throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex);
} catch (NoSuchAlgorithmException ex) {
throw new AuthenticationException(HMAC_SHA1_ALGORITHM +
" algorithm is not supported", ex);
}
}
/**
* Returns the canonicalized AMZ headers.
*
* @param headers
* The list of request headers.
* @return The canonicalized AMZ headers.
*/
private static String getCanonicalizedAmzHeaders(final Header[] headers) {
StringBuilder sb = new StringBuilder();
Pattern spacePattern = Pattern.compile("\\s+");
// Create a lexographically sorted list of headers that begin with x-amz
SortedMap<String, String> amzHeaders = new TreeMap<String, String>();
for (Header header : headers) {
String name = header.getName().toLowerCase();
if (name.startsWith("x-amz-")) {
String value = "";
if (amzHeaders.containsKey(name))
value = amzHeaders.get(name) + "," + header.getValue();
else
value = header.getValue();
// All newlines and multiple spaces must be replaced with a
// single space character.
Matcher m = spacePattern.matcher(value);
value = m.replaceAll(" ");
amzHeaders.put(name, value);
}
}
// Concatenate all AMZ headers
for (Entry<String, String> entry : amzHeaders.entrySet()) {
sb.append(entry.getKey()).append(':').append(entry.getValue()).append("\n");
}
return sb.toString();
}
/**
* Returns the canonicalized resource.
*
* @param uri
* The resource uri
* @param hostName
* the host name
* @return The canonicalized resource.
*/
private static String getCanonicalizedResource(String uri, String hostName) {
StringBuilder sb = new StringBuilder();
// Append the bucket if there is one
if (hostName != null) {
// If the host name contains a port number remove it
if (hostName.contains(":"))
hostName = hostName.substring(0, hostName.indexOf(":"));
// Now extract the bucket if there is one
if (hostName.endsWith(".s3.amazonaws.com")) {
String bucketName = hostName.substring(0, hostName.length() - 17);
sb.append("/" + bucketName);
}
}
int queryIdx = uri.indexOf("?");
// Append the resource path
if (queryIdx >= 0)
sb.append(uri.substring(0, queryIdx));
else
sb.append(uri.substring(0, uri.length()));
// Append the AWS sub-resource
if (queryIdx >= 0) {
String query = uri.substring(queryIdx - 1, uri.length());
if (query.contains("?acl"))
sb.append("?acl");
else if (query.contains("?location"))
sb.append("?location");
else if (query.contains("?logging"))
sb.append("?logging");
else if (query.contains("?torrent"))
sb.append("?torrent");
}
return sb.toString();
}
public String getParameter(String name) {
return null;
}
public String getRealm() {
return null;
}
public String getSchemeName() {
return NAME;
}
public boolean isComplete() {
return true;
}
public boolean isConnectionBased() {
return false;
}
public void processChallenge(final Header header) throws MalformedChallengeException {
// Nothing to do here
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.auth;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthSchemeFactory;
import org.apache.http.params.HttpParams;
/**
* {@link AuthSchemeFactory} implementation that creates and initializes
* {@link AWSScheme} instances.
*/
public class AWSSchemeFactory implements AuthSchemeFactory {
public AuthScheme newInstance(final HttpParams params) {
return new AWSScheme();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.contrib.auth;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.impl.auth.SpnegoTokenGenerator;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.util.ASN1Dump;
/**
* Takes Kerberos ticket and wraps into a SPNEGO token. Leaving some optional fields out.
*/
public class BouncySpnegoTokenGenerator implements SpnegoTokenGenerator {
private final Log log = LogFactory.getLog(getClass());
private final DERObjectIdentifier spnegoOid;
private final DERObjectIdentifier kerbOid;
public BouncySpnegoTokenGenerator() {
super();
this.spnegoOid = new DERObjectIdentifier("1.3.6.1.5.5.2");
this.kerbOid = new DERObjectIdentifier("1.2.840.113554.1.2.2");
}
public byte [] generateSpnegoDERObject(byte [] kerbTicket) throws IOException {
DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket);
DERSequence kerbOidSeq = new DERSequence(kerbOid);
DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq);
DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket);
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(tagged0);
v.add(tagged2);
DERSequence seq = new DERSequence(v);
DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ASN1OutputStream asn1Out = new ASN1OutputStream(out);
ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object();
ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object();
int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length;
byte [] lenBytes = writeLength(length);
byte[] appWrap = new byte[lenBytes.length + 1];
appWrap[0] = 0x60;
for(int i=1; i < appWrap.length; i++){
appWrap[i] = lenBytes[i-1];
}
asn1Out.write(appWrap);
asn1Out.writeObject(spnegoOid.toASN1Object());
asn1Out.writeObject(taggedSpnego.toASN1Object());
byte[] app = out.toByteArray();
ASN1InputStream in = new ASN1InputStream(app);
if (log.isDebugEnabled() ){
int skip = 12;
byte [] manipBytes = new byte[app.length - skip];
for(int i=skip; i < app.length; i++){
manipBytes[i-skip] = app[i];
}
ASN1InputStream ourSpnego = new ASN1InputStream( manipBytes );
log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject()));
}
return in.readObject().getDEREncoded();
}
private byte [] writeLength(int length) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (length > 127) {
int size = 1;
int val = length;
while ((val >>>= 8) != 0) {
size++;
}
out.write((byte) (size | 0x80));
for (int i = (size - 1) * 8; i >= 0; i -= 8) {
out.write((byte) (length >> i));
}
} else {
out.write((byte) length);
}
return out.toByteArray();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Random;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.entity.mime.content.ContentBody;
import org.apache.ogt.http.message.BasicHeader;
import org.apache.ogt.http.protocol.HTTP;
/**
* Multipart/form coded HTTP entity consisting of multiple body parts.
*
* @since 4.0
*/
public class MultipartEntity implements HttpEntity {
/**
* The pool of ASCII chars to be used for generating a multipart boundary.
*/
private final static char[] MULTIPART_CHARS =
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
private final HttpMultipart multipart;
private final Header contentType;
// @GuardedBy("dirty") // we always read dirty before accessing length
private long length;
private volatile boolean dirty; // used to decide whether to recalculate length
/**
* Creates an instance using the specified parameters
* @param mode the mode to use, may be {@code null}, in which case {@link HttpMultipartMode#STRICT} is used
* @param boundary the boundary string, may be {@code null}, in which case {@link #generateBoundary()} is invoked to create the string
* @param charset the character set to use, may be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
*/
public MultipartEntity(
HttpMultipartMode mode,
String boundary,
Charset charset) {
super();
if (boundary == null) {
boundary = generateBoundary();
}
if (mode == null) {
mode = HttpMultipartMode.STRICT;
}
this.multipart = new HttpMultipart("form-data", charset, boundary, mode);
this.contentType = new BasicHeader(
HTTP.CONTENT_TYPE,
generateContentType(boundary, charset));
this.dirty = true;
}
/**
* Creates an instance using the specified {@link HttpMultipartMode} mode.
* Boundary and charset are set to {@code null}.
* @param mode the desired mode
*/
public MultipartEntity(final HttpMultipartMode mode) {
this(mode, null, null);
}
/**
* Creates an instance using mode {@link HttpMultipartMode#STRICT}
*/
public MultipartEntity() {
this(HttpMultipartMode.STRICT, null, null);
}
protected String generateContentType(
final String boundary,
final Charset charset) {
StringBuilder buffer = new StringBuilder();
buffer.append("multipart/form-data; boundary=");
buffer.append(boundary);
if (charset != null) {
buffer.append("; charset=");
buffer.append(charset.name());
}
return buffer.toString();
}
protected String generateBoundary() {
StringBuilder buffer = new StringBuilder();
Random rand = new Random();
int count = rand.nextInt(11) + 30; // a random size from 30 to 40
for (int i = 0; i < count; i++) {
buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
return buffer.toString();
}
public void addPart(final FormBodyPart bodyPart) {
this.multipart.addBodyPart(bodyPart);
this.dirty = true;
}
public void addPart(final String name, final ContentBody contentBody) {
addPart(new FormBodyPart(name, contentBody));
}
public boolean isRepeatable() {
for (FormBodyPart part: this.multipart.getBodyParts()) {
ContentBody body = part.getBody();
if (body.getContentLength() < 0) {
return false;
}
}
return true;
}
public boolean isChunked() {
return !isRepeatable();
}
public boolean isStreaming() {
return !isRepeatable();
}
public long getContentLength() {
if (this.dirty) {
this.length = this.multipart.getTotalLength();
this.dirty = false;
}
return this.length;
}
public Header getContentType() {
return this.contentType;
}
public Header getContentEncoding() {
return null;
}
public void consumeContent()
throws IOException, UnsupportedOperationException{
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException, UnsupportedOperationException {
throw new UnsupportedOperationException(
"Multipart form entity does not implement #getContent()");
}
public void writeTo(final OutputStream outstream) throws IOException {
this.multipart.writeTo(outstream);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
import java.nio.charset.Charset;
/**
*
* @since 4.0
*/
public final class MIME {
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_TRANSFER_ENC = "Content-Transfer-Encoding";
public static final String CONTENT_DISPOSITION = "Content-Disposition";
public static final String ENC_8BIT = "8bit";
public static final String ENC_BINARY = "binary";
/** The default character set to be used, i.e. "US-ASCII" */
public static final Charset DEFAULT_CHARSET = Charset.forName("US-ASCII");
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
/**
* Minimal MIME field.
*
* @since 4.0
*/
public class MinimalField {
private final String name;
private final String value;
MinimalField(final String name, final String value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return this.name;
}
public String getBody() {
return this.value;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(this.name);
buffer.append(": ");
buffer.append(this.value);
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
import java.io.IOException;
import java.io.OutputStream;
/**
*
* @since 4.0
*/
public interface ContentBody extends ContentDescriptor {
String getFilename();
void writeTo(OutputStream out) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.mime.MIME;
/**
*
* @since 4.0
*/
public class FileBody extends AbstractContentBody {
private final File file;
private final String filename;
private final String charset;
/**
* @since 4.1
*/
public FileBody(final File file,
final String filename,
final String mimeType,
final String charset) {
super(mimeType);
if (file == null) {
throw new IllegalArgumentException("File may not be null");
}
this.file = file;
if (filename != null)
this.filename = filename;
else
this.filename = file.getName();
this.charset = charset;
}
/**
* @since 4.1
*/
public FileBody(final File file,
final String mimeType,
final String charset) {
this(file, null, mimeType, charset);
}
public FileBody(final File file, final String mimeType) {
this(file, mimeType, null);
}
public FileBody(final File file) {
this(file, "application/octet-stream");
}
public InputStream getInputStream() throws IOException {
return new FileInputStream(this.file);
}
/**
* @deprecated use {@link #writeTo(OutputStream)}
*/
@Deprecated
public void writeTo(final OutputStream out, int mode) throws IOException {
writeTo(out);
}
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream in = new FileInputStream(this.file);
try {
byte[] tmp = new byte[4096];
int l;
while ((l = in.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} finally {
in.close();
}
}
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
public String getCharset() {
return charset;
}
public long getContentLength() {
return this.file.length();
}
public String getFilename() {
return filename;
}
public File getFile() {
return this.file;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.mime.MIME;
/**
*
* @since 4.0
*/
public class InputStreamBody extends AbstractContentBody {
private final InputStream in;
private final String filename;
public InputStreamBody(final InputStream in, final String mimeType, final String filename) {
super(mimeType);
if (in == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
this.in = in;
this.filename = filename;
}
public InputStreamBody(final InputStream in, final String filename) {
this(in, "application/octet-stream", filename);
}
public InputStream getInputStream() {
return this.in;
}
/**
* @deprecated use {@link #writeTo(OutputStream)}
*/
@Deprecated
public void writeTo(final OutputStream out, int mode) throws IOException {
writeTo(out);
}
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
try {
byte[] tmp = new byte[4096];
int l;
while ((l = this.in.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} finally {
this.in.close();
}
}
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
public String getCharset() {
return null;
}
public long getContentLength() {
return -1;
}
public String getFilename() {
return this.filename;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.entity.mime.MIME;
import org.apache.ogt.http.entity.mime.content.AbstractContentBody;
/**
* Body part that is built using a byte array containing a file.
*
* @since 4.1
*/
public class ByteArrayBody extends AbstractContentBody {
/**
* The contents of the file contained in this part.
*/
private final byte[] data;
/**
* The name of the file contained in this part.
*/
private final String filename;
/**
* Creates a new ByteArrayBody.
*
* @param data The contents of the file contained in this part.
* @param mimeType The mime type of the file contained in this part.
* @param filename The name of the file contained in this part.
*/
public ByteArrayBody(final byte[] data, final String mimeType, final String filename) {
super(mimeType);
if (data == null) {
throw new IllegalArgumentException("byte[] may not be null");
}
this.data = data;
this.filename = filename;
}
/**
* Creates a new ByteArrayBody.
*
* @param data The contents of the file contained in this part.
* @param filename The name of the file contained in this part.
*/
public ByteArrayBody(final byte[] data, final String filename) {
this(data, "application/octet-stream", filename);
}
public String getFilename() {
return filename;
}
public void writeTo(final OutputStream out) throws IOException {
out.write(data);
}
public String getCharset() {
return null;
}
public String getTransferEncoding() {
return MIME.ENC_BINARY;
}
public long getContentLength() {
return data.length;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
/**
* Represents common content properties.
*/
public interface ContentDescriptor {
/**
* Returns the body descriptors MIME type.
* @see #getMediaType()
* @see #getSubType()
* @return The MIME type, which has been parsed from the
* content-type definition. Must not be null, but
* "text/plain", if no content-type was specified.
*/
String getMimeType();
/**
* Gets the defaulted MIME media type for this content.
* For example <code>TEXT</code>, <code>IMAGE</code>, <code>MULTIPART</code>
* @see #getMimeType()
* @return the MIME media type when content-type specified,
* otherwise the correct default (<code>TEXT</code>)
*/
String getMediaType();
/**
* Gets the defaulted MIME sub type for this content.
* @see #getMimeType()
* @return the MIME media type when content-type is specified,
* otherwise the correct default (<code>PLAIN</code>)
*/
String getSubType();
/**
* <p>The body descriptors character set, defaulted appropriately for the MIME type.</p>
* <p>
* For <code>TEXT</code> types, this will be defaulted to <code>us-ascii</code>.
* For other types, when the charset parameter is missing this property will be null.
* </p>
* @return Character set, which has been parsed from the
* content-type definition. Not null for <code>TEXT</code> types, when unset will
* be set to default <code>us-ascii</code>. For other types, when unset,
* null will be returned.
*/
String getCharset();
/**
* Returns the body descriptors transfer encoding.
* @return The transfer encoding. Must not be null, but "7bit",
* if no transfer-encoding was specified.
*/
String getTransferEncoding();
/**
* Returns the body descriptors content-length.
* @return Content length, if known, or -1, to indicate the absence of a
* content-length header.
*/
long getContentLength();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.ogt.http.entity.mime.MIME;
/**
*
* @since 4.0
*/
public class StringBody extends AbstractContentBody {
private final byte[] content;
private final Charset charset;
/**
* @since 4.1
*/
public static StringBody create(
final String text,
final String mimeType,
final Charset charset) throws IllegalArgumentException {
try {
return new StringBody(text, mimeType, charset);
} catch (UnsupportedEncodingException ex) {
throw new IllegalArgumentException("Charset " + charset + " is not supported", ex);
}
}
/**
* @since 4.1
*/
public static StringBody create(
final String text, final Charset charset) throws IllegalArgumentException {
return create(text, null, charset);
}
/**
* @since 4.1
*/
public static StringBody create(final String text) throws IllegalArgumentException {
return create(text, null, null);
}
/**
* Create a StringBody from the specified text, mime type and character set.
*
* @param text to be used for the body, not {@code null}
* @param mimeType the mime type, not {@code null}
* @param charset the character set, may be {@code null}, in which case the US-ASCII charset is used
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException if the {@code text} parameter is null
*/
public StringBody(
final String text,
final String mimeType,
Charset charset) throws UnsupportedEncodingException {
super(mimeType);
if (text == null) {
throw new IllegalArgumentException("Text may not be null");
}
if (charset == null) {
charset = Charset.forName("US-ASCII");
}
this.content = text.getBytes(charset.name());
this.charset = charset;
}
/**
* Create a StringBody from the specified text and character set.
* The mime type is set to "text/plain".
*
* @param text to be used for the body, not {@code null}
* @param charset the character set, may be {@code null}, in which case the US-ASCII charset is used
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException if the {@code text} parameter is null
*/
public StringBody(final String text, final Charset charset) throws UnsupportedEncodingException {
this(text, "text/plain", charset);
}
/**
* Create a StringBody from the specified text.
* The mime type is set to "text/plain".
* The hosts default charset is used.
*
* @param text to be used for the body, not {@code null}
* @throws UnsupportedEncodingException
* @throws IllegalArgumentException if the {@code text} parameter is null
*/
public StringBody(final String text) throws UnsupportedEncodingException {
this(text, "text/plain", null);
}
public Reader getReader() {
return new InputStreamReader(
new ByteArrayInputStream(this.content),
this.charset);
}
/**
* @deprecated use {@link #writeTo(OutputStream)}
*/
@Deprecated
public void writeTo(final OutputStream out, int mode) throws IOException {
writeTo(out);
}
public void writeTo(final OutputStream out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
InputStream in = new ByteArrayInputStream(this.content);
byte[] tmp = new byte[4096];
int l;
while ((l = in.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
}
public String getTransferEncoding() {
return MIME.ENC_8BIT;
}
public String getCharset() {
return this.charset.name();
}
public long getContentLength() {
return this.content.length;
}
public String getFilename() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime.content;
/**
*
* @since 4.0
*/
public abstract class AbstractContentBody implements ContentBody {
private final String mimeType;
private final String mediaType;
private final String subType;
public AbstractContentBody(final String mimeType) {
super();
if (mimeType == null) {
throw new IllegalArgumentException("MIME type may not be null");
}
this.mimeType = mimeType;
int i = mimeType.indexOf('/');
if (i != -1) {
this.mediaType = mimeType.substring(0, i);
this.subType = mimeType.substring(i + 1);
} else {
this.mediaType = mimeType;
this.subType = null;
}
}
public String getMimeType() {
return this.mimeType;
}
public String getMediaType() {
return this.mediaType;
}
public String getSubType() {
return this.subType;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.entity.mime.content.ContentBody;
import org.apache.ogt.http.util.ByteArrayBuffer;
/**
* HttpMultipart represents a collection of MIME multipart encoded content bodies. This class is
* capable of operating either in the strict (RFC 822, RFC 2045, RFC 2046 compliant) or
* the browser compatible modes.
*
* @since 4.0
*/
public class HttpMultipart {
private static ByteArrayBuffer encode(
final Charset charset, final String string) {
ByteBuffer encoded = charset.encode(CharBuffer.wrap(string));
ByteArrayBuffer bab = new ByteArrayBuffer(encoded.remaining());
bab.append(encoded.array(), encoded.position(), encoded.remaining());
return bab;
}
private static void writeBytes(
final ByteArrayBuffer b, final OutputStream out) throws IOException {
out.write(b.buffer(), 0, b.length());
}
private static void writeBytes(
final String s, final Charset charset, final OutputStream out) throws IOException {
ByteArrayBuffer b = encode(charset, s);
writeBytes(b, out);
}
private static void writeBytes(
final String s, final OutputStream out) throws IOException {
ByteArrayBuffer b = encode(MIME.DEFAULT_CHARSET, s);
writeBytes(b, out);
}
private static void writeField(
final MinimalField field, final OutputStream out) throws IOException {
writeBytes(field.getName(), out);
writeBytes(FIELD_SEP, out);
writeBytes(field.getBody(), out);
writeBytes(CR_LF, out);
}
private static void writeField(
final MinimalField field, final Charset charset, final OutputStream out) throws IOException {
writeBytes(field.getName(), charset, out);
writeBytes(FIELD_SEP, out);
writeBytes(field.getBody(), charset, out);
writeBytes(CR_LF, out);
}
private static final ByteArrayBuffer FIELD_SEP = encode(MIME.DEFAULT_CHARSET, ": ");
private static final ByteArrayBuffer CR_LF = encode(MIME.DEFAULT_CHARSET, "\r\n");
private static final ByteArrayBuffer TWO_DASHES = encode(MIME.DEFAULT_CHARSET, "--");
private final String subType;
private final Charset charset;
private final String boundary;
private final List<FormBodyPart> parts;
private final HttpMultipartMode mode;
/**
* Creates an instance with the specified settings.
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @param mode the mode to use
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpMultipart(final String subType, final Charset charset, final String boundary, HttpMultipartMode mode) {
super();
if (subType == null) {
throw new IllegalArgumentException("Multipart subtype may not be null");
}
if (boundary == null) {
throw new IllegalArgumentException("Multipart boundary may not be null");
}
this.subType = subType;
this.charset = charset != null ? charset : MIME.DEFAULT_CHARSET;
this.boundary = boundary;
this.parts = new ArrayList<FormBodyPart>();
this.mode = mode;
}
/**
* Creates an instance with the specified settings.
* Mode is set to {@link HttpMultipartMode#STRICT}
*
* @param subType mime subtype - must not be {@code null}
* @param charset the character set to use. May be {@code null}, in which case {@link MIME#DEFAULT_CHARSET} - i.e. US-ASCII - is used.
* @param boundary to use - must not be {@code null}
* @throws IllegalArgumentException if charset is null or boundary is null
*/
public HttpMultipart(final String subType, final Charset charset, final String boundary) {
this(subType, charset, boundary, HttpMultipartMode.STRICT);
}
public HttpMultipart(final String subType, final String boundary) {
this(subType, null, boundary);
}
public String getSubType() {
return this.subType;
}
public Charset getCharset() {
return this.charset;
}
public HttpMultipartMode getMode() {
return this.mode;
}
public List<FormBodyPart> getBodyParts() {
return this.parts;
}
public void addBodyPart(final FormBodyPart part) {
if (part == null) {
return;
}
this.parts.add(part);
}
public String getBoundary() {
return this.boundary;
}
private void doWriteTo(
final HttpMultipartMode mode,
final OutputStream out,
boolean writeContent) throws IOException {
ByteArrayBuffer boundary = encode(this.charset, getBoundary());
for (FormBodyPart part: this.parts) {
writeBytes(TWO_DASHES, out);
writeBytes(boundary, out);
writeBytes(CR_LF, out);
Header header = part.getHeader();
switch (mode) {
case STRICT:
for (MinimalField field: header) {
writeField(field, out);
}
break;
case BROWSER_COMPATIBLE:
// Only write Content-Disposition
// Use content charset
MinimalField cd = part.getHeader().getField(MIME.CONTENT_DISPOSITION);
writeField(cd, this.charset, out);
String filename = part.getBody().getFilename();
if (filename != null) {
MinimalField ct = part.getHeader().getField(MIME.CONTENT_TYPE);
writeField(ct, this.charset, out);
}
break;
}
writeBytes(CR_LF, out);
if (writeContent) {
part.getBody().writeTo(out);
}
writeBytes(CR_LF, out);
}
writeBytes(TWO_DASHES, out);
writeBytes(boundary, out);
writeBytes(TWO_DASHES, out);
writeBytes(CR_LF, out);
}
/**
* Writes out the content in the multipart/form encoding. This method
* produces slightly different formatting depending on its compatibility
* mode.
*
* @see #getMode()
*/
public void writeTo(final OutputStream out) throws IOException {
doWriteTo(this.mode, out, true);
}
/**
* Determines the total length of the multipart content (content length of
* individual parts plus that of extra elements required to delimit the parts
* from one another). If any of the @{link BodyPart}s contained in this object
* is of a streaming entity of unknown length the total length is also unknown.
* <p/>
* This method buffers only a small amount of data in order to determine the
* total length of the entire entity. The content of individual parts is not
* buffered.
*
* @return total length of the multipart entity if known, <code>-1</code>
* otherwise.
*/
public long getTotalLength() {
long contentLen = 0;
for (FormBodyPart part: this.parts) {
ContentBody body = part.getBody();
long len = body.getContentLength();
if (len >= 0) {
contentLen += len;
} else {
return -1;
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
doWriteTo(this.mode, out, false);
byte[] extra = out.toByteArray();
return contentLen + extra.length;
} catch (IOException ex) {
// Should never happen
return -1;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The header of an entity (see RFC 2045).
*/
public class Header implements Iterable<MinimalField> {
private final List<MinimalField> fields;
private final Map<String, List<MinimalField>> fieldMap;
public Header() {
super();
this.fields = new LinkedList<MinimalField>();
this.fieldMap = new HashMap<String, List<MinimalField>>();
}
public void addField(final MinimalField field) {
if (field == null) {
return;
}
String key = field.getName().toLowerCase(Locale.US);
List<MinimalField> values = this.fieldMap.get(key);
if (values == null) {
values = new LinkedList<MinimalField>();
this.fieldMap.put(key, values);
}
values.add(field);
this.fields.add(field);
}
public List<MinimalField> getFields() {
return new ArrayList<MinimalField>(this.fields);
}
public MinimalField getField(final String name) {
if (name == null) {
return null;
}
String key = name.toLowerCase(Locale.US);
List<MinimalField> list = this.fieldMap.get(key);
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
public List<MinimalField> getFields(final String name) {
if (name == null) {
return null;
}
String key = name.toLowerCase(Locale.US);
List<MinimalField> list = this.fieldMap.get(key);
if (list == null || list.isEmpty()) {
return Collections.emptyList();
} else {
return new ArrayList<MinimalField>(list);
}
}
public int removeFields(final String name) {
if (name == null) {
return 0;
}
String key = name.toLowerCase(Locale.US);
List<MinimalField> removed = fieldMap.remove(key);
if (removed == null || removed.isEmpty()) {
return 0;
}
this.fields.removeAll(removed);
return removed.size();
}
public void setField(final MinimalField field) {
if (field == null) {
return;
}
String key = field.getName().toLowerCase(Locale.US);
List<MinimalField> list = fieldMap.get(key);
if (list == null || list.isEmpty()) {
addField(field);
return;
}
list.clear();
list.add(field);
int firstOccurrence = -1;
int index = 0;
for (Iterator<MinimalField> it = this.fields.iterator(); it.hasNext(); index++) {
MinimalField f = it.next();
if (f.getName().equalsIgnoreCase(field.getName())) {
it.remove();
if (firstOccurrence == -1) {
firstOccurrence = index;
}
}
}
this.fields.add(firstOccurrence, field);
}
public Iterator<MinimalField> iterator() {
return Collections.unmodifiableList(fields).iterator();
}
@Override
public String toString() {
return this.fields.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
import org.apache.ogt.http.entity.mime.content.ContentBody;
/**
* FormBodyPart class represents a content body that can be used as a part of multipart encoded
* entities. This class automatically populates the header with standard fields based on
* the content description of the enclosed body.
*
* @since 4.0
*/
public class FormBodyPart {
private final String name;
private final Header header;
private final ContentBody body;
public FormBodyPart(final String name, final ContentBody body) {
super();
if (name == null) {
throw new IllegalArgumentException("Name may not be null");
}
if (body == null) {
throw new IllegalArgumentException("Body may not be null");
}
this.name = name;
this.body = body;
this.header = new Header();
generateContentDisp(body);
generateContentType(body);
generateTransferEncoding(body);
}
public String getName() {
return this.name;
}
public ContentBody getBody() {
return this.body;
}
public Header getHeader() {
return this.header;
}
public void addField(final String name, final String value) {
if (name == null) {
throw new IllegalArgumentException("Field name may not be null");
}
this.header.addField(new MinimalField(name, value));
}
protected void generateContentDisp(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append("form-data; name=\"");
buffer.append(getName());
buffer.append("\"");
if (body.getFilename() != null) {
buffer.append("; filename=\"");
buffer.append(body.getFilename());
buffer.append("\"");
}
addField(MIME.CONTENT_DISPOSITION, buffer.toString());
}
protected void generateContentType(final ContentBody body) {
StringBuilder buffer = new StringBuilder();
buffer.append(body.getMimeType()); // MimeType cannot be null
if (body.getCharset() != null) { // charset may legitimately be null
buffer.append("; charset=");
buffer.append(body.getCharset());
}
addField(MIME.CONTENT_TYPE, buffer.toString());
}
protected void generateTransferEncoding(final ContentBody body) {
addField(MIME.CONTENT_TRANSFER_ENC, body.getTransferEncoding()); // TE cannot be null
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.entity.mime;
/**
*
* @since 4.0
*/
public enum HttpMultipartMode {
/** RFC 822, RFC 2045, RFC 2046 compliant */
STRICT,
/** browser-compatible mode, i.e. only write Content-Disposition; use content charset */
BROWSER_COMPATIBLE
}
| Java |
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples.entity.mime;
import java.io.File;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.client.HttpClient;
import org.apache.ogt.http.client.methods.HttpPost;
import org.apache.ogt.http.entity.mime.MultipartEntity;
import org.apache.ogt.http.entity.mime.content.FileBody;
import org.apache.ogt.http.entity.mime.content.StringBody;
import org.apache.ogt.http.impl.client.DefaultHttpClient;
import org.apache.ogt.http.util.EntityUtils;
/**
* Example how to use multipart/form encoded POST request.
*/
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("File path not given");
System.exit(1);
}
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio;
import java.io.IOException;
import java.nio.channels.FileChannel;
import org.apache.http.nio.ContentEncoder;
/**
* A content encoder capable of transferring data directly from a {@link FileChannel}
*
* @since 4.0
*/
public interface FileContentEncoder extends ContentEncoder {
/**
* Transfers a portion of entity content from the given file channel
* to the underlying network channel.
*
* @param src the source FileChannel to transfer data from.
* @param position
* The position within the file at which the transfer is to begin;
* must be non-negative
* @param count
* The maximum number of bytes to be transferred; must be
* non-negative
*@throws IOException, if some I/O error occurs.
* @return The number of bytes, possibly zero,
* that were actually transferred
*/
long transfer(FileChannel src, long position, long count) throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
/**
* Abstract exception handler intended to deal with potentially recoverable
* I/O exceptions thrown by an I/O reactor.
*
* @since 4.0
*/
public interface IOReactorExceptionHandler {
/**
* This method is expected to examine the I/O exception passed as
* a parameter and decide whether it is safe to continue execution of
* the I/O reactor.
*
* @param ex potentially recoverable I/O exception
* @return <code>true</code> if it is safe to ignore the exception
* and continue execution of the I/O reactor; <code>false</code> if the
* I/O reactor must throw {@link IOReactorException} and terminate
*/
boolean handle(IOException ex);
/**
* This method is expected to examine the runtime exception passed as
* a parameter and decide whether it is safe to continue execution of
* the I/O reactor.
*
* @param ex potentially recoverable runtime exception
* @return <code>true</code> if it is safe to ignore the exception
* and continue execution of the I/O reactor; <code>false</code> if the
* I/O reactor must throw {@link RuntimeException} and terminate
*/
boolean handle(RuntimeException ex);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import org.apache.http.util.CharArrayBuffer;
/**
* Session output buffer for non-blocking connections. This interface
* facilitates intermediate buffering of output data streamed out to
* a destination channel and writing data to the buffer from a source, usually
* {@link ByteBuffer} or {@link ReadableByteChannel}. This interface also
* provides methods for writing lines of text.
*
* @since 4.0
*/
public interface SessionOutputBuffer {
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
boolean hasData();
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
int length();
/**
* Makes an attempt to flush the content of this buffer to the given
* destination {@link WritableByteChannel}.
*
* @param channel the destination channel.
* @return The number of bytes written, possibly zero.
* @throws IOException in case of an I/O error.
*/
int flush(WritableByteChannel channel)
throws IOException;
/**
* Copies content of the source buffer into this buffer. The capacity of
* the destination will be expanded in order to accommodate the entire
* content of the source buffer.
*
* @param src the source buffer.
*/
void write(ByteBuffer src);
/**
* Reads a sequence of bytes from the source channel into this buffer.
*
* @param src the source channel.
*/
void write(ReadableByteChannel src)
throws IOException;
/**
* Copies content of the source buffer into this buffer as one line of text
* including a line delimiter. The capacity of the destination will be
* expanded in order to accommodate the entire content of the source buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param src the source buffer.
*/
void writeLine(CharArrayBuffer src)
throws CharacterCodingException;
/**
* Copies content of the given string into this buffer as one line of text
* including a line delimiter.
* The capacity of the destination will be expanded in order to accommodate
* the entire string.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param s the string.
*/
void writeLine(String s)
throws IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.nio.channels.SelectionKey;
/**
* Type of I/O event notifications I/O sessions can declare interest in.
*
* @since 4.0
*/
public interface EventMask {
/**
* Interest in data input.
*/
public static final int READ = SelectionKey.OP_READ;
/**
* Interest in data output.
*/
public static final int WRITE = SelectionKey.OP_WRITE;
/**
* Interest in data input/output.
*/
public static final int READ_WRITE = READ | WRITE;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.net.SocketAddress;
/**
* ListenerEndpoint interface represents an endpoint used by an I/O reactor
* to listen for incoming connection from remote clients.
*
* @since 4.0
*/
public interface ListenerEndpoint {
/**
* Returns the socket address of this endpoint.
*
* @return socket address.
*/
SocketAddress getAddress();
/**
* Returns an instance of {@link IOException} thrown during initialization
* of this endpoint or <code>null</code>, if initialization was successful.
*
* @return I/O exception object or <code>null</code>.
*/
IOException getException();
/**
* Waits for completion of initialization process of this endpoint.
*
* @throws InterruptedException in case the initialization process was
* interrupted.
*/
void waitFor() throws InterruptedException;
/**
* Determines if this endpoint has been closed and is no longer listens
* for incoming connections.
*
* @return <code>true</code> if the endpoint has been closed,
* <code>false</code> otherwise.
*/
boolean isClosed();
/**
* Closes this endpoint. The endpoint will stop accepting incoming
* connection.
*/
void close();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
/**
* SessionRequestCallback interface can be used to get notifications of
* completion of session requests asynchronously without having to wait
* for it, blocking the current thread of execution.
*
* @since 4.0
*/
public interface SessionRequestCallback {
/**
* Triggered on successful completion of a {@link SessionRequest}.
* The {@link SessionRequest#getSession()} method can now be used to obtain
* the new I/O session.
*
* @param request session request.
*/
void completed(SessionRequest request);
/**
* Triggered on unsuccessful completion a {@link SessionRequest}.
* The {@link SessionRequest#getException()} method can now be used to
* obtain the cause of the error.
*
* @param request session request.
*/
void failed(SessionRequest request);
/**
* Triggered if a {@link SessionRequest} times out.
*
* @param request session request.
*/
void timeout(SessionRequest request);
/**
* Triggered on cancellation of a {@link SessionRequest}.
*
* @param request session request.
*/
void cancelled(SessionRequest request);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.net.SocketAddress;
import java.nio.channels.ByteChannel;
/**
* IOSession interface represents a sequence of logically related data exchanges
* between two end points.
* <p>
* The channel associated with implementations of this interface can be used to
* read data from and write data to the session.
* <p>
* I/O sessions are not bound to an execution thread, therefore one cannot use
* the context of the thread to store a session's state. All details about
* a particular session must be stored within the session itself, usually
* using execution context associated with it.
* <p>
* Implementations of this interface are expected to be threading safe.
*
* @since 4.0
*/
public interface IOSession {
/**
* Name of the context attribute key, which can be used to obtain the
* session attachment object.
*/
public static final String ATTACHMENT_KEY = "http.session.attachment";
public static final int ACTIVE = 0;
public static final int CLOSING = 1;
public static final int CLOSED = Integer.MAX_VALUE;
/**
* Returns the underlying I/O channel associated with this session.
*
* @return the I/O channel.
*/
ByteChannel channel();
/**
* Returns address of the remote peer.
*
* @return socket address.
*/
SocketAddress getRemoteAddress();
/**
* Returns local address.
*
* @return socket address.
*/
SocketAddress getLocalAddress();
/**
* Returns mask of I/O evens this session declared interest in.
*
* @return I/O event mask.
*/
int getEventMask();
/**
* Declares interest in I/O event notifications by setting the event mask
* associated with the session
*
* @param ops new I/O event mask.
*/
void setEventMask(int ops);
/**
* Declares interest in a particular I/O event type by updating the event
* mask associated with the session.
*
* @param op I/O event type.
*/
void setEvent(int op);
/**
* Clears interest in a particular I/O event type by updating the event
* mask associated with the session.
*
* @param op I/O event type.
*/
void clearEvent(int op);
/**
* Terminates the session gracefully and closes the underlying I/O channel.
* This method ensures that session termination handshake, such as the one
* used by the SSL/TLS protocol, is correctly carried out.
*/
void close();
/**
* Terminates the session by shutting down the underlying I/O channel.
*/
void shutdown();
/**
* Returns status of the session:
* <p>
* {@link #ACTIVE}: session is active.
* <p>
* {@link #CLOSING}: session is being closed.
* <p>
* {@link #CLOSED}: session has been terminated.
*
* @return session status.
*/
int getStatus();
/**
* Determines if the session has been terminated.
*
* @return <code>true</code> if the session has been terminated,
* <code>false</code> otherwise.
*/
boolean isClosed();
/**
* Returns value of the socket timeout in milliseconds. The value of
* <code>0</code> signifies the session cannot time out.
*
* @return socket timeout.
*/
int getSocketTimeout();
/**
* Sets value of the socket timeout in milliseconds. The value of
* <code>0</code> signifies the session cannot time out.
*
* @param timeout socket timeout.
*/
void setSocketTimeout(int timeout);
/**
* Quite often I/O sessions need to maintain internal I/O buffers in order
* to transform input / output data prior to returning it to the consumer or
* writing it to the underlying channel. Memory management in HttpCore NIO
* is based on the fundamental principle that the data consumer can read
* only as much input data as it can process without having to allocate more
* memory. That means, quite often some input data may remain unread in one
* of the internal or external session buffers. The I/O reactor can query
* the status of these session buffers, and make sure the consumer gets
* notified correctly as more data gets stored in one of the session
* buffers, thus allowing the consumer to read the remaining data once it
* is able to process it
* <p>
* I/O sessions can be made aware of the status of external session buffers
* using the {@link SessionBufferStatus} interface.
*
* @param status
*/
void setBufferStatus(SessionBufferStatus status);
/**
* Determines if the input buffer associated with the session contains data.
*
* @return <code>true</code> if the session input buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedInput();
/**
* Determines if the output buffer associated with the session contains
* data.
*
* @return <code>true</code> if the session output buffer contains data,
* <code>false</code> otherwise.
*/
boolean hasBufferedOutput();
/**
* This method can be used to associate a particular object with the
* session by the given attribute name.
* <p>
* I/O sessions are not bound to an execution thread, therefore one cannot
* use the context of the thread to store a session's state. All details
* about a particular session must be stored within the session itself.
*
* @param name name of the attribute.
* @param obj value of the attribute.
*/
void setAttribute(String name, Object obj);
/**
* Returns the value of the attribute with the given name. The value can be
* <code>null</code> if not set.
* <p>
* The value of the session attachment object can be obtained using
* {@link #ATTACHMENT_KEY} name.
*
* @see #setAttribute(String, Object)
*
* @param name name of the attribute.
* @return value of the attribute.
*/
Object getAttribute(String name);
/**
* Removes attribute with the given name.
*
* @see #setAttribute(String, Object)
*
* @param name name of the attribute to be removed.
* @return value of the removed attribute.
*/
Object removeAttribute(String name);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.nio.reactor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.CharacterCodingException;
import org.apache.http.util.CharArrayBuffer;
/**
* Session input buffer for non-blocking connections. This interface facilitates
* intermediate buffering of input data streamed from a source channel and
* reading buffered data to a destination, usually {@link ByteBuffer} or
* {@link WritableByteChannel}. This interface also provides methods for reading
* lines of text.
*
* @since 4.0
*/
public interface SessionInputBuffer {
/**
* Determines if the buffer contains data.
*
* @return <code>true</code> if there is data in the buffer,
* <code>false</code> otherwise.
*/
boolean hasData();
/**
* Returns the length of this buffer.
*
* @return buffer length.
*/
int length();
/**
* Makes an attempt to fill the buffer with data from the given
* {@link ReadableByteChannel}.
*
* @param src the source channel
* @return The number of bytes read, possibly zero, or <tt>-1</tt> if the
* channel has reached end-of-stream.
* @throws IOException in case of an I/O error.
*/
int fill(ReadableByteChannel src) throws IOException;
/**
* Reads one byte from the buffer. If the buffer is empty this method can
* throw a runtime exception. The exact type of runtime exception thrown
* by this method depends on implementation.
*
* @return one byte
*/
int read();
/**
* Reads a sequence of bytes from this buffer into the destination buffer,
* up to the given maximum limit. The exact number of bytes transferred
* depends on availability of data in this buffer and capacity of the
* destination buffer, but cannot be more than <code>maxLen</code> value.
*
* @param dst the destination buffer.
* @param maxLen the maximum number of bytes to be read.
* @return The number of bytes read, possibly zero.
*/
int read(ByteBuffer dst, int maxLen);
/**
* Reads a sequence of bytes from this buffer into the destination buffer.
* The exact number of bytes transferred depends on availability of data
* in this buffer and capacity of the destination buffer.
*
* @param dst the destination buffer.
* @return The number of bytes read, possibly zero.
*/
int read(ByteBuffer dst);
/**
* Reads a sequence of bytes from this buffer into the destination channel,
* up to the given maximum limit. The exact number of bytes transferred
* depends on availability of data in this buffer, but cannot be more than
* <code>maxLen</code> value.
*
* @param dst the destination channel.
* @param maxLen the maximum number of bytes to be read.
* @return The number of bytes read, possibly zero.
* @throws IOException in case of an I/O error.
*/
int read(WritableByteChannel dst, int maxLen) throws IOException;
/**
* Reads a sequence of bytes from this buffer into the destination channel.
* The exact number of bytes transferred depends on availability of data in
* this buffer.
*
* @param dst the destination channel.
* @return The number of bytes read, possibly zero.
* @throws IOException in case of an I/O error.
*/
int read(WritableByteChannel dst) throws IOException;
/**
* Attempts to transfer a complete line of characters up to a line delimiter
* from this buffer to the destination buffer. If a complete line is
* available in the buffer, the sequence of chars is transferred to the
* destination buffer the method returns <code>true</code>. The line
* delimiter itself is discarded. If a complete line is not available in
* the buffer, this method returns <code>false</code> without transferring
* anything to the destination buffer. If <code>endOfStream</code> parameter
* is set to <code>true</code> this method assumes the end of stream has
* been reached and the content currently stored in the buffer should be
* treated as a complete line.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param dst the destination buffer.
* @param endOfStream
* @return <code>true</code> if a sequence of chars representing a complete
* line has been transferred to the destination buffer, <code>false</code>
* otherwise.
*
* @throws CharacterCodingException in case a character encoding or decoding
* error occurs.
*/
boolean readLine(CharArrayBuffer dst, boolean endOfStream)
throws CharacterCodingException;
/**
* Attempts to transfer a complete line of characters up to a line delimiter
* from this buffer to a newly created string. If a complete line is
* available in the buffer, the sequence of chars is transferred to a newly
* created string. The line delimiter itself is discarded. If a complete
* line is not available in the buffer, this method returns
* <code>null</code>. If <code>endOfStream</code> parameter
* is set to <code>true</code> this method assumes the end of stream has
* been reached and the content currently stored in the buffer should be
* treated as a complete line.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param endOfStream
* @return a string representing a complete line, if available.
* <code>null</code> otherwise.
*
* @throws CharacterCodingException in case a character encoding or decoding
* error occurs.
*/
String readLine(boolean endOfStream)
throws CharacterCodingException;
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.