Example usage for org.apache.http.protocol HttpContext getAttribute

List of usage examples for org.apache.http.protocol HttpContext getAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext getAttribute.

Prototype

Object getAttribute(String str);

Source Link

Usage

From source file:org.apache.axis2.transport.nhttp.ServerHandler.java

/**
 * Process ready output by writing into the channel
 * @param conn the connection being processed
 * @param encoder the content encoder in use
 *//*from w w  w .j ava 2  s . c o  m*/
public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {

    HttpContext context = conn.getContext();
    HttpResponse response = conn.getHttpResponse();
    Pipe.SourceChannel source = (Pipe.SourceChannel) context.getAttribute(RESPONSE_SOURCE_CHANNEL);
    ByteBuffer outbuf = (ByteBuffer) context.getAttribute(RESPONSE_BUFFER);

    try {
        int bytesRead = source.read(outbuf);
        if (bytesRead == -1) {
            encoder.complete();
        } else {
            outbuf.flip();
            encoder.write(outbuf);
            outbuf.compact();
        }

        if (encoder.isCompleted()) {
            source.close();
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            }
        }

    } catch (IOException e) {
        handleException("I/O Error : " + e.getMessage(), e, conn);
    }
}

From source file:org.apache.http.client.protocol.RequestProxyAuthentication.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }//from   w  w w . jav  a  2  s.co  m
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (authState == null) {
        return;
    }

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        return;
    }

    Credentials creds = authState.getCredentials();
    if (creds == null) {
        this.log.debug("User credentials not available");
        return;
    }
    if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
        try {
            request.addHeader(authScheme.authenticate(creds, request));
        } catch (AuthenticationException ex) {
            if (this.log.isErrorEnabled()) {
                this.log.error("Proxy authentication error: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.http.client.protocol.RequestTargetAuthentication.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }/*from w ww. java2s .c  o  m*/
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;
    }

    if (request.containsHeader(AUTH.WWW_AUTH_RESP)) {
        return;
    }

    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (authState == null) {
        return;
    }

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        return;
    }

    Credentials creds = authState.getCredentials();
    if (creds == null) {
        this.log.debug("User credentials not available");
        return;
    }

    if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
        try {
            request.addHeader(authScheme.authenticate(creds, request));
        } catch (AuthenticationException ex) {
            if (this.log.isErrorEnabled()) {
                this.log.error("Authentication error: " + ex.getMessage());
            }
        }
    }
}

From source file:org.apache.http.client.protocol.ResponseAuthCache.java

public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    Args.notNull(response, "HTTP request");
    Args.notNull(context, "HTTP context");
    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);

    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (target != null && targetState != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Target auth state: " + targetState.getState());
        }/* w w  w. jav a 2s .  c  o  m*/
        if (isCachable(targetState)) {
            final SchemeRegistry schemeRegistry = (SchemeRegistry) context
                    .getAttribute(ClientContext.SCHEME_REGISTRY);
            if (target.getPort() < 0) {
                final Scheme scheme = schemeRegistry.getScheme(target);
                target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()),
                        target.getSchemeName());
            }
            if (authCache == null) {
                authCache = new BasicAuthCache();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            }
            switch (targetState.getState()) {
            case CHALLENGED:
                cache(authCache, target, targetState.getAuthScheme());
                break;
            case FAILURE:
                uncache(authCache, target, targetState.getAuthScheme());
            }
        }
    }

    final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
    final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (proxy != null && proxyState != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Proxy auth state: " + proxyState.getState());
        }
        if (isCachable(proxyState)) {
            if (authCache == null) {
                authCache = new BasicAuthCache();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            }
            switch (proxyState.getState()) {
            case CHALLENGED:
                cache(authCache, proxy, proxyState.getAuthScheme());
                break;
            case FAILURE:
                uncache(authCache, proxy, proxyState.getAuthScheme());
            }
        }
    }
}

From source file:org.apache.http.impl.auth.GGSSchemeBase.java

