Java Code Examples for org.apache.commons.httpclient.HttpStatus#SC_UNAUTHORIZED

The following examples show how to use org.apache.commons.httpclient.HttpStatus#SC_UNAUTHORIZED . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EwsExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check endpoint url.
 *
 * @throws IOException on error
 */
protected void checkEndPointUrl() throws IOException {
    GetFolderMethod checkMethod = new GetFolderMethod(BaseShape.ID_ONLY,
            DistinguishedFolderId.getInstance(null, DistinguishedFolderId.Name.root), null);
    int status = executeMethod(checkMethod);
    // add NTLM if required
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && DavGatewayHttpClientFacade.acceptsNTLMOnly(checkMethod) && !DavGatewayHttpClientFacade.hasNTLMorNegotiate(httpClient)) {
        LOGGER.debug("Received " + status + " unauthorized at " + checkMethod.getURI() + ", retrying with NTLM");
        DavGatewayHttpClientFacade.addNTLM(httpClient);
        checkMethod = new GetFolderMethod(BaseShape.ID_ONLY,
                DistinguishedFolderId.getInstance(null, DistinguishedFolderId.Name.root), null);
        status = executeMethod(checkMethod);
    }
    if (status == HttpStatus.SC_UNAUTHORIZED) {
        throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
    } else if (status != HttpStatus.SC_OK) {
        throw new IOException("Ews endpoint not available at " + checkMethod.getURI().toString() + " status " + status);
    }
}
 
Example 2
Source File: ExchangeSessionFactory.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Send a request to Exchange server to check current settings.
 *
 * @throws IOException if unable to access Exchange server
 */
public static void checkConfig() throws IOException {
    String url = Settings.getProperty("davmail.url");
    if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) {
        throw new DavMailException("LOG_INVALID_URL", url);
    }
    HttpClient httpClient = DavGatewayHttpClientFacade.getInstance(url);
    GetMethod testMethod = new GetMethod(url);
    try {
        // get webMail root url (will not follow redirects)
        int status = DavGatewayHttpClientFacade.executeTestMethod(httpClient, testMethod);
        ExchangeSession.LOGGER.debug("Test configuration status: " + status);
        if (status != HttpStatus.SC_OK && status != HttpStatus.SC_UNAUTHORIZED
                && !DavGatewayHttpClientFacade.isRedirect(status)) {
            throw new DavMailException("EXCEPTION_CONNECTION_FAILED", url, status);
        }
        // session opened, future failure will mean network down
        configChecked = true;
        // Reset so next time an problem occurs message will be sent once
        errorSent = false;
    } catch (Exception exc) {
        handleNetworkDown(exc);
    } finally {
        testMethod.releaseConnection();
    }

}
 
Example 3
Source File: RestServiceHandler.java    From RestServices with Apache License 2.0 5 votes vote down vote up
private void serveErrorPage(RestServiceRequest rsr, int status, String error, String errorCode) {
	rsr.response.reset();
	rsr.response.setStatus(status);

	//reques authentication
	if (status == HttpStatus.SC_UNAUTHORIZED)
		rsr.response.addHeader(RestServices.HEADER_WWWAUTHENTICATE, "Basic realm=\"Rest Services\"");

	rsr.startDoc();

	switch(rsr.getResponseContentType()) {
	default:
	case HTML:
		rsr.write("<h1>" + error + "</h1>");
		if (errorCode != null)
			rsr.write("<p>Error code: " + errorCode + "</p>");
		rsr.write("<p>Http status code: " + status + "</p>");
		break;
	case JSON:
	case XML:
		JSONObject data = new JSONObject();
		data.put(RestServiceError.MemberNames.errorMessage.toString(), error);
		if (errorCode != null && !errorCode.isEmpty())
			data.put(RestServiceError.MemberNames.errorCode.toString(), errorCode);
		rsr.datawriter.value(data);
		break;
	}

	rsr.endDoc();
}
 
Example 4
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * Execute a method in a new HttpClient instance.
 * If the auth failed, authenticate then retry the method.
 *
 * @param method methot to exec
 * @param <M> Method type
 * @return the status code
 * @throws IOException on any failure
 */
private <M extends HttpMethod> int exec(M method) throws IOException {
  final HttpClient client = new HttpClient();
  if (proxyHost != null) {
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
            new HttpHost(proxyHost, proxyPort));
  }

  int statusCode = execWithDebugOutput(method, client);

  if ((statusCode == HttpStatus.SC_UNAUTHORIZED
          || statusCode == HttpStatus.SC_BAD_REQUEST)
          && method instanceof AuthPostMethod
          && !useKeystoneAuthentication) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Operation failed with status " + method.getStatusCode() +
               " attempting keystone auth");
    }
    //if rackspace key authentication failed - try custom Keystone authentication
    useKeystoneAuthentication = true;
    final AuthPostMethod authentication = (AuthPostMethod) method;
    //replace rackspace auth with keystone one
    authentication.setRequestEntity(getAuthenticationRequst(keystoneAuthRequest));
    statusCode = execWithDebugOutput(method, client);
  }

  if (statusCode == HttpStatus.SC_UNAUTHORIZED ) {
    //unauthed -or the auth uri rejected it.

    if (method instanceof AuthPostMethod) {
        //unauth response from the AUTH URI itself.
        throw new SwiftAuthenticationFailedException(authRequest.toString(),
                                                     "auth",
                                                     authUri,
                                                     method);
    }
    //any other URL: try again
    if (LOG.isDebugEnabled()) {
      LOG.debug("Reauthenticating");
    }
    //re-auth, this may recurse into the same dir
    authenticate();
    if (LOG.isDebugEnabled()) {
      LOG.debug("Retrying original request");
    }
    statusCode = execWithDebugOutput(method, client);
  }
  return statusCode;
}
 
