FileDocCategorySizeDatePackage
NtlmHttpURLConnection.javaAPI DocJCIFS 1.3.17 API21463Tue Oct 18 15:26:24 BST 2011jcifs.http

NtlmHttpURLConnection

public class NtlmHttpURLConnection extends HttpURLConnection
Wraps an HttpURLConnection to provide NTLM authentication services. Please read Using jCIFS NTLM Authentication for HTTP Connections.

Fields Summary
private static final int
MAX_REDIRECTS
private static final int
LM_COMPATIBILITY
private static final String
DEFAULT_DOMAIN
private HttpURLConnection
connection
private Map
requestProperties
private Map
headerFields
private ByteArrayOutputStream
cachedOutput
private String
authProperty
private String
authMethod
private boolean
handshakeComplete
Constructors Summary
public NtlmHttpURLConnection(HttpURLConnection connection)


     
        String domain = System.getProperty("http.auth.ntlm.domain");
        if (domain == null) domain = Type3Message.getDefaultDomain();
        DEFAULT_DOMAIN = domain;
    
        super(connection.getURL());
        this.connection = connection;
        requestProperties = new HashMap();
    
Methods Summary
public voidaddRequestProperty(java.lang.String key, java.lang.String value)

        if (key == null) throw new NullPointerException();
        List values = null;
        Iterator entries = requestProperties.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            if (key.equalsIgnoreCase((String) entry.getKey())) {
                values = (List) entry.getValue();
                values.add(value);
                break;
            }
        }
        if (values == null) {
            values = new ArrayList();
            values.add(value);
            requestProperties.put(key, values);
        }
        // 1.3-compatible.
        StringBuffer buffer = new StringBuffer();
        Iterator propertyValues = values.iterator();
        while (propertyValues.hasNext()) {
            buffer.append(propertyValues.next());
            if (propertyValues.hasNext()) {
                buffer.append(", ");
            }
        }
        connection.setRequestProperty(key, buffer.toString());
    
