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:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

protected static void processStandardHttpResponseCodes(HttpResponse httpResponse)
        throws AuthenticationException, IOException {
    int code = httpResponse.getStatusLine().getStatusCode();
    Log.d(TAG, "Response http code: " + code);
    if (code >= 200 && code <= 299)
        return;/*  ww w.  ja  va2  s. com*/
    if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
        String OTP = getHeaderValue(httpResponse.getFirstHeader("X-GitHub-OTP"));
        if (code == HttpStatus.SC_UNAUTHORIZED && OTP != null && OTP.contains("required")) {
            throw new OTPAuthenticationException(Utils.trimToNull(OTP.replace("required;", "")));
        }
        throw new AuthenticationException(
                "Authentication problem: " + getResponseContentAsString(httpResponse));
    } else if (code == HttpStatus.SC_BAD_REQUEST || code == HttpStatus.SC_NOT_FOUND) {
        throw new InvalidObjectException(
                "HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
    } else {
        throw new IOException("HttpCode=" + code + " message: " + getResponseContentAsString(httpResponse));
    }
}

From source file:info.ajaxplorer.client.http.RestRequest.java

private void authenticate() throws AuthenticationException {
    loginStateChanged = false;//from  ww  w  . j a  v  a  2  s .  c o m
    AjxpAPI API = AjxpAPI.getInstance();
    try {
        if (authStep.equals("RENEW-TOKEN")) {

            JSONObject jObject = this.getJSonContent(API.getGetSecureTokenUri());
            RestStateHolder.getInstance().setSECURE_TOKEN(jObject.getString("SECURE_TOKEN"));
            loginStateChanged = true;

        } else {

            String seed = this.getStringContent(API.getGetLoginSeedUri());
            if (seed != null)
                seed = seed.trim();
            if (seed.indexOf("captcha") > -1) {
                throw new AuthenticationException(AUTH_ERROR_LOCKEDOUT);
            }
            if (!RestStateHolder.getInstance().isServerSet()) {
                throw new AuthenticationException(AUTH_ERROR_NOSERVER);
            }
            String user = RestStateHolder.getInstance().getServer().getUser();
            String password = RestStateHolder.getInstance().getServer().getPassword();
            if (!seed.trim().equals("-1")) {
                password = RestRequest.md5(password) + seed;
                password = RestRequest.md5(password);
            }
            Document doc = this.getDocumentContent(API.makeLoginUri(user, password, seed));
            if (doc.getElementsByTagName("logging_result").getLength() > 0) {
                String result = doc.getElementsByTagName("logging_result").item(0).getAttributes()
                        .getNamedItem("value").getNodeValue();
                if (result.equals("1")) {
                    //Log.d("RestRequest Authentication", "LOGGING SUCCEED! REFRESHING TOKEN");
                    String newToken = doc.getElementsByTagName("logging_result").item(0).getAttributes()
                            .getNamedItem("secure_token").getNodeValue();
                    RestStateHolder.getInstance().setSECURE_TOKEN(newToken);
                    loginStateChanged = true;
                } else {
                    //Log.d("RestRequest Authentication", "Login Failed");
                    throw new AuthenticationException(AUTH_ERROR_LOGIN_FAILED);
                }
            }

        }
    } catch (AuthenticationException e) {
        throw e;
    } catch (Exception e) {
        throw new AuthenticationException(e.getMessage());
    }
}

From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java

