Example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED

List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Prototype

int HTTP_UNAUTHORIZED

To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Click Source Link

Document

HTTP Status-Code 401: Unauthorized.

Usage

From source file:org.apache.hive.service.server.TestHS2HttpServerPam.java

@Test
public void testIncorrectPassword() throws Exception {
    CloseableHttpClient httpclient = null;
    try {/*w  w w  .j  a  va 2s  .  c o m*/
        String username = "user1";
        String password = "aaaa";
        httpclient = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet("http://" + host + ":" + webUIPort);
        String authB64Code = B64Code.encode(username + ":" + password, StringUtil.__ISO_8859_1);
        httpGet.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        Assert.assertTrue(response.toString().contains(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));

    } finally {
        if (httpclient != null) {
            httpclient.close();
        }
    }
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

@Override
public synchronized boolean checkConnection() {
    int code = this.digitalSTROMClient.checkConnection(sessionToken);
    switch (code) {
    case HttpURLConnection.HTTP_OK:
        if (!lostConnectionState) {
            lostConnectionState = true;/*from  w w  w . j  a  va  2  s.c o  m*/
            onConnectionResumed();
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        lostConnectionState = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        if (this.genAppToken) {
            if (StringUtils.isNotBlank(config.getAppToken())) {
                sessionToken = this.digitalSTROMClient.loginApplication(config.getAppToken());
            } else {
                this.onNotAuthenticated();
            }
        } else {
            sessionToken = this.digitalSTROMClient.login(this.config.getUserName(), this.config.getPassword());
        }
        if (sessionToken != null) {
            if (!lostConnectionState) {
                onConnectionResumed();
                lostConnectionState = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            lostConnectionState = false;
        }
        break;
    case -2:
        onConnectionLost(ConnectionListener.INVALID_URL);
        lostConnectionState = false;
        break;
    case -3:
    case -4:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        lostConnectionState = false;
        break;
    case -1:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case -5:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        lostConnectionState = false;
        break;
    }
    return lostConnectionState;
}

From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java

private void checkCustomerKey(OAuthToken token, String customerKey) throws OAuthException {
    if (customerKey != null && !customerKey.equals(token.getConsumer().getKey())) {
        throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "Invalid customer key");
    }//from   w ww. j ava2s .  c om
}

From source file:com.bigstep.datalake.KerberosIdentityAuthenticator.java

private boolean isNegotiate() throws IOException {
    boolean negotiate = false;
    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        String authHeader = conn.getHeaderField(WWW_AUTHENTICATE);
        negotiate = authHeader != null && authHeader.trim().startsWith(NEGOTIATE);
    }/*from ww w.j ava  2 s  .c  om*/
    return negotiate;
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void addCoOwner(String carName, String coOwnerUsername, LoginBean login) {

    String servlet = "AddCoOwner";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("carName", carName));
    params.add(new BasicNameValuePair("coOwnerUsername", coOwnerUsername));
    params.add(new BasicNameValuePair("username", login.getUsername()));
    params.add(new BasicNameValuePair("password", login.getPassword()));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.COOWNER_ADDED);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Error.NOT_FOUND);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/*  ww w. j a va 2 s  . co m*/

}

From source file:org.debux.webmotion.shiro.Shiro.java

/**
 * Check if the current user is permitted.
 * //  w  w w . j  a  va 2  s .  com
 * @param permission
 * @return 
 */
public Render isPermitted(HttpContext context, Call call) {
    FilterRule rule = (FilterRule) call.getCurrentRule();
    Map<String, String[]> defaultParameters = rule.getDefaultParameters();

    String[] permissions = defaultParameters.get("permission");

    Subject currentUser = getSubject(context);
    if (currentUser.isAuthenticated()) {

        boolean[] permitted = currentUser.isPermitted(permissions);
        if (BooleanUtils.and(permitted)) {
            doProcess();
            return null;
        } else {
            return renderError(HttpURLConnection.HTTP_FORBIDDEN);
        }

    } else {
        return renderError(HttpURLConnection.HTTP_UNAUTHORIZED);
    }
}

From source file:org.omegat.gui.glossary.taas.TaaSClient.java

/**
 * Request specified URL and check response code.
 *///from   w w  w  . jav  a 2s.com
HttpURLConnection requestPost(String url, String body) throws IOException, Unauthorized, FormatError {
    Log.logInfoRB("TAAS_REQUEST", url);
    HttpURLConnection conn;
    conn = (HttpURLConnection) new URL(url).openConnection();

    conn.setRequestProperty("Authorization", BASIC_AUTH);
    if (taasUserKey != null) {
        conn.setRequestProperty("TaaS-User-Key", taasUserKey);
    }
    conn.setRequestProperty("Accept", "text/xml");
    conn.setRequestMethod("POST");

    conn.setRequestProperty("Content-Type", "text/plain");// ; charset=UTF-8
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    try {
        out.write(body.getBytes(StandardCharsets.UTF_8));
    } finally {
        out.close();
    }

    if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        throw new Unauthorized();
    }

    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new FormatError(conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    return conn;
}