private jcifs.ntlmssp.NtlmMessageattemptNegotiation(int response)

        authProperty = null;
        authMethod = null;
        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null && errorStream.available() != 0) {
            int count;
            byte[] buf = new byte[1024];
            while ((count = errorStream.read(buf, 0, 1024)) != -1);
        }
        String authHeader;
        if (response == HTTP_UNAUTHORIZED) {
            authHeader = "WWW-Authenticate";
            authProperty = "Authorization";
        } else {
            authHeader = "Proxy-Authenticate";
            authProperty = "Proxy-Authorization";
        }
        String authorization = null;
        List methods = (List) getHeaderFields0().get(authHeader);
        if (methods == null) return null;
        Iterator iterator = methods.iterator();
        while (iterator.hasNext()) {
            String currentAuthMethod = (String) iterator.next();
            if (currentAuthMethod.startsWith("NTLM")) {
                if (currentAuthMethod.length() == 4) {
                    authMethod = "NTLM";
                    break;
                }
                if (currentAuthMethod.indexOf(' ") != 4) continue;
                authMethod = "NTLM";
                authorization = currentAuthMethod.substring(5).trim();
                break;
            } else if (currentAuthMethod.startsWith("Negotiate")) {
                if (currentAuthMethod.length() == 9) {
                    authMethod = "Negotiate";
                    break;
                }
                if (currentAuthMethod.indexOf(' ") != 9) continue;
                authMethod = "Negotiate";
                authorization = currentAuthMethod.substring(10).trim();
                break;
            }
        }
        if (authMethod == null) return null;
        NtlmMessage message = (authorization != null) ?
                new Type2Message(Base64.decode(authorization)) : null;
        reconnect();
        if (message == null) {
            message = new Type1Message();
            if (LM_COMPATIBILITY > 2) {
                message.setFlag(NtlmFlags.NTLMSSP_REQUEST_TARGET, true);
            }
        } else {
            String domain = DEFAULT_DOMAIN;
            String user = Type3Message.getDefaultUser();
            String password = Type3Message.getDefaultPassword();
            String userInfo = url.getUserInfo();
            if (userInfo != null) {
                userInfo = URLDecoder.decode(userInfo);
                int index = userInfo.indexOf(':");
                user = (index != -1) ? userInfo.substring(0, index) : userInfo;
                if (index != -1) password = userInfo.substring(index + 1);
                index = user.indexOf('\\");
                if (index == -1) index = user.indexOf('/");
                domain = (index != -1) ? user.substring(0, index) : domain;
                user = (index != -1) ? user.substring(index + 1) : user;
            }
            if (user == null) {
                if (!allowUserInteraction) return null;
                try {
                    URL url = getURL();
                    String protocol = url.getProtocol();
                    int port = url.getPort();
                    if (port == -1) {
                        port = "https".equalsIgnoreCase(protocol) ? 443 : 80;
                    }
                    PasswordAuthentication auth =
                            Authenticator.requestPasswordAuthentication(null,
                                    port, protocol, "", authMethod);
                    if (auth == null) return null;
                    user = auth.getUserName();
                    password = new String(auth.getPassword());
                } catch (Exception ex) { }
            }
            Type2Message type2 = (Type2Message) message;
            message = new Type3Message(type2, password, domain, user,
                    Type3Message.getDefaultWorkstation(), 0);
        }
        return message;
    
public voidconnect()

        if (connected) return;
        connection.connect();
        connected = true;
    
public voiddisconnect()

        connection.disconnect();
        handshakeComplete = false;
        connected = false;
    
private voiddoHandshake()

        connect();
        try {
            int response = parseResponseCode();
            if (response != HTTP_UNAUTHORIZED && response != HTTP_PROXY_AUTH) {
                return;
            }
            Type1Message type1 = (Type1Message) attemptNegotiation(response);
            if (type1 == null) return; // no NTLM
            int attempt = 0;
            while (attempt < MAX_REDIRECTS) {
                connection.setRequestProperty(authProperty, authMethod + ' " +
                        Base64.encode(type1.toByteArray()));
                connection.connect(); // send type 1
                response = parseResponseCode();
                if (response != HTTP_UNAUTHORIZED &&
                        response != HTTP_PROXY_AUTH) {
                    return;
                }
                Type3Message type3 = (Type3Message)
                        attemptNegotiation(response);
                if (type3 == null) return;
                connection.setRequestProperty(authProperty, authMethod + ' " +
                        Base64.encode(type3.toByteArray()));
                connection.connect(); // send type 3
                if (cachedOutput != null && doOutput) {
                    OutputStream output = connection.getOutputStream();
                    cachedOutput.writeTo(output);
                    output.flush();
                }
                response = parseResponseCode();
                if (response != HTTP_UNAUTHORIZED &&
                        response != HTTP_PROXY_AUTH) {
                    return;
                }
                attempt++;
                if (allowUserInteraction && attempt < MAX_REDIRECTS) {
                    reconnect();
                } else {
                    break;
                }
            }
            throw new IOException("Unable to negotiate NTLM authentication.");
        } finally {
            cachedOutput = null;
        }
    
public booleangetAllowUserInteraction()

        return connection.getAllowUserInteraction();
    
public java.lang.ObjectgetContent()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getContent();
    
public java.lang.ObjectgetContent(java.lang.Class[] classes)

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getContent(classes);
    
public java.lang.StringgetContentEncoding()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getContentEncoding();
    
public intgetContentLength()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getContentLength();
    
public java.lang.StringgetContentType()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getContentType();
    
public longgetDate()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getDate();
    
public booleangetDefaultUseCaches()

        return connection.getDefaultUseCaches();
    
public booleangetDoInput()

        return connection.getDoInput();
    
public booleangetDoOutput()

        return connection.getDoOutput();
    
public java.io.InputStreamgetErrorStream()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getErrorStream();
    
public longgetExpiration()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getExpiration();
    
public java.lang.StringgetHeaderField(java.lang.String header)

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getHeaderField(header);
    
public java.lang.StringgetHeaderField(int index)

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getHeaderField(index);
    
public longgetHeaderFieldDate(java.lang.String header, long def)

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getHeaderFieldDate(header, def);
    
public intgetHeaderFieldInt(java.lang.String header, int def)

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getHeaderFieldInt(header, def);
    
public java.lang.StringgetHeaderFieldKey(int index)

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getHeaderFieldKey(index);
    
public java.util.MapgetHeaderFields()

        if (headerFields != null) return headerFields;
        try {
            handshake();
        } catch (IOException ex) { }
        return getHeaderFields0();
    
private java.util.MapgetHeaderFields0()

        if (headerFields != null) return headerFields;
        Map map = new HashMap();
        String key = connection.getHeaderFieldKey(0);
        String value = connection.getHeaderField(0);
        for (int i = 1; key != null || value != null; i++) {
            List values = (List) map.get(key);
            if (values == null) {
                values = new ArrayList();
                map.put(key, values);
            }
            values.add(value);
            key = connection.getHeaderFieldKey(i);
            value = connection.getHeaderField(i);
        }
        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            entry.setValue(Collections.unmodifiableList((List)
                    entry.getValue()));
        }
        return (headerFields = Collections.unmodifiableMap(map));
    
public longgetIfModifiedSince()

        return connection.getIfModifiedSince();
    
public java.io.InputStreamgetInputStream()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getInputStream();
    
public booleangetInstanceFollowRedirects()

        return connection.getInstanceFollowRedirects();
    
public longgetLastModified()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getLastModified();
    
public java.io.OutputStreamgetOutputStream()

        try {
            connect();
        } catch (IOException ex) { }
        OutputStream output = connection.getOutputStream();
        cachedOutput = new ByteArrayOutputStream();
        return new CacheStream(output, cachedOutput);
    
public java.security.PermissiongetPermission()

        return connection.getPermission();
    
public java.lang.StringgetRequestMethod()

        return connection.getRequestMethod();
    
public java.util.MapgetRequestProperties()

        Map map = new HashMap();
        Iterator entries = requestProperties.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            map.put(entry.getKey(),
                    Collections.unmodifiableList((List) entry.getValue()));
        }
        return Collections.unmodifiableMap(map);
    
public java.lang.StringgetRequestProperty(java.lang.String key)

        return connection.getRequestProperty(key);
    
public intgetResponseCode()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getResponseCode();
    
public java.lang.StringgetResponseMessage()

        try {
            handshake();
        } catch (IOException ex) { }
        return connection.getResponseMessage();
    
public java.net.URLgetURL()

        return connection.getURL();
    
public booleangetUseCaches()

        return connection.getUseCaches();
    
private voidhandshake()

        if (handshakeComplete) return;
        doHandshake();
        handshakeComplete = true;
    
private intparseResponseCode()

        try {
            String response = connection.getHeaderField(0);
            int index = response.indexOf(' ");
            while (response.charAt(index) == ' ") index++;
            return Integer.parseInt(response.substring(index, index + 3));
        } catch (Exception ex) {
            throw new IOException(ex.getMessage());
        }
    
private voidreconnect()

        connection = (HttpURLConnection) connection.getURL().openConnection();
        connection.setRequestMethod(method);
        headerFields = null;
        Iterator properties = requestProperties.entrySet().iterator();
        while (properties.hasNext()) {
            Map.Entry property = (Map.Entry) properties.next();
            String key = (String) property.getKey();
            StringBuffer value = new StringBuffer();
            Iterator values = ((List) property.getValue()).iterator();
            while (values.hasNext()) {
                value.append(values.next());
                if (values.hasNext()) value.append(", ");
            }
            connection.setRequestProperty(key, value.toString());
        }
        connection.setAllowUserInteraction(allowUserInteraction);
        connection.setDoInput(doInput);
        connection.setDoOutput(doOutput);
        connection.setIfModifiedSince(ifModifiedSince);
        connection.setUseCaches(useCaches);
    
public voidsetAllowUserInteraction(boolean allowUserInteraction)

        connection.setAllowUserInteraction(allowUserInteraction);
        this.allowUserInteraction = allowUserInteraction;
    
public voidsetDefaultUseCaches(boolean defaultUseCaches)

        connection.setDefaultUseCaches(defaultUseCaches);
    
public voidsetDoInput(boolean doInput)

        connection.setDoInput(doInput);
        this.doInput = doInput;
    
public voidsetDoOutput(boolean doOutput)

        connection.setDoOutput(doOutput);
        this.doOutput = doOutput;
    
public voidsetIfModifiedSince(long ifModifiedSince)

        connection.setIfModifiedSince(ifModifiedSince);
        this.ifModifiedSince = ifModifiedSince;
    
public voidsetInstanceFollowRedirects(boolean instanceFollowRedirects)

        connection.setInstanceFollowRedirects(instanceFollowRedirects);
    
public voidsetRequestMethod(java.lang.String requestMethod)

        connection.setRequestMethod(requestMethod);
        this.method = requestMethod;
    
public voidsetRequestProperty(java.lang.String key, java.lang.String value)

        if (key == null) throw new NullPointerException();
        List values = new ArrayList();
        values.add(value);
        boolean found = false;
        Iterator entries = requestProperties.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            if (key.equalsIgnoreCase((String) entry.getKey())) {
                entry.setValue(values);
                found = true;
                break;
            }
        }
        if (!found) requestProperties.put(key, values);
        connection.setRequestProperty(key, value);
    
public voidsetUseCaches(boolean useCaches)

        connection.setUseCaches(useCaches);
        this.useCaches = useCaches;
    
public java.lang.StringtoString()

        return connection.toString();
    
public booleanusingProxy()

        return connection.usingProxy();