Example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.

Click Source Link

Document

<tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.zimbra.qa.unittest.TestCollectConfigServletsAccess.java

/**
 * Verify that an HTTP client canNOT access servlet at /service/collectconfig/ without an auth token
 * @throws Exception/*w ww.  ja  v  a2  s  .com*/
 */
@Test
public void testConfigNoToken() throws Exception {
    URI servletURI = new URI(getConfigServletUrl());
    HttpClient restClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    restClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    GetMethod get = new GetMethod(servletURI.toString());
    int statusCode = HttpClientUtil.executeMethod(restClient, get);
    assertEquals("This request should NOT succeed. Getting status code " + statusCode,
            HttpStatus.SC_UNAUTHORIZED, statusCode);
}

From source file:com.zimbra.qa.unittest.TestCookieReuse.java

/**
 * Verify that we canNOT RE-use the cookie taken from a legitimate HTTP session for a REST request
 * after ending the original session/*from  w w  w. j  ava  2  s. c om*/
 */
@Test
public void testForceEndSession() throws ServiceException, IOException {
    //establish legitimate connection
    TestUtil.setAccountAttr(USER_NAME, Provisioning.A_zimbraForceClearCookies, "FALSE");
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    URI uri = mbox.getRestURI("Inbox?fmt=rss");
    HttpClient alice = mbox.getHttpClient(uri);

    //create evesdropper's connection
    HttpClient eve = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Cookie[] cookies = alice.getState().getCookies();
    HttpState state = new HttpState();
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        state.addCookie(new Cookie(uri.getHost(), cookie.getName(), cookie.getValue(), "/", null, false));
    }
    eve.setState(state);
    Account a = TestUtil.getAccount(USER_NAME);
    a.setForceClearCookies(false);

    EndSessionRequest esr = new EndSessionRequest();
    esr.setLogOff(true);
    mbox.invokeJaxb(esr);
    GetMethod get = new GetMethod(uri.toString());
    int statusCode = HttpClientUtil.executeMethod(eve, get);
    Assert.assertEquals("This request should not succeed. Getting status code " + statusCode,
            HttpStatus.SC_UNAUTHORIZED, statusCode);
}

From source file:domderrien.wrapper.UrlFetch.UrlFetchHttpConnection.java

@Override
public String readLine(String charset) throws IOException, IllegalStateException {
    if (waitForHttpStatus) {
        // Dom Derrien: called only once to get the HTTP status, other information being read from the response output stream
        int responseCode = getResponse().getResponseCode();
        String line = "HTTP/1.1 " + responseCode;
        switch (responseCode) {
        case HttpStatus.SC_OK:
            line += " OK";
            break;
        case HttpStatus.SC_BAD_REQUEST:
            line += " BAD REQUEST";
            break;
        case HttpStatus.SC_UNAUTHORIZED:
            line += " UNAUTHORIZED";
            break;
        case HttpStatus.SC_FORBIDDEN:
            line += " FORBIDDEN";
            break;
        case HttpStatus.SC_NOT_FOUND:
            line += " NOT FOUND";
            break;
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            line += " INTERNAL SERVER ERROR";
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            line += " SERVICE UNAVAILABLE";
            break;
        default://from w  w w .  j a v  a  2 s.co m
            line = "HTTP/1.1 " + HttpStatus.SC_BAD_REQUEST + " BAD REQUEST";
        }
        waitForHttpStatus = false;
        return line;
    }
    throw new RuntimeException("readLine(String)");
}

From source file:com.serena.rlc.provider.jira.client.JiraClient.java

private JiraClientException createHttpError(HttpResponse response) {
    String message;//from ww w.j ava2 s.  com
    try {
        StatusLine statusLine = response.getStatusLine();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        StringBuffer responsePayload = new StringBuffer();
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            responsePayload.append(line);
        }

        message = String.format(" request not successful: %d %s. Reason: %s", statusLine.getStatusCode(),
                HttpStatus.getStatusText(statusLine.getStatusCode()), responsePayload);

        logger.debug(message);

        if (new Integer(HttpStatus.SC_UNAUTHORIZED).equals(statusLine.getStatusCode())) {
            return new JiraClientException("Invalid credentials provided.");
        } else if (new Integer(HttpStatus.SC_NOT_FOUND).equals(statusLine.getStatusCode())) {
            return new JiraClientException("JIRA: Request URL not found.");
        } else if (new Integer(HttpStatus.SC_BAD_REQUEST).equals(statusLine.getStatusCode())) {
            return new JiraClientException("JIRA: Bad request. " + responsePayload);
        }
    } catch (IOException e) {
        return new JiraClientException("JIRA: Can't read response");
    }

    return new JiraClientException(message);
}

From source file:com.moss.bdbadmin.openejb.BdbAdminOpenEjbAdapter.java

public void onMessage(final HttpRequest request, final HttpResponse response) throws Exception {

    final IdProof assertion;
    {/* w  ww .  j  a v  a2s.  c o  m*/
        IdProof a = null;

        String value = request.getHeader(AuthenticationHeader.HEADER_NAME);
        if (value != null && value.length() > 0) {
            try {
                a = AuthenticationHeader.decode(value);
            } catch (Exception ex) {
                ex.printStackTrace();
                a = null;
            }
        } else {
            System.out.println("No assertion included in request header");
            a = null;
        }

        assertion = a;
    }

    final ServiceResource resource;
    {
        String path;
        if (request.getURI().getPath().length() >= contextPath.length()) {
            path = request.getURI().getPath().substring(contextPath.length()).trim();
        } else {
            path = request.getURI().getPath();
        }

        ServiceResource r = null;
        ;
        try {
            r = service.resolve(path);
        } catch (ResourcePathException ex) {
            ex.printStackTrace();
        }

        resource = r;
    }

    if (assertion == null || resource == null) {
        response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
    } else {
        abstract class Handler {
            abstract void handle() throws Exception;
        }

        Handler handler = resource.acceptVisitor(new ServiceResourceVisitor<Handler>() {
            public Handler visit(BdbMapResource map) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod().name())) {
                            byte[] data = service.map(assertion);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(BdbCategory category) {
                return null;
            }

            public Handler visit(BdbEnv env) {
                return null;
            }

            public Handler visit(final BdbDb db) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("GET".equals(request.getMethod().name())) {
                            byte[] data = service.dbInfo(assertion, db);
                            response.setHeader("Content-Length", Integer.toString(data.length));
                            response.getOutputStream().write(data);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else if ("DELETE".equals(request.getMethod().name())) {
                            service.clearDb(assertion, db);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }

            public Handler visit(final BdbEntityResource entity) {
                return new Handler() {
                    public void handle() throws IdProovingException, NotAuthorizedException, IOException {
                        if ("OPTIONS".equals(request.getMethod().name())) {
                            byte[] data = service.entryInfo(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("GET".equals(request.getMethod().name())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setHeader("Content-Length", Integer.toString(data.length));
                                response.getOutputStream().write(data);
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("HEAD".equals(request.getMethod().name())) {
                            byte[] data = service.getEntry(assertion, entity);
                            if (data == null) {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            } else {
                                response.setStatusCode(HttpStatus.SC_OK);
                            }
                        } else if ("PUT".equals(request.getMethod().name())) {

                            byte[] input;
                            {
                                InputStream in = request.getInputStream();
                                ByteArrayOutputStream out = new ByteArrayOutputStream();

                                byte[] buffer = new byte[1023 * 10]; //10k buffer
                                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                                    out.write(buffer, 0, numRead);
                                }

                                in.close();
                                out.close();

                                input = out.toByteArray();
                            }

                            service.putEntry(assertion, entity, input);
                            response.setStatusCode(HttpStatus.SC_OK);
                        } else if ("DELETE".equals(request.getMethod().name())) {
                            if (service.deleteEntry(assertion, entity)) {
                                response.setStatusCode(HttpStatus.SC_OK);
                            } else {
                                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                            }
                        } else {
                            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
                        }
                    }
                };
            }
        });

        if (handler == null) {
            System.out.println("Cannot perform any methods on requested path");
            response.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
        } else {
            try {
                handler.handle();
            } catch (IdProovingException ex) {
                ex.printStackTrace();
                response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
            } catch (NotAuthorizedException ex) {
                ex.printStackTrace();
                response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
    }

    response.getOutputStream().close();
}

From source file:com.idega.slide.business.FileSystemCopyServiceBean.java

private void connect() {

    /*//from   w w w. ja v a  2s  .c  o m
    if (!uri.endsWith("/") && !uri.endsWith("\\")) {
    // append / to the path
     uri+="/";
    }
    */
    //System.out.println("connect " + uri);
    try {
        //httpURL = uriToHttpURL(uri);
        //          httpURL.setUserinfo("root","root");
        if (this.webdavResource == null) {
            this.webdavResource = getService().getWebdavExternalResourceAuthenticatedAsRoot();
            //webdavResource.setDebug(Integer.MAX_VALUE);

            // is not a collection?
            if (!this.webdavResource.getResourceType().isCollection()) {
                this.webdavResource = null;
                this.httpURL = null;
                //System.out.println("Error: " + uri + " is not a collection! Use open/connect only for collections!");
            }

        } else {
            this.webdavResource.close();
            //            webdavResource.setHttpURL(httpURL);
            this.webdavResource = getService().getWebdavExternalResourceAuthenticatedAsRoot();
        }
        setPath(this.webdavResource.getPath() + CoreConstants.PATH_FILES_ROOT);
    } catch (HttpException we) {
        System.out.print("HttpException.getReasonCode(): " + we.getReasonCode());
        if (we.getReasonCode() == HttpStatus.SC_UNAUTHORIZED) {
            try {

                String userName = "root";
                if ((userName == null) || (userName.length() == 0)) {
                    disconnect();
                    return;
                }
                userName = userName.trim();
                String password = "root";
                if (password != null) {
                    password = password.trim();
                }
                try {
                    if (this.webdavResource != null) {
                        this.webdavResource.close();
                    }
                } catch (IOException e) {
                } finally {
                    this.httpURL = null;
                    this.webdavResource = null;
                }
                //httpURL = uriToHttpURL(uri);
                // It should be used like this way.
                this.httpURL.setUserinfo(userName, password);
                this.webdavResource = new WebdavResource(this.httpURL);
                //webdavResource.setDebug(Integer.MAX_VALUE);
                setPath(this.webdavResource.getPath());

                if (!this.webdavResource.getResourceType().isCollection()) {
                    this.webdavResource = null;
                    this.httpURL = null;
                    System.out.println("Error: " + this.httpURL.getURI()
                            + " is not a collection! Use open/connect only for collections!");
                }
            } catch (Exception ex) {
                handleException(ex);
                this.httpURL = null;
                this.webdavResource = null;
            }
        } else {
            handleException(we);
            this.httpURL = null;
            this.webdavResource = null;
        }
    } catch (Exception ex) {
        handleException(ex);
        this.webdavResource = null;
        this.httpURL = null;
    }

}

From source file:davmail.exchange.ExchangeSession.java

/**
 * Create an exchange session for the given URL.
 * The session is established for given userName and password
 *
 * @param url      Exchange url/* w w w . j  a  va  2s . c  o  m*/
 * @param userName user login name
 * @param password user password
 * @throws IOException on error
 */
public ExchangeSession(String url, String userName, String password) throws IOException {
    this.userName = userName;
    try {
        httpClient = DavGatewayHttpClientFacade.getInstance(url);
        // set private connection pool
        DavGatewayHttpClientFacade.createMultiThreadedHttpConnectionManager(httpClient);
        boolean isBasicAuthentication = isBasicAuthentication(httpClient, url);
        // clear cookies created by authentication test
        httpClient.getState().clearCookies();

        // The user may have configured an OTP pre-auth username. It is processed
        // so early because OTP pre-auth may disappear in the Exchange LAN and this
        // helps the user to not change is account settings in mail client at each network change.
        if (preAuthUsername == null) {
            // Searches for the delimiter in configured username for the pre-auth user. 
            // The double-quote is not allowed inside email addresses anyway.
            int doubleQuoteIndex = this.userName.indexOf('"');
            if (doubleQuoteIndex > 0) {
                preAuthUsername = this.userName.substring(0, doubleQuoteIndex);
                this.userName = this.userName.substring(doubleQuoteIndex + 1);
            } else {
                // No doublequote: the pre-auth user is the full username, or it is not used at all.
                preAuthUsername = this.userName;
            }
        }

        DavGatewayHttpClientFacade.setCredentials(httpClient, userName, password);

        // get webmail root url
        // providing credentials
        // manually follow redirect
        HttpMethod method = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, url);

        if (!this.isAuthenticated()) {
            if (isBasicAuthentication) {
                int status = method.getStatusCode();

                if (status == HttpStatus.SC_UNAUTHORIZED) {
                    method.releaseConnection();
                    throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
                } else if (status != HttpStatus.SC_OK) {
                    method.releaseConnection();
                    throw DavGatewayHttpClientFacade.buildHttpException(method);
                }
                // workaround for basic authentication on /exchange and form based authentication at /owa
                if ("/owa/auth/logon.aspx".equals(method.getPath())) {
                    method = formLogin(httpClient, method, userName, password);
                }
            } else {
                method = formLogin(httpClient, method, userName, password);
            }
        }

        // avoid 401 roundtrips, only if NTLM is disabled and basic authentication enabled
        if (isBasicAuthentication && !DavGatewayHttpClientFacade.hasNTLM(httpClient)) {
            httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
        }

        buildSessionInfo(method);

    } catch (DavMailAuthenticationException exc) {
        LOGGER.error(exc.getMessage());
        throw exc;
    } catch (UnknownHostException exc) {
        BundleMessage message = new BundleMessage("EXCEPTION_CONNECT", exc.getClass().getName(),
                exc.getMessage());
        ExchangeSession.LOGGER.error(message);
        throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
    } catch (WebdavNotAvailableException exc) {
        throw exc;
    } catch (IOException exc) {
        LOGGER.error(BundleMessage.formatLog("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc));
        throw new DavMailException("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc);
    }
    LOGGER.debug("Session " + this + " created");
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

private static int checkNTLM(HttpClient httpClient, HttpMethod currentMethod) throws IOException {
    int status = currentMethod.getStatusCode();
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && acceptsNTLMOnly(currentMethod) && !hasNTLM(httpClient)) {
        LOGGER.debug(//from   w w w .j  a  v  a  2 s.  c om
                "Received " + status + " unauthorized at " + currentMethod.getURI() + ", retrying with NTLM");
        resetMethod(currentMethod);
        addNTLM(httpClient);
        status = httpClient.executeMethod(currentMethod);
    }
    return status;
}

From source file:com.thoughtworks.go.server.service.ScheduleServiceTest.java

@Test
public void shouldNotCancelStageWhenTheUserDoesNotHaveOperatePermission() throws Exception {
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    Pipeline pipeline = PipelineMother.pipeline("pipeline-name",
            StageMother.passedStageInstance("mingle", "job-bar", "pipeline-name"));
    Stage spiedStage = spy(pipeline.getFirstStage());

    long stageId = spiedStage.getId();
    Username admin = new Username(new CaseInsensitiveString("admin"));

    doReturn(true).when(spiedStage).isActive();
    when(stageService.stageById(stageId)).thenReturn(spiedStage);
    when(securityService.hasOperatePermissionForStage(pipeline.getName(), spiedStage.getName(),
            admin.getUsername().toString())).thenReturn(false);

    Stage resultStage = service.cancelAndTriggerRelevantStages(stageId, admin, result);

    assertThat(resultStage, is(nullValue()));
    assertThat(result.httpCode(), is(HttpStatus.SC_UNAUTHORIZED));
    assertThat(result.isSuccessful(), is(false));
    verify(securityService).hasOperatePermissionForStage(pipeline.getName(), spiedStage.getName(),
            admin.getUsername().toString());
    verify(stageService, never()).cancelStage(spiedStage);
    verify(spiedStage).isActive();//from   w ww.java 2 s  . co m
}

From source file:com.serena.rlc.provider.jenkins.client.JenkinsClient.java

private JenkinsClientException createHttpError(HttpResponse response) {
    String message;//  w  ww. j a v a2 s.c o  m
    try {
        StatusLine statusLine = response.getStatusLine();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        StringBuffer responsePayload = new StringBuffer();
        // Read response until the end
        while ((line = rd.readLine()) != null) {
            responsePayload.append(line);
        }

        message = String.format("request not successful: %d %s. Reason: %s", statusLine.getStatusCode(),
                HttpStatus.getStatusText(statusLine.getStatusCode()), responsePayload);

        logger.info(message);

        if (new Integer(HttpStatus.SC_UNAUTHORIZED).equals(statusLine.getStatusCode())) {
            return new JenkinsClientException("Invalid credentials provided.");
        } else if (new Integer(HttpStatus.SC_NOT_FOUND).equals(statusLine.getStatusCode())) {
            return new JenkinsClientException("Jenkins: Request URL not found.");
        } else if (new Integer(HttpStatus.SC_BAD_REQUEST).equals(statusLine.getStatusCode())) {
            return new JenkinsClientException("Jenkins: Bad request. " + responsePayload);
        }
    } catch (IOException e) {
        return new JenkinsClientException("Jenkins: Can't read response");
    }

    return new JenkinsClientException(message);
}