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.maven.wagon.providers.http.LightweightHttpWagon.java

public void fillInputData(InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String visitingUrl = buildUrl(resource.getName());
    try {/*from w w w.j a v  a 2  s .com*/
        List<String> visitedUrls = new ArrayList<String>();

        for (int redirectCount = 0; redirectCount < MAX_REDIRECTS; redirectCount++) {
            if (visitedUrls.contains(visitingUrl)) {
                throw new TransferFailedException("Cyclic http redirect detected. Aborting! " + visitingUrl);
            }
            visitedUrls.add(visitingUrl);

            URL url = new URL(visitingUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(this.proxy);

            urlConnection.setRequestProperty("Accept-Encoding", "gzip");
            if (!useCache) {
                urlConnection.setRequestProperty("Pragma", "no-cache");
            }

            addHeaders(urlConnection);

            // TODO: handle all response codes
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN
                    || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new AuthorizationException("Access denied to: " + buildUrl(resource.getName()));
            }
            if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                visitingUrl = urlConnection.getHeaderField("Location");
                continue;
            }

            InputStream is = urlConnection.getInputStream();
            String contentEncoding = urlConnection.getHeaderField("Content-Encoding");
            boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding);
            if (isGZipped) {
                is = new GZIPInputStream(is);
            }
            inputData.setInputStream(is);
            resource.setLastModified(urlConnection.getLastModified());
            resource.setContentLength(urlConnection.getContentLength());
            break;
        }
    } catch (MalformedURLException e) {
        throw new ResourceDoesNotExistException("Invalid repository URL: " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
        throw new ResourceDoesNotExistException("Unable to locate resource in repository", e);
    } catch (IOException e) {
        StringBuilder message = new StringBuilder("Error transferring file: ");
        message.append(e.getMessage());
        message.append(" from " + visitingUrl);
        if (getProxyInfo() != null && getProxyInfo().getHost() != null) {
            message.append(" with proxyInfo ").append(getProxyInfo().toString());
        }
        throw new TransferFailedException(message.toString(), e);
    }
}

From source file:net.praqma.jenkins.rqm.request.RQMHttpClient.java

public int login() throws HttpException, IOException, GeneralSecurityException {
    log.finest("Register trusting ssl");
    registerTrustingSSL();// w  w  w.  j  av a 2 s.  co m

    GetMethod methodPart1 = new GetMethod(url.toString() + contextRoot + "/auth/authrequired");

    int response = executeMethod(methodPart1);

    followRedirects(methodPart1, response);

    GetMethod methodPart2 = new GetMethod(this.url.toString() + contextRoot + "/authenticated/identity");

    response = executeMethod(methodPart2);

    followRedirects(methodPart2, response);

    HttpMethodBase authenticationMethod = null;
    Header authenticateHeader = methodPart2.getResponseHeader("WWW-Authenticate"); //$NON-NLS-1$

    if ((response == HttpURLConnection.HTTP_UNAUTHORIZED) && (authenticateHeader != null)
            && (authenticateHeader.getValue().toLowerCase().indexOf("basic realm") == 0)) {

        super.getState().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(getUsr(), getPassword()));

        String authMethod = this.url.toString() + "/authenticated/identity";
        authenticationMethod = new GetMethod(authMethod);
        response = super.executeMethod(methodPart2);
    } else {
        authenticationMethod = new PostMethod(this.url.toString() + contextRoot + "/j_security_check");
        NameValuePair[] nvps = new NameValuePair[2];
        nvps[0] = new NameValuePair("j_username", getUsr());
        nvps[1] = new NameValuePair("j_password", getPassword());
        ((PostMethod) (authenticationMethod)).addParameters(nvps);
        ((PostMethod) (authenticationMethod)).addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=utf-8");
        response = executeMethod(authenticationMethod);
        Header location = authenticationMethod.getResponseHeader("X-com-ibm-team-repository-web-auth-msg");
        if (location != null && location.getValue().indexOf("authfailed") >= 0) {
            response = HttpURLConnection.HTTP_UNAUTHORIZED;
        }
    }

    if ((response != HttpURLConnection.HTTP_OK) && (response != HttpURLConnection.HTTP_MOVED_TEMP)) {
        if (response != HttpURLConnection.HTTP_UNAUTHORIZED) {
            String body = "";
            try {
                body = authenticationMethod.getResponseBodyAsString();
            } catch (Exception e) {
                log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s",
                        response, body));
            }
            log.severe(String.format("Failed to login, with response code %s %n Response body: %n %s", response,
                    body));
        }
    } else {
        followRedirects(authenticationMethod, response);
        String methodText = String.format(
                "%s%s/service/com.ibm.team.repository.service.internal.webuiInitializer.IWebUIInitializerRestService/initializationData",
                url.toString(), contextRoot);
        GetMethod get3 = new GetMethod(methodText);
        response = executeMethod(get3);
        followRedirects(get3, response);
    }

    log.finest("Response was: " + response);
    return response;
}