@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {
    Args.notNull(request, "HTTP request");
    switch (state) {
    case UNINITIATED:
        throw new AuthenticationException(getSchemeName() + " authentication has not been initiated");
    case FAILED:/*from ww  w  . jav  a2  s . c  om*/
        throw new AuthenticationException(getSchemeName() + " authentication has failed");
    case CHALLENGE_RECEIVED:
        try {
            final HttpRoute route = (HttpRoute) context.getAttribute(HttpClientContext.HTTP_ROUTE);
            if (route == null) {
                throw new AuthenticationException("Connection route is not available");
            }
            HttpHost host;
            if (isProxy()) {
                host = route.getProxyHost();
                if (host == null) {
                    host = route.getTargetHost();
                }
            } else {
                host = route.getTargetHost();
            }
            final String authServer;
            if (!this.stripPort && host.getPort() > 0) {
                authServer = host.toHostString();
            } else {
                authServer = host.getHostName();
            }

            if (log.isDebugEnabled()) {
                log.debug("init " + authServer);
            }
            token = generateToken(token, authServer);
            state = State.TOKEN_GENERATED;
        } catch (final GSSException gsse) {
            state = State.FAILED;
            if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                    || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) {
                throw new InvalidCredentialsException(gsse.getMessage(), gsse);
            }
            if (gsse.getMajor() == GSSException.NO_CRED) {
                throw new InvalidCredentialsException(gsse.getMessage(), gsse);
            }
            if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN
                    || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                    || gsse.getMajor() == GSSException.OLD_TOKEN) {
                throw new AuthenticationException(gsse.getMessage(), gsse);
            }
            // other error
            throw new AuthenticationException(gsse.getMessage());
        }
    case TOKEN_GENERATED:
        final String tokenstr = new String(base64codec.encode(token));
        if (log.isDebugEnabled()) {
            log.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        final CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    default:
        throw new IllegalStateException("Illegal state: " + state);
    }
}

From source file:org.apache.http.impl.client.AbstractAuthenticationHandler.java

public AuthScheme selectScheme(final Map<String, Header> challenges, final HttpResponse response,
        final HttpContext context) throws AuthenticationException {

    final AuthSchemeRegistry registry = (AuthSchemeRegistry) context
            .getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
    Asserts.notNull(registry, "AuthScheme registry");
    Collection<String> authPrefs = getAuthPreferences(response, context);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }//from w w w .  jav a 2 s. co m

    if (this.log.isDebugEnabled()) {
        this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
    }

    AuthScheme authScheme = null;
    for (final String id : authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));

        if (challenge != null) {
            if (this.log.isDebugEnabled()) {
                this.log.debug(id + " authentication scheme selected");
            }
            try {
                authScheme = registry.getAuthScheme(id, response.getParams());
                break;
            } catch (final IllegalStateException e) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication scheme " + id + " not supported");
                    // Try again
                }
            }
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    if (authScheme == null) {
        // If none selected, something is wrong
        throw new AuthenticationException("Unable to respond to any of these challenges: " + challenges);
    }
    return authScheme;
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost,
        final HttpResponse response, final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }//  ww w .java2 s .co  m

    final AuthScheme authScheme;
    try {
        authScheme = this.handler.selectScheme(challenges, response, context);
    } catch (final AuthenticationException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn(ex.getMessage(), ex);
        }
        return options;
    }
    final String id = authScheme.getSchemeName();
    final Header challenge = challenges.get(id.toLowerCase(Locale.US));
    authScheme.processChallenge(challenge);

    final AuthScope authScope = new AuthScope(authhost.getHostName(), authhost.getPort(), authScheme.getRealm(),
            authScheme.getSchemeName());

    final Credentials credentials = credsProvider.getCredentials(authScope);
    if (credentials != null) {
        options.add(new AuthOption(authScheme, credentials));
    }
    return options;
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (isCachable(authScheme)) {
        if (authCache == null) {
            authCache = new BasicAuthCache();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }/*from w  w w .  j a va  2  s  .  c om*/
        if (this.log.isDebugEnabled()) {
            this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
        }
        authCache.put(authhost, authScheme);
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public void authFailed(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    final AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null) {
        return;/*from w  w  w.j a  v a  2  s . c o m*/
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Removing from cache '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
    }
    authCache.remove(authhost);
}

From source file:org.apache.http.impl.client.DefaultRedirectHandler.java

public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) {
    Args.notNull(response, "HTTP response");

    final int statusCode = response.getStatusLine().getStatusCode();
    switch (statusCode) {
    case HttpStatus.SC_MOVED_TEMPORARILY:
    case HttpStatus.SC_MOVED_PERMANENTLY:
    case HttpStatus.SC_TEMPORARY_REDIRECT:
        final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        final String method = request.getRequestLine().getMethod();
        return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME);
    case HttpStatus.SC_SEE_OTHER:
        return true;
    default://w  w w . j  ava2  s .  c om
        return false;
    } //end of switch
}