Example usage for org.apache.http.auth AuthenticationException AuthenticationException

List of usage examples for org.apache.http.auth AuthenticationException AuthenticationException

Introduction

In this page you can find the example usage for org.apache.http.auth AuthenticationException AuthenticationException.

Prototype

public AuthenticationException(final String message) 

Source Link

Document

Creates a new AuthenticationException with the specified message.

Usage

From source file:org.restcomm.connect.java.sdk.ExceptionHandler.java

public ExceptionHandler(final CloseableHttpResponse response) {
    this.response = response;
    int StatusCode;
    StatusCode = response.getStatusLine().getStatusCode();

    try {/*from   w  ww .j  a  v  a2  s.  c  o  m*/
        if (StatusCode == 401)
            throw new AuthenticationException("The Credentials Provided Are Incorrect");
        if (StatusCode == 404)
            throw new ResourceNotFoundException("The Requested Resource Is Not Available");
    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (ResourceNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:org.apache.droids.protocol.http.NoAuthHandler.java

@Override
public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context)
        throws AuthenticationException {
    throw new AuthenticationException("Unable to respond to any of these challenges: " + challenges);
}

From source file:org.muckebox.android.net.ApiHelper.java

public static String getResponseAsString(HttpResponse response) throws IOException, AuthenticationException {
    StatusLine statusLine = response.getStatusLine();

    Log.d(LOG_TAG, "HTTP Response " + statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());

    switch (statusLine.getStatusCode()) {
    case 401://from w  ww .j  a  va2s  .  c o m
        throw new AuthenticationException(statusLine.getReasonPhrase());
    case 200:
        break;
    default:
        throw new IOException();
    }

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    StringBuilder str = new StringBuilder();
    char[] charBuf = new char[1024];

    int bytes_read;

    while ((bytes_read = reader.read(charBuf)) != -1)
        str.append(charBuf, 0, bytes_read);

    return str.toString();
}

From source file:microsoft.exchange.webservices.data.EwsJCIFSNTLMScheme.java

public EwsJCIFSNTLMScheme() throws AuthenticationException {
    // Check if JCIFS is present. If not present, do not proceed.
    try {//from   w  ww  .ja v a2 s.  c  o  m
        Class.forName("jcifs.ntlmssp.NtlmMessage", false, this.getClass().getClassLoader());
    } catch (ClassNotFoundException e) {
        throw new AuthenticationException("Unable to proceed as JCIFS library is not found.");
    }
}

From source file:org.ohmage.sync.StreamSyncAdapterTest.java

public void testOnPerformSyncForStreams_cantGetAccessToken_setsAuthExceptionInSyncResult() throws Exception {
    Streams fakeStreams = new Streams();
    fakeStreams.add(fakeStream);//  ww  w  . j  a  v  a 2 s. c  o m
    when(fakeWriter.moveToNextBatch()).thenReturn(true, false);
    whenAccountStillExists();
    when(fakeOhmageService.uploadStreamData(fakeStreamId, fakeStreamVersion, fakeWriter))
            .thenThrow(new AuthenticationException(""));

    mSyncAdapter.performSyncForStreams(fakeAccount, fakeStreams, fakeWriter, fakeSyncResult);

    assertEquals(1, fakeSyncResult.stats.numAuthExceptions);
}

From source file:com.androidquery.test.NTLMScheme.java

public Header authenticate(final Credentials credentials, final HttpRequest request)
        throws AuthenticationException {
    NTCredentials ntcredentials = null;// w  ww .  java2s .  c o  m
    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);
}

From source file:com.cloudmine.api.AccessListController.java

/**
 * WARNING: If the user associated with this ACL is not logged in, you will NOT receive the ACL create
 * request as a return value; instead, you will return {@link com.cloudmine.api.rest.CloudMineRequest#FAKE_REQUEST}
 * as the system needs to log the user in first. If you want to guarantee you will receive the actual request,
 * you should make use of the {@link #save(android.content.Context, CMSessionToken, com.android.volley.Response.Listener, com.android.volley.Response.ErrorListener)} method
 * @param context the activity context that will be used to cancel this request
 * @param successListener/*from   w  ww . j  av  a 2s  .co m*/
 * @param errorListener
 * @return the submitted request IFF the associated user is logged in; {@link com.cloudmine.api.rest.CloudMineRequest#FAKE_REQUEST} otherwise
 */
public CloudMineRequest save(final Context context, final Response.Listener<CreationResponse> successListener,
        final Response.ErrorListener errorListener) {
    JavaCMUser user = getUser();
    if (user == null) {
        errorListener.onErrorResponse(
                new VolleyError(new IllegalStateException("Cannot save an ACL without an owner")));
        return CloudMineRequest.FAKE_REQUEST;
    }
    CMSessionToken sessionToken = user.getSessionToken();
    if (sessionToken == null || sessionToken.getSessionToken().equals(CMSessionToken.INVALID_TOKEN)) {
        if (user instanceof BaseCMUser) {
            ((BaseCMUser) user).login(context, null, null, new Response.Listener<LoginResponse>() {
                @Override
                public void onResponse(LoginResponse loginResponse) {
                    save(context, loginResponse.getSessionToken(), successListener, errorListener);
                }
            }, errorListener);
        } else {
            user.login(new LoginResponseCallback() {
                public void onCompletion(LoginResponse loginResponse) {
                    if (loginResponse.wasSuccess()) {
                        save(context, loginResponse.getSessionToken(), successListener, errorListener);
                    } else {
                        errorListener.onErrorResponse(new VolleyError(
                                new AuthenticationException("Unable to log user in to save ACL")));
                    }
                }

                public void onFailure(Throwable throwable, String msg) {
                    errorListener.onErrorResponse(new VolleyError(throwable));
                }
            });
        }
    } else {
        return save(context, sessionToken, successListener, errorListener);
    }
    return CloudMineRequest.FAKE_REQUEST;
}

From source file:eu.masconsult.bgbanking.accounts.AccountAuthenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle options) throws NetworkErrorException {
    Log.v(TAG, "getAuthToken(account: " + account + ", authTokenType: " + authTokenType + ")");

    Bank bank = Bank.fromAccountType(context, account.type);
    if (bank == null) {
        throw new IllegalArgumentException("unsupported account type " + account.type);
    }/*from  w ww .  j av a 2 s. c  o m*/
    if (!Constants.getAuthorityType(context).equals(authTokenType)) {
        throw new IllegalArgumentException("unsupported authTOkenType " + authTokenType);
    }

    final Intent intent = new Intent(context, LoginActivity.class);
    intent.putExtra(KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    intent.putExtra(KEY_ACCOUNT_NAME, account.name);
    intent.putExtra(KEY_ACCOUNT_TYPE, account.type);

    String password = accountManager.getPassword(account);
    try {
        String authToken = bank.getClient().authenticate(account.name, password);
        Log.v(TAG, "obtained auth token " + authToken);

        if (authToken == null) {
            throw new AuthenticationException("no authToken");
        }

        // store the new auth token and return it
        accountManager.setAuthToken(account, authTokenType, authToken);
        intent.putExtra(KEY_AUTHTOKEN, authToken);
        return intent.getExtras();
    } catch (ParseException e) {
        Log.w(TAG, "ParseException", e);
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_ERROR_CODE, 1);
        bundle.putString(KEY_ERROR_MESSAGE, e.getMessage());
        return bundle;
    } catch (IOException e) {
        Log.w(TAG, "IOException", e);
        throw new NetworkErrorException(e);
    } catch (CaptchaException e) {
        Log.w(TAG, "CaptchaException", e);
        // We need human to verify captcha
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        intent.putExtra(KEY_CAPTCHA_URI, e.getCaptchaUri());
        return bundle;
    } catch (AuthenticationException e) {
        Log.w(TAG, "AuthenticationException", e);
        // we need new credentials
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        return bundle;
    }
}

From source file:org.ohmage.sync.StreamSyncAdapterTest.java

public void testOnPerformSyncForStreams_authErrorUploading_triesAgainAfterInvalidating() throws Exception {
    Streams fakeStreams = new Streams();
    fakeStreams.add(fakeStream);//w w  w  .ja  va  2s.co m
    when(fakeWriter.moveToNextBatch()).thenReturn(true, false);
    whenAccountStillExists();
    when(fakeOhmageService.uploadStreamData(fakeStreamId, fakeStreamVersion, fakeWriter))
            .thenThrow(new AuthenticationException(""))
            .thenReturn(new Response(200, "", new ArrayList<Header>(), null));

    mSyncAdapter.performSyncForStreams(fakeAccount, fakeStreams, fakeWriter, fakeSyncResult);

    verify(fakeOhmageService, times(2)).uploadStreamData(fakeStreamId, fakeStreamVersion, fakeWriter);
}

From source file:eu.masconsult.bgbanking.banks.fibank.ebanking.EFIBankClient.java

private void obtainSession(DefaultHttpClient httpClient, AuthToken authToken)
        throws IOException, AuthenticationException {
    HttpEntity entity;//  w  w w  .j  a va2  s .  c o  m
    try {
        entity = new StringEntity("<?xml version=\"1.0\"?><LOGIN><USER_NAME>" + authToken.username
                + "</USER_NAME><USER_PASS>" + authToken.password
                + "</USER_PASS><USER_LANG>BG</USER_LANG><PATH>Login</PATH></LOGIN>", "utf-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    HttpPost post = new HttpPost(LOGIN_URL);
    post.addHeader("Content-Type", "text/xml");
    post.setHeader("Accept", "*/*");
    post.setEntity(entity);

    HttpResponse resp = httpClient.execute(post);
    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new AuthenticationException("Invalid credentials!");
    }

    String response = EntityUtils.toString(resp.getEntity());

    Log.v(TAG, "response = " + response);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new ParseException(e.getMessage());
    }

    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(response));

    Document doc;
    try {
        doc = db.parse(is);
    } catch (SAXException e) {
        throw new ParseException(e.getMessage());
    }

    NodeList session = doc.getElementsByTagName("SESSION");
    if (session == null || session.getLength() != 1) {
        throw new ParseException("can't find SESSION ");
    }

    NamedNodeMap attributes = session.item(0).getAttributes();
    authToken.sessionId = attributes.getNamedItem("id").getTextContent();
}