Example 5
Source File: AuthenticatedHttp.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Execute the given method, authenticated as the given user using ticket-based authentication.
 * @param method method to execute
 * @param userName name of user to authenticate
 * @return status-code resulting from the request
 */
private <T extends Object> T executeWithTicketAuthentication(HttpMethod method, String userName, String password, HttpRequestCallback<T> callback)
{
    String ticket = authDetailProvider.getTicketForUser(userName);
    if(ticket == null)
    {
       ticket = fetchLoginTicket(userName, password);
       authDetailProvider.updateTicketForUser(userName, ticket);
    }
    
    
    
    try
    {
        HttpState state = applyTicketToMethod(method, ticket);
        
       // Try executing the method
        int result = httpProvider.getHttpClient().executeMethod(null, method, state);
        
        if(result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN)
        {
            method.releaseConnection();
            if(!method.validate())
            {
                throw new RuntimeException("Ticket re-authentication failed for user " + userName + " (HTTPMethod not reusable)");
            }
            // Fetch new ticket, store and apply to HttpMethod
            ticket = fetchLoginTicket(userName, userName);
            authDetailProvider.updateTicketForUser(userName, ticket);
            
            state = applyTicketToMethod(method, ticket);
            
            // Run method agian with new ticket
            result = httpProvider.getHttpClient().executeMethod(null, method, state);
        }
       
        if(callback != null)
        {
            return callback.onCallSuccess(method);
        }
        
        return null;
    }
    catch(Throwable t)
    {
        boolean handled = false;
        // Delegate to callback to handle error. If not available, throw exception
        if(callback != null)
        {
            handled = callback.onError(method, t);
        }
        
        if(!handled)
        {
            throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() +")", t);
        }
        return null;
        
    }
    finally
    {
        method.releaseConnection();
    }
    
}
 
Example 6
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Execute a method in a new HttpClient instance.
 * If the auth failed, authenticate then retry the method.
 *
 * @param method methot to exec
 * @param <M> Method type
 * @return the status code
 * @throws IOException on any failure
 */
private <M extends HttpMethod> int exec(M method) throws IOException {
  final HttpClient client = new HttpClient();
  if (proxyHost != null) {
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
            new HttpHost(proxyHost, proxyPort));
  }

  int statusCode = execWithDebugOutput(method, client);

  if ((statusCode == HttpStatus.SC_UNAUTHORIZED
          || statusCode == HttpStatus.SC_BAD_REQUEST)
          && method instanceof AuthPostMethod
          && !useKeystoneAuthentication) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Operation failed with status " + method.getStatusCode() +
               " attempting keystone auth");
    }
    //if rackspace key authentication failed - try custom Keystone authentication
    useKeystoneAuthentication = true;
    final AuthPostMethod authentication = (AuthPostMethod) method;
    //replace rackspace auth with keystone one
    authentication.setRequestEntity(getAuthenticationRequst(keystoneAuthRequest));
    statusCode = execWithDebugOutput(method, client);
  }

  if (statusCode == HttpStatus.SC_UNAUTHORIZED ) {
    //unauthed -or the auth uri rejected it.

    if (method instanceof AuthPostMethod) {
        //unauth response from the AUTH URI itself.
        throw new SwiftAuthenticationFailedException(authRequest.toString(),
                                                     "auth",
                                                     authUri,
                                                     method);
    }
    //any other URL: try again
    if (LOG.isDebugEnabled()) {
      LOG.debug("Reauthenticating");
    }
    //re-auth, this may recurse into the same dir
    authenticate();
    if (LOG.isDebugEnabled()) {
      LOG.debug("Retrying original request");
    }
    statusCode = execWithDebugOutput(method, client);
  }
  return statusCode;
}
 
Example 7
Source File: SwiftRestClient.java    From sahara-extra with Apache License 2.0 4 votes vote down vote up
/**
 * Execute a method in a new HttpClient instance.
 * If the auth failed, authenticate then retry the method.
 *
 * @param method methot to exec
 * @param <M> Method type
 * @return the status code
 * @throws IOException on any failure
 */
private <M extends HttpMethod> int exec(M method) throws IOException {
  final HttpClient client = new HttpClient();
  if (proxyHost != null) {
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
            new HttpHost(proxyHost, proxyPort));
  }

  int statusCode = execWithDebugOutput(method, client);

  if ((statusCode == HttpStatus.SC_UNAUTHORIZED
          || statusCode == HttpStatus.SC_BAD_REQUEST)
          && method instanceof AuthPostMethod
          && !useKeystoneAuthentication) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Operation failed with status " + method.getStatusCode() +
               " attempting keystone auth");
    }
    //if rackspace key authentication failed - try custom Keystone authentication
    useKeystoneAuthentication = true;
    final AuthPostMethod authentication = (AuthPostMethod) method;
    //replace rackspace auth with keystone one
    authentication.setRequestEntity(getAuthenticationRequst(keystoneAuthRequest));
    statusCode = execWithDebugOutput(method, client);
  }

  if (statusCode == HttpStatus.SC_UNAUTHORIZED ) {
    //unauthed -or the auth uri rejected it.

    if (method instanceof AuthPostMethod) {
        //unauth response from the AUTH URI itself.
        throw new SwiftAuthenticationFailedException(authRequest.toString(),
                                                     "auth",
                                                     authUri,
                                                     method);
    }
    //any other URL: try again
    if (LOG.isDebugEnabled()) {
      LOG.debug("Reauthenticating");
    }
    //re-auth, this may recurse into the same dir
    setAuthToken(method, authenticate());
    if (LOG.isDebugEnabled()) {
      LOG.debug("Retrying original request");
    }
    statusCode = execWithDebugOutput(method, client);
  }
  return statusCode;
}