List of usage examples for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN
int SC_FORBIDDEN
To view the source code for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.
Click Source Link
From source file:org.openanzo.client.BinaryStoreClient.java
private void authenticate() throws AnzoException { try {/*from w w w. java2s.com*/ URL aURL = new URL(authentication_url); httpclient.getHostConfiguration().setHost(aURL.getHost(), aURL.getPort(), aURL.getProtocol()); PostMethod authpost = new PostMethod(aURL.getPath()); NameValuePair formUserid = new NameValuePair( EncryptedTokenAuthenticatorConstants.USERNAME_PARAMETER_NAME, anzoClient.clientDatasource.getServiceUser()); NameValuePair formPassword = new NameValuePair( EncryptedTokenAuthenticatorConstants.PASSWORD_PARAMETER_NAME, anzoClient.clientDatasource.getServicePassword()); authpost.setRequestBody(new NameValuePair[] { formUserid, formPassword }); authpost.addRequestHeader("X-Requested-With", "XMLHttpRequest"); authpost.setDoAuthentication(false); httpclient.executeMethod(authpost); if (authpost.getStatusCode() == HttpStatus.SC_FORBIDDEN) { throw new AnzoException(ExceptionConstants.SERVER.BAD_USER_PASSWORD); } authpost.releaseConnection(); CookieSpec cookiespec = CookiePolicy.getDefaultSpec(); Cookie[] logoncookies = cookiespec.match(aURL.getHost(), aURL.getPort() == -1 ? aURL.getDefaultPort() : aURL.getPort(), "/", false, httpclient.getState().getCookies()); boolean authenticated = false; for (int i = 0; i < logoncookies.length; i++) { if (logoncookies[i].getName().equals(EncryptedTokenAuthenticatorConstants.ANZO_TOKEN_COOKIE_NAME)) authenticated = true; } if (!authenticated) throw new AnzoException(ExceptionConstants.SERVER.BAD_USER_PASSWORD); } catch (IOException e) { throw new AnzoException(ExceptionConstants.BINARYSTORECLIENT.BINARYSTORECLIENT_ERROR, e); } }
From source file:org.openanzo.test.TestEncryptedTokenAuthorizationBlocksServletAccess.java
/** * Trying to access a protected path without proper authentication should prevent access to the servlet. * /*w w w . j a v a 2 s . c om*/ * @throws Exception */ public void testUnauthenticatedProtectedPathAccessDoesNotReachServlet() throws Exception { resetServletCounter(); // Try to tell the servlet to increment the counter via a path that is protected by authentication. // This should fail via an authentication error. HttpClient client = new HttpClient(); GetMethod request = new GetMethod(getControlServletURI() + PROTECTED_URI_PATH + "increment_the_counter"); request.addRequestHeader("X-Requested-With", "XMLHttpRequest"); client.executeMethod(request); int statusCode = request.getStatusCode(); assertEquals("Invalid status code. Status text: " + request.getStatusText(), HttpStatus.SC_FORBIDDEN, statusCode); // Get the value of the counter (via a non-protected path) to make sure it stayed at zero. request = new GetMethod(getControlServletURI() + ControlServlet.OPERATION_URI_SUFFIX_COUNTER_READ); request.addRequestHeader("X-Requested-With", "XMLHttpRequest"); client.executeMethod(request); statusCode = request.getStatusCode(); assertEquals("Invalid status code. Status text: " + request.getStatusText(), HttpStatus.SC_OK, statusCode); assertEquals("0", request.getResponseBodyAsString()); }
From source file:org.openanzo.test.TestEncryptedTokenAuthorizationBlocksServletAccess.java
/** * An authenticate request should not invoke the protected servlet. It should be handled only by the authenticator in both successful and invalid * authentication cases.// w w w .ja v a 2 s . c o m * * @throws Exception */ public void testFailedAuthenticateRequestDoesNotReachServlet() throws Exception { resetServletCounter(); Pair<String, String> userInfo = getDefaultUserAndPassword(); // Send a authentication request that we expect to fail. HttpClient client = new HttpClient(); PostMethod authpost = new PostMethod( getControlServletURI() + EncryptedTokenAuthenticatorConstants.LOGIN_URI_SUFFIX); NameValuePair formUserid = new NameValuePair(EncryptedTokenAuthenticatorConstants.USERNAME_PARAMETER_NAME, userInfo.first); NameValuePair formPassword = new NameValuePair(EncryptedTokenAuthenticatorConstants.PASSWORD_PARAMETER_NAME, "anIncorrectPassword"); authpost.setRequestBody(new NameValuePair[] { formUserid, formPassword }); authpost.addRequestHeader("X-Requested-With", "XMLHttpRequest"); authpost.setDoAuthentication(false); client.executeMethod(authpost); int statusCode = authpost.getStatusCode(); assertEquals("Invalid status code. Status text: " + authpost.getStatusText(), HttpStatus.SC_FORBIDDEN, statusCode); authpost.releaseConnection(); Cookie[] logoncookies = client.getState().getCookies(); boolean authenticated = false; for (int i = 0; i < logoncookies.length; i++) { if (logoncookies[i].getName().equals(EncryptedTokenAuthenticatorConstants.ANZO_TOKEN_COOKIE_NAME)) authenticated = true; } assertFalse("Expect a failed authentication.", authenticated); // Get the value of the counter (via a non-protected path) to make sure it stayed at zero, which would indicate the // servlet wasn't touched by the authenticate request. GetMethod request = new GetMethod( getControlServletURI() + ControlServlet.OPERATION_URI_SUFFIX_COUNTER_READ); request.addRequestHeader("X-Requested-With", "XMLHttpRequest"); client.executeMethod(request); statusCode = request.getStatusCode(); assertEquals("Invalid status code. Status text: " + request.getStatusText(), HttpStatus.SC_OK, statusCode); assertEquals("0", request.getResponseBodyAsString()); }
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function does the GET http communication to the device * *//*from w ww.j av a2 s . co m*/ public byte[] getDataFromService(String service) { byte[] responseBodyB64 = null; int maxNbrGets = 3; int statusCode = 0; // Create an instance of HttpClient. if (client == null) { client = new HttpClient(); } synchronized (client) { // Create a method instance. GetMethod method = new GetMethod("http://" + device.getIP4Address() + service); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Set the right header method.setRequestHeader("Accept", "application/json"); method.addRequestHeader("User-Agent", "TeleHeater/2.2.3"); try { for (int i = 0; i < maxNbrGets && statusCode != HttpStatus.SC_OK; i++) { // Execute the method. statusCode = client.executeMethod(method); // Check the status switch (statusCode) { case HttpStatus.SC_OK: break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: /* Unknown problem with the device, wait and try again */ logger.warn("HTTP GET failed: 500, internal server error, repeating.. "); Thread.sleep(2000L); continue; case HttpStatus.SC_FORBIDDEN: /* Service is available but not readable */ byte[] test = new byte[1]; return test; default: logger.error("HTTP GET failed: {}", method.getStatusLine()); return null; } } device.setCharSet(method.getResponseCharSet()); // Read the response body. responseBodyB64 = ByteStreams.toByteArray(method.getResponseBodyAsStream()); } catch (HttpException e) { logger.error("Fatal protocol violation: {}", e.getMessage()); } catch (InterruptedException e) { logger.error("Sleep was interrupted: {}", e.getMessage()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return responseBodyB64; } }
From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java
private int computeStatus(int status) { switch (status) { case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_METHOD_NOT_ALLOWED: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_NOT_ACCEPTABLE: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: case HttpStatus.SC_REQUEST_TIMEOUT: case HttpStatus.SC_CONFLICT: case HttpStatus.SC_GONE: case HttpStatus.SC_LENGTH_REQUIRED: case HttpStatus.SC_PRECONDITION_FAILED: case HttpStatus.SC_REQUEST_TOO_LONG: case HttpStatus.SC_REQUEST_URI_TOO_LONG: case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE: case HttpStatus.SC_EXPECTATION_FAILED: case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE: case HttpStatus.SC_METHOD_FAILURE: case HttpStatus.SC_UNPROCESSABLE_ENTITY: case HttpStatus.SC_LOCKED: case HttpStatus.SC_FAILED_DEPENDENCY: case HttpStatus.SC_INTERNAL_SERVER_ERROR: case HttpStatus.SC_NOT_IMPLEMENTED: case HttpStatus.SC_BAD_GATEWAY: case HttpStatus.SC_SERVICE_UNAVAILABLE: case HttpStatus.SC_GATEWAY_TIMEOUT: case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED: case HttpStatus.SC_INSUFFICIENT_STORAGE: return 0; case HttpStatus.SC_CONTINUE: case HttpStatus.SC_SWITCHING_PROTOCOLS: case HttpStatus.SC_PROCESSING: case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION: case HttpStatus.SC_NO_CONTENT: case HttpStatus.SC_RESET_CONTENT: case HttpStatus.SC_PARTIAL_CONTENT: case HttpStatus.SC_MULTI_STATUS: case HttpStatus.SC_MULTIPLE_CHOICES: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_NOT_MODIFIED: case HttpStatus.SC_USE_PROXY: case HttpStatus.SC_TEMPORARY_REDIRECT: return 1; default:/*w ww . j a v a2s .com*/ return 1; } }
From source file:org.paxle.filter.robots.impl.RobotsTxtManager.java
/** * Downloads a <i>robots.txt</i> file from the given url and parses it * @param robotsUrlStr the URL to the robots.txt. This must be a http(s) resource * @return the parsed robots.txt file as a {@link RobotsTxt}-object * @throws IOException/* w w w. j av a2 s . c o m*/ * @throws URISyntaxException */ RobotsTxt getFromWeb(URI robotsURL) throws IOException, URISyntaxException { String hostPort = this.getHostPort(robotsURL); String statusLine = null; if (!robotsURL.getScheme().startsWith("http")) { throw new IOException(String.format("Unsupported protocol: %s", robotsURL.getScheme())); } InputStream inputStream = null; HttpMethod getMethod = null; try { getMethod = new GetMethod(robotsURL.toASCIIString()); int code = this.httpClient.executeMethod(getMethod); statusLine = getMethod.getStatusLine().toString(); if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) { // access to the whole website is restricted return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine, true); } else if (code == HttpStatus.SC_NOT_FOUND) { // no robots.txt provided return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine); } else if (code != HttpStatus.SC_OK) { // the robots.txt seems not to be deliverable return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine); } Header contentTypeHeader = getMethod.getResponseHeader("Content-Type"); if (contentTypeHeader != null && !contentTypeHeader.getValue().startsWith("text/plain")) { // the robots.txt seems not to be available return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_ERROR, "Wrong mimeType " + contentTypeHeader.getValue()); } inputStream = getMethod.getResponseBodyAsStream(); RobotsTxt robotsTxt = new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, statusLine); return this.parseRobotsTxt(robotsTxt, inputStream); } catch (IOException e) { long reloadInterval = RobotsTxt.RELOAD_INTERVAL_TEMP_ERROR; String status = e.getMessage(); if (e instanceof UnknownHostException) { reloadInterval = RobotsTxt.RELOAD_INTERVAL_ERROR; status = "Unknown host"; logger.info(String.format("Unknown host '%s'.", robotsURL.getHost())); } else if (e instanceof CircularRedirectException || e instanceof RedirectException || e instanceof InvalidRedirectLocationException) { reloadInterval = RobotsTxt.RELOAD_INTERVAL_ERROR; logger.info(String.format("Invalid redirection on host '%s'.", hostPort)); } else if (e instanceof SocketTimeoutException || e instanceof ConnectTimeoutException || e instanceof NoHttpResponseException) { logger.debug(String.format("TimeOut while loading robots.txt from host '%s'.", hostPort)); } else if (!(e instanceof ConnectException || e instanceof SocketException)) { logger.error("Exception while loading robots.txt from " + hostPort, e); } return new RobotsTxt(hostPort, reloadInterval, status); } catch (IllegalArgumentException e) { // occurs if redirected to an invalid URI, see https://bugs.pxl.li/view.php?id=172 // we treat it like a 404, see above logger.info(String.format("Invalid redirection URI on host '%s'.", hostPort)); return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, "Redirected to illegal URI"); } catch (IllegalStateException e) { // occurs if redirected to an URI with an invalid protocol, see https://bugs.pxl.li/view.php?id=169 // we treat it like a 404, see above logger.info(String.format("Invalid redirection URI on host '%s'.", hostPort)); return new RobotsTxt(hostPort, RobotsTxt.RELOAD_INTERVAL_DEFAULT, "Redirected to illegal URI"); } finally { if (inputStream != null) try { inputStream.close(); } catch (Exception e) { this.logger.error(e); } if (getMethod != null) getMethod.releaseConnection(); } }
From source file:org.phenotips.security.authorization.remote.internal.RemoteAuthorizationModule.java
private byte remoteCheck(String right, String username, String internalId, String externalId) { HttpPost method = new HttpPost(this.remoteServiceURL); JSONObject payload = new JSONObject(); payload.element("access", right); payload.element("username", username); payload.element("patient-id", internalId); payload.element("patient-eid", externalId); method.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON)); CloseableHttpResponse response = null; try {//from w ww.j a v a 2 s . c o m response = this.client.execute(method); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { cacheResponse(getCacheKey(username, right, internalId), Boolean.TRUE, response); return GRANTED; } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) { cacheResponse(getCacheKey(username, right, internalId), Boolean.FALSE, response); return DENIED; } } catch (IOException ex) { this.logger.warn("Failed to communicate with the authorization server: {}", ex.getMessage(), ex); return ERROR; } finally { if (response != null) { try { response.close(); } catch (IOException e) { // Just ignore, this shouldn't happen } } } return UNKNWON; }
From source file:org.phenotips.security.authorization.remote.internal.RemoteAuthorizationModuleTest.java
@Test public void refusesAccessWithForbiddenResponse() throws Exception { setupNeededComponents();//from www. j a v a2s . c o m when(this.client.execute(any(HttpPost.class))).thenReturn(this.response); when(this.response.getStatusLine()).thenReturn(this.status); when(this.status.getStatusCode()).thenReturn(HttpStatus.SC_FORBIDDEN); Assert.assertFalse(this.mocker.getComponentUnderTest().hasAccess(this.user, this.access, this.document)); verify(this.cache).set("jdoe::edit::P0000001", false); }
From source file:org.phenotips.security.authorization.remote.internal.RemoteAuthorizationModuleTest.java
@Test public void noActionWithOtherResponses() throws Exception { setupNeededComponents();//w w w .j ava 2s. co m when(this.client.execute(any(HttpPost.class))).thenReturn(this.response); when(this.response.getStatusLine()).thenReturn(this.status); for (int i = 0; i < 600; ++i) { if (i == HttpStatus.SC_OK || i == HttpStatus.SC_FORBIDDEN) { continue; } when(this.status.getStatusCode()).thenReturn(i); Assert.assertNull(this.mocker.getComponentUnderTest().hasAccess(this.user, this.access, this.document)); } // Other responses are not cached verify(this.cache, never()).set(Matchers.anyString(), Matchers.anyBoolean()); }
From source file:org.picketlink.test.authentication.web.BasicAuthenticationSchemeFromAjaxClientTestCase.java
@Test @OperateOnDeployment("default") public void testSuccessfulAuthentication() throws Exception { WebClient client = new WebClient(); WebRequestSettings request = new WebRequestSettings(getProtectedResourceURL()); prepareAjaxRequest(request);/*from ww w .ja v a2 s .c om*/ WebResponse response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_FORBIDDEN, response.getStatusCode()); String authenticateHeader = response.getResponseHeaderValue("WWW-Authenticate"); assertNotNull(authenticateHeader); assertTrue(authenticateHeader.contains("Basic realm=\"Test Realm\"")); prepareAuthenticationRequest(request, DEFAULT_USERNAME, DEFAULT_USER_PASSWD); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); request.setUrl(getContextPath()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Index Page", response.getContentAsString()); request.setUrl(getProtectedResourceURL()); response = client.loadWebResponse(request); assertEquals(HttpStatus.SC_OK, response.getStatusCode()); assertEquals("Protected Page", response.getContentAsString()); }