From source file:rapture.server.web.servlet.JavaScriptPageServlet.java

private void process(Map<String, String> parameterMap, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    logger.debug("req is " + req);
    logger.debug("resp is " + resp);
    logger.debug("parameterMap is " + parameterMap);

    // check script exists
    RaptureURI scriptURI = getScriptURI(req);
    logger.info(String.format("Running script for uri %s", scriptURI.toString()));
    RaptureScript script = Kernel.getScript().getScript(ContextFactory.ADMIN, scriptURI.toString());
    if (script == null || StringUtils.isBlank(script.getScript())) {
        logger.warn("Could not locate script for uri - " + scriptURI.toString());
        resp.setStatus(HttpStatus.SC_NOT_FOUND);
        return;//from ww  w .ja v a 2  s.  c om
    }
    // run JavaScript
    DispatchReturn response;
    try {
        CallingContext context = BaseDispatcher.validateSession(req);
        if (context != null) {
            logger.trace("Got session context " + context.debug());
            String result = Kernel.getScript().runScript(context, scriptURI.getFullPath(), parameterMap);
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().append(result);
            resp.setContentType("text/plain");
        } else {
            String err = "Cannot execute script " + script + " : cannot get session context for authorization";
            logger.error(err);
            resp.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, err);
        }
    } catch (RaptNotLoggedInException re) {
        logger.error("Cannot execute script " + script + " : " + re.getMessage());
        resp.sendError(re.getStatus(), re.getMessage());
    } catch (Exception e) {
        response = handleUnexpectedException(e);
        sendResponseAppropriately(response.getContext(), req, resp, response.getResponse());
    }
}

From source file:co.cask.cdap.security.authentication.client.basic.BasicAuthenticationClientTestBase.java

@Test
public void testNotAuthorizedGetAccessToken() throws IOException {
    Properties testProperties = new Properties();
    testProperties.setProperty(USERNAME_PROP_NAME, "test");
    testProperties.setProperty(PASSWORD_PROP_NAME, "test");
    testProperties.setProperty(VERIFY_SSL_CERT_PROP_NAME, VERIFY_SSL_CERT_PROP_VALUE);

    AuthenticationClient authenticationClient = new BasicAuthenticationClient();
    authenticationClient.setConnectionInfo(authEnabledRouter.getBindAddress().getHostName(),
            authEnabledRouter.getBindAddress().getPort(), sslEnabled);
    authenticationClient.configure(testProperties);
    try {//from  w  w  w  . j  a v a2 s.co m
        authenticationClient.getAccessToken();
        fail("Expected unauthorized status.");
    } catch (HttpFailureException e) {
        assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}

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

@Override
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) {
    HttpURLConnection connection = context.connection.getConnection();
    try {//  w  w w. j  a  va  2  s  .  com
        boolean renewCookie = false;
        int statusCode = connection.getResponseCode();
        switch (statusCode) {
        case HttpURLConnection.HTTP_FORBIDDEN: //403
            //check if it was an expiry case
            InputStream errorStream = connection.getErrorStream();
            String errorString = new String(IOUtils.toString(errorStream, "UTF-8"));
            try {
                JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject.class);
                String error = errorResponse.getAsJsonPrimitive("error").getAsString();
                String reason = errorResponse.getAsJsonPrimitive("reason").getAsString();
                if (!"credentials_expired".equals(error)) {
                    //wasn't a credentials expired, throw exception
                    throw new HttpConnectionInterceptorException(error, reason);
                } else {
                    // Was expired - set boolean to renew cookie
                    renewCookie = true;
                }
            } catch (JsonParseException e) {
                //wasn't JSON throw an exception
                throw new HttpConnectionInterceptorException(errorString);
            } finally {
                errorStream.close();
            }
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED: //401
            // We need to get a new cookie
            renewCookie = true;
            break;
        default:
            break;
        }
        if (renewCookie) {
            cookie = getCookie(connection.getURL(), context);
            // Don't resend request, failed to get cookie
            if (cookie != null) {
                context.replayRequest = true;
            } else {
                context.replayRequest = false;
            }
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to get response code from request", e);
    }
    return context;

}

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

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

    conn.setRequestProperty("Authorization", BASIC_AUTH);
    if (!StringUtil.isEmpty(taasUserKey)) {
        conn.setRequestProperty("TaaS-User-Key", taasUserKey);
    }
    conn.setRequestProperty("Accept", "text/xml");

    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:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Simple function to validate a user login.
 * Basically it only serves as a "calling point" and does not really validate a user
 * (since this is done previously by LAS2peer itself, the user does not reach this method
 * if he or she is not authenticated).//from  w ww  .j  a  v  a 2s.  c om
 * 
 */
@GET
@Path("/validation")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "User Validation", notes = "Simple function to validate a user login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Validation Confirmation"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
public HttpResponse validateLogin() {
    String returnString = "";
    returnString += "You are " + ((UserAgent) getActiveAgent()).getLoginName() + " and your login is valid!";

    return new HttpResponse(returnString, HttpURLConnection.HTTP_OK);
}

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

@Test
public void testIncorrectUser() throws Exception {
    CloseableHttpClient httpclient = null;
    try {/*from w  w w  .j ava2 s .c  o m*/
        String username = "nouser";
        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:com.mobile.godot.core.controller.CoreController.java

public synchronized void removeCar(String carName, LoginBean login) {

    String servlet = "RemoveCar";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("carName", carName));
    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.CAR_REMOVED);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();//  w  w  w  .  jav a 2s .  c o  m

}

From source file:co.cask.cdap.security.authentication.client.AbstractAuthenticationClient.java

/**
 * Fetches the available authentication server URL, if authentication is enabled in the gateway server,
 * otherwise, empty string will be returned.
 *
 * @return string value of the authentication server URL
 * @throws IOException IOException in case of a problem or the connection was aborted or if url list is empty
 *///  w  w  w.  j  a v  a  2 s . co m
private String fetchAuthURI() throws IOException {
    if (baseURI == null) {
        throw new IllegalStateException("Connection information not set!");
    }

    LOG.debug("Try to get the authentication URI from the gateway server: {}.", baseURI);
    HttpResponse response = HttpRequests.execute(HttpRequest.get(baseURI.toURL()).build(),
            getHttpRequestConfig());

    LOG.debug("Got response {} - {} from {}", response.getResponseCode(), response.getResponseMessage(),
            baseURI);
    if (response.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED) {
        return "";
    }

    Map<String, List<String>> responseMap = ObjectResponse
            .fromJsonBody(response, new TypeToken<Map<String, List<String>>>() {
            }).getResponseObject();
    LOG.debug("Response map from gateway server: {}", responseMap);

    String result;
    List<String> uriList = responseMap.get(AUTH_URI_KEY);
    if (uriList != null && !uriList.isEmpty()) {
        result = uriList.get(RANDOM.nextInt(uriList.size()));
    } else {
        throw new IOException("Authentication servers list is empty.");
    }
    return result;
}