From source file:com.cloudant.http.internal.interceptors.CookieInterceptor.java

@Override
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {

    // Check if this interceptor is valid before attempting any kind of renewal
    if (shouldAttemptCookieRequest.get()) {

        HttpURLConnection connection = context.connection.getConnection();

        // If we got a 401 or 403 we might need to renew the cookie
        try {//from  www .  j  av  a2s .  co m
            boolean renewCookie = false;
            int statusCode = connection.getResponseCode();

            if (statusCode == HttpURLConnection.HTTP_FORBIDDEN
                    || statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                InputStream errorStream = connection.getErrorStream();
                String errorString = null;
                if (errorStream != null) {
                    try {
                        // Get the string value of the error stream
                        errorString = IOUtils.toString(errorStream, "UTF-8");
                    } finally {
                        IOUtils.closeQuietly(errorStream);
                    }
                }
                logger.log(Level.FINE, String.format(Locale.ENGLISH, "Intercepted " + "response %d %s",
                        statusCode, errorString));
                switch (statusCode) {
                case HttpURLConnection.HTTP_FORBIDDEN: //403
                    // Check if it was an expiry case
                    // Check using a regex to avoid dependency on a JSON library.
                    // Note (?siu) flags used for . to also match line breaks and for
                    // unicode
                    // case insensitivity.
                    if (errorString != null && errorString
                            .matches("(?siu)" + ".*\\\"error\\\"\\s*:\\s*\\\"credentials_expired\\\".*")) {
                        // Was expired - set boolean to renew cookie
                        renewCookie = true;
                    } else {
                        // Wasn't a credentials expired, throw exception
                        HttpConnectionInterceptorException toThrow = new HttpConnectionInterceptorException(
                                errorString);
                        // Set the flag for deserialization
                        toThrow.deserialize = errorString != null;
                        throw toThrow;
                    }
                    break;
                case HttpURLConnection.HTTP_UNAUTHORIZED: //401
                    // We need to get a new cookie
                    renewCookie = true;
                    break;
                default:
                    break;
                }

                if (renewCookie) {
                    logger.finest("Cookie was invalid attempt to get new cookie.");
                    boolean success = requestCookie(context);
                    if (success) {
                        // New cookie obtained, replay the request
                        context.replayRequest = true;
                    } else {
                        // Didn't successfully renew, maybe creds are invalid
                        context.replayRequest = false; // Don't replay
                        shouldAttemptCookieRequest.set(false); // Set the flag to stop trying
                    }
                }
            } else {
                // Store any cookies provided on the response
                storeCookiesFromResponse(connection);
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error reading response code or body from request", e);
        }
    }
    return context;

}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.BasicNetwork.java

@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
        HttpResponse httpResponse = null;
        byte[] responseContents = null;
        Map<String, String> responseHeaders = new HashMap<String, String>();
        try {/*  w  w w  . j  a  v  a2  s  .c  o m*/
            // Gather headers.
            Map<String, String> headers = new HashMap<String, String>();
            addCacheHeaders(headers, request.getCacheEntry());
            httpResponse = mHttpStack.performRequest(request, headers);
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            responseHeaders = convertHeaders(httpResponse.getAllHeaders());
            // Handle cache validation.
            if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) {
                return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED,
                        request.getCacheEntry() == null ? null : request.getCacheEntry().data, responseHeaders,
                        true);
            }

            // Some responses such as 204s do not have content.  We must check.
            if (httpResponse.getEntity() != null) {
                responseContents = entityToBytes(httpResponse.getEntity());
            } else {
                // Add 0 byte response as a way of honestly representing a
                // no-content request.
                responseContents = new byte[0];
            }

            // if the request is slow, log it.
            long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
            logSlowRequests(requestLifetime, request, responseContents, statusLine);

            if (statusCode < 200 || statusCode > 299) {
                throw new IOException();
            }
            return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
        } catch (SocketTimeoutException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "SocketTimeoutException");
            }
            attemptRetryOnException("socket", request, new TimeoutError());
        } catch (ConnectTimeoutException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "ConnectTimeoutException");
            }
            attemptRetryOnException("connection", request, new TimeoutError());
        } catch (MalformedURLException e) {
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "MalformedURLException");
            }
            throw new RuntimeException("Bad URL " + request.getUrl(), e);
        } catch (IOException e) {
            int statusCode = 0;
            NetworkResponse networkResponse = null;
            if (httpResponse != null) {
                statusCode = httpResponse.getStatusLine().getStatusCode();
            } else {
                Log.e("Connection Error", " " + e.getMessage());
                throw new NoConnectionError(e);
            }
            VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
            if (ConfigDataProvider.DEBUG) {
                Log.e("Volley", "IOException statusCode:" + statusCode + " url:" + request.getUrl());
            }
            if (responseContents != null) {
                networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false);
                if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
                } else {
                    // TODO: Only throw ServerError for 5xx status codes.
                    throw new ServerError(networkResponse);
                }
            } else {
                throw new NetworkError(networkResponse);
            }
        }
    }
}