@Override
/** {@inheritDoc} */
public List<ISweetContact> getNewerContacts(String token, String date, int start, int count)
        throws IOException, AuthenticationException {
    final HttpResponse resp;
    Log.i(TAG, "getNewerContacts()");

    JSONArray jso_array = new JSONArray();
    JSONArray jso_fields = new JSONArray();
    // TODO: add newer fields (adress and other phones)
    jso_fields.put(SUGARCRM_CONTACT_ID_FIELD).put(SUGARCRM_FIRST_NAME_FIELD).put(SUGARCRM_LAST_NAME_FIELD)
            .put(SUGARCRM_TITLE_FIELD).put(SUGARCRM_ACCOUNT_NAME_FIELD).put(SUGARCRM_ACCOUNT_ID_FIELD)
            .put(SUGARCRM_EMAIL1_FIELD).put(SUGARCRM_PHONE_WORK_FIELD).put(SUGARCRM_PHONE_MOBILE_FIELD)
            .put(SUGARCRM_FAX_WORK_FIELD).put(SUGARCRM_STREET_FIELD).put(SUGARCRM_CITY_FIELD)
            .put(SUGARCRM_STATE_FIELD).put(SUGARCRM_POSTAL_CODE_FIELD).put(SUGARCRM_COUNTRY_FIELD)
            .put(SUGARCRM_DATE_MODIFIED_FIELD);
    String sugar_query = SUGAR_CONTACTS_QUERY;
    if (date != null)
        sugar_query = "(contacts.date_modified >= '" + date + "')";
    jso_array.put(token).put(SUGAR_MODULE_CONTACTS).put(sugar_query).put(SUGAR_CONTACTS_ORDER_BY).put(start)
            .put(jso_fields).put(SUGAR_CONTACT_LINK_NAMES).put(count).put(0);

    final HttpPost post = prepareJSONRequest(jso_array.toString(), GET_METHOD);
    HttpClient httpClient = getConnection();
    Log.i(TAG, "Sending request");
    resp = httpClient.execute(post);/*from  w  w  w.  j a v  a2 s .  com*/
    Log.i(TAG, "Got response");
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Successful authentication");
        }
        Log.i(TAG, "Buffering request");
        List<ISweetContact> contacts = new ArrayList<ISweetContact>();
        String message = getResponseString(resp);
        JSONArray result;
        JSONObject json = null;
        try {
            Log.i(TAG, "Parsing response");
            json = (JSONObject) new JSONTokener(message).nextValue();
            result = json.getJSONArray("entry_list");
            Log.i(TAG, "Creating contact objects");
            for (int i = 0; i < result.length(); i++) {
                try {
                    // ID, first name and last name are compulsory, the rest
                    // can be skipped
                    JSONObject entrada = result.getJSONObject(i).getJSONObject("name_value_list");
                    contacts.add(new SweetContact(
                            getJSONString(entrada.getJSONObject(SUGARCRM_CONTACT_ID_FIELD).getString("value")),
                            getJSONString(entrada.getJSONObject(SUGARCRM_FIRST_NAME_FIELD).getString("value")),
                            getJSONString(entrada.getJSONObject(SUGARCRM_LAST_NAME_FIELD).getString("value")),
                            getSugarValue(entrada, SUGARCRM_TITLE_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_ACCOUNT_NAME_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_ACCOUNT_ID_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_EMAIL1_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_PHONE_WORK_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_PHONE_MOBILE_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_FAX_WORK_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_STREET_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_CITY_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_STATE_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_POSTAL_CODE_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_COUNTRY_FIELD, ""),
                            getSugarValue(entrada, SUGARCRM_DATE_MODIFIED_FIELD, "")));
                } catch (Exception ex) {
                    ex.printStackTrace();
                    Log.e(TAG, "Unknown error parsing, skipping entry");
                }
            }

            return contacts;
        } catch (Exception e) {
            if (json != null) {
                Log.i(TAG, "Error parsing json in getNewerContacts. Auth invalid");
                try {

                    throw new AuthenticationException(json.getString("description"));
                } catch (JSONException ex) {
                    throw new AuthenticationException("Invalid session");
                }
            }
        } finally {
            httpClient.getConnectionManager().closeIdleConnections(100, TimeUnit.MILLISECONDS);
        }
    } else {
        Log.v(TAG, "Error authenticating" + resp.getStatusLine());
        throw new AuthenticationException("Invalid session");
    }
    return null;
}

From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.java

private void processChallenges(final Map<String, Header> challenges, final AuthState authState,
        final AuthenticationHandler authHandler, final HttpResponse response, final HttpContext context)
        throws MalformedChallengeException, AuthenticationException {

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        // Authentication not attempted before
        authScheme = authHandler.selectScheme(challenges, response, context);
        authState.setAuthScheme(authScheme);
    }//from   w  w w  . j  a v a  2s.  co m
    String id = authScheme.getSchemeName();

    Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
    if (challenge == null) {
        throw new AuthenticationException(id + " authorization challenge expected, but not found");
    }
    authScheme.processChallenge(challenge);
    LOGGER.debug("Authorization challenge processed");
}

From source file:com.github.vseguip.sweet.rest.SugarRestAPI.java

@Override
public List<String> sendNewContacts(String token, List<ISweetContact> contacts, boolean create)
        throws IOException, AuthenticationException {
    final HttpResponse resp;
    ArrayList<String> listaIds = new ArrayList<String>();
    Log.i(TAG, "sendNewContacts()");

    JSONArray jsonData = new JSONArray();
    JSONArray jsonContactList = new JSONArray();
    // TODO: add newer fields (adress and other phones)
    for (ISweetContact c : contacts) {
        JSONArray jsonContactArray = new JSONArray();
        try {/* w w w.j a v  a  2 s .co m*/
            if (!create)
                setJsonFieldEntry(jsonContactArray, SUGARCRM_CONTACT_ID_FIELD, c.getId());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_FIRST_NAME_FIELD, c.getFirstName());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_LAST_NAME_FIELD, c.getLastName());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_TITLE_FIELD, c.getTitle());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_ACCOUNT_NAME_FIELD, c.getAccountName());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_ACCOUNT_ID_FIELD, c.getAccountId());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_EMAIL1_FIELD, c.getEmail1());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_PHONE_WORK_FIELD, c.getWorkPhone());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_PHONE_MOBILE_FIELD, c.getMobilePhone());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_FAX_WORK_FIELD, c.getWorkFax());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_STREET_FIELD, c.getStreet());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_CITY_FIELD, c.getCity());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_STATE_FIELD, c.getRegion());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_POSTAL_CODE_FIELD, c.getPostalCode());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_COUNTRY_FIELD, c.getCountry());
            setJsonFieldEntry(jsonContactArray, SUGARCRM_DATE_MODIFIED_FIELD, c.getDateModified());
            jsonContactList.put(jsonContactArray);
        } catch (JSONException e) {
            Log.e(TAG, "Error sending contact to the server");
            e.printStackTrace();
        }

    }
    jsonData.put(token).put(SUGAR_MODULE_CONTACTS).put(jsonContactList);

    final HttpPost post = prepareJSONRequest(jsonData.toString(), SET_METHOD);
    HttpClient httpClient = getConnection();
    Log.i(TAG, "Sending request");

    resp = httpClient.execute(post);
    Log.i(TAG, "Got response");
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        Log.i(TAG, "Buffering request");
        String message = getResponseString(resp);
        Log.i(TAG, "Set entries result: " + message);
        JSONObject response = null;
        try {
            response = (JSONObject) new JSONTokener(message).nextValue();
            JSONArray ids = response.getJSONArray("ids");
            for (int i = 0; i < ids.length(); i++) {
                listaIds.add(ids.getString(i));
            }
        } catch (Exception e) {
            if (response != null) {
                Log.i(TAG, "Error parsing json in sendNewContacts. Auth invalid");
                try {
                    throw new AuthenticationException(response.getString("description"));
                } catch (JSONException ex) {
                    throw new AuthenticationException("Invalid session");
                }
            }
        }
    }
    return listaIds;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

private static String retryAuthentification(int retryCount, AccountManager accountManager, String authtoken,
        String accountName, HttpResponse response)
        throws AuthenticationException, OperationCanceledException, NetworkErrorException, ServerException {
    accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authtoken);
    String newToken = null;/*from w  w w. j  a v a2s.  c o  m*/
    if (retryCount == 0) {
        newToken = blockingGetAuthToken(accountManager, new Account(accountName, Constants.ACCOUNT_TYPE), null);
    }
    if (newToken == null) {
        throw new AuthenticationException(response.getStatusLine().toString());
    }
    return newToken;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

public static boolean savePwdSalt(Context context, String accountName, String authtoken, String newSalt,
        String oldSalt, boolean clearData, String pwdCheck)
        throws AuthenticationException, ServerException, NetworkErrorException {
    final HttpPost post = new HttpPost(PWDSALT_URI);
    List<BasicNameValuePair> values = new ArrayList<BasicNameValuePair>();
    values.add(new BasicNameValuePair("newSalt", newSalt == null ? "" : newSalt));
    values.add(new BasicNameValuePair("oldSalt", oldSalt == null ? "" : oldSalt));
    values.add(new BasicNameValuePair("clearData", String.valueOf(clearData)));
    values.add(new BasicNameValuePair("pwdCheck", pwdCheck == null ? "" : pwdCheck));

    HttpResponse resp = null;//from  w w w.j  a  v a2 s.  com
    final String respStr;
    HttpEntity entity = null;
    try {
        HttpEntity postEntity = new UrlEncodedFormEntity(values, SyncDataHelper.DEFAULT_CHARSET_NAME);
        post.setHeader(postEntity.getContentEncoding());
        post.setEntity(postEntity);

        resp = getHttpClient(context).execute(post, createHttpContext(accountName, authtoken));
        entity = resp.getEntity();
        respStr = EntityUtils.toString(entity);
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        throw new NetworkErrorException(ex);
    } finally {
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException ex) {
                LogHelper.logD(TAG, "Close Entity failed with: " + ex.getMessage(), ex);
            }
        }
    }

    boolean saltSaved = true;
    StatusLine statusLine = resp.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException(statusLine.toString());
        } else if (statusCode == HttpStatus.SC_BAD_REQUEST) {
            saltSaved = false;
        } else {
            throw new ServerException("Server error in query savePwdSalt: " + statusLine);
        }
    } else {
        if (respStr != null && !respStr.startsWith("OK")) {
            Log.w(TAG, "SaltSaved failed with: " + respStr);
            saltSaved = false;
        }
    }
    return saltSaved;
}

From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java

private void processChallenges(final Map<String, Header> challenges, final AuthState authState,
        final AuthenticationHandler authHandler, final HttpResponse response, final HttpContext context)
        throws MalformedChallengeException, AuthenticationException {

    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        // Authentication not attempted before
        authScheme = authHandler.selectScheme(challenges, response, context);
        authState.setAuthScheme(authScheme);
    }//from  w ww. j a  va 2s.  c o m
    String id = authScheme.getSchemeName();

    Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
    if (challenge == null) {
        throw new AuthenticationException(id + " authorization challenge expected, but not found");
    }
    authScheme.processChallenge(challenge);
    this.log.debug("Authorization challenge processed");
}

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:/*  ww  w. j  av  a  2  s. c  o m*/
        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  ww  w  .j a v a 2s.com

    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;
}