List of usage examples for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED
int SC_UNAUTHORIZED
To view the source code for org.apache.commons.httpclient HttpStatus SC_UNAUTHORIZED.
Click Source Link
From source file:net.bryansaunders.jee6divelog.service.rest.SecurityApiIT.java
/** * Test Login./* ww w.j a v a2 s . com*/ */ @Test public void ifCredentialsInvalidThenFail() { final Credentials credentials = new Credentials(); credentials.setUsername("nope@fail.com"); credentials.setPassword("wrongpass"); given().contentType(ContentType.JSON).body(credentials).expect().statusCode(HttpStatus.SC_UNAUTHORIZED) .when().post(RestApiTest.URL_ROOT + "/security/login/"); }
From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.HttpConnectionCheckerTest.java
@Test public void shouldFailCheckConnectionToTheRepoWhenHttpClientReturnsAUnSuccessfulReturnCode() throws IOException { HttpClient httpClient = mock(HttpClient.class); GetMethod getMethod = mock(GetMethod.class); when(checker.getHttpClient()).thenReturn(httpClient); when(checker.getGetMethod(Matchers.<String>any())).thenReturn(getMethod); when(httpClient.executeMethod(getMethod)).thenReturn(HttpStatus.SC_UNAUTHORIZED); when(getMethod.getStatusLine()).thenReturn(new StatusLine("HTTP/1.1 401 Unauthorized")); try {/*from www .j ava2 s .co m*/ checker.checkConnection("url", new Credentials(null, null)); fail("should fail"); } catch (Exception e) { assertThat(e.getMessage(), is("HTTP/1.1 401 Unauthorized")); } verify(httpClient).executeMethod(getMethod); verify(getMethod).getStatusLine(); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java
@Override public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm, final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String oid = request.getParameter("oid"); final File file = FenixFramework.getDomainObject(oid); if (file == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close();// w ww .ja v a 2s . c o m } else { final Person person = AccessControl.getPerson(); if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) { response.setContentType(file.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename()); response.setContentLength(file.getSize().intValue()); final DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(file.getContents()); dos.close(); } else if (file.isPrivate() && person == null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED)); response.getWriter().close(); } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN)); response.getWriter().close(); } } return null; }
From source file:hr.fer.zemris.vhdllab.platform.remoting.HttpClientRequestExecutor.java
@SuppressWarnings("null") @Override//from w w w . j av a 2 s . c om protected void executePostMethod(HttpInvokerClientConfiguration config, HttpClient httpClient, PostMethod postMethod) throws IOException { AuthScope scope = new AuthScope(config.getCodebaseUrl(), AuthScope.ANY_PORT); super.executePostMethod(config, httpClient, postMethod); switch (postMethod.getStatusCode()) { case HttpStatus.SC_UNAUTHORIZED: UsernamePasswordCredentials credentials; if (Environment.isDevelopment() && !showRetryMessage) { credentials = new UsernamePasswordCredentials("test", "test"); // credentials = new UsernamePasswordCredentials("admin", "admin"); showRetryMessage = true; } else { CommandManager manager = Application.instance().getActiveWindow().getCommandManager(); LoginCommand command = (LoginCommand) manager.getCommand("loginCommand"); command.execute(); credentials = command.getCredentials(); } if (credentials == null) { System.exit(1); } ApplicationContextHolder.getContext().setUserId(credentials.getUserName()); showRetryMessage = true; getHttpClient().getState().setCredentials(scope, credentials); executePostMethod(config, httpClient, postMethod); break; } }
From source file:com.sap.netweaver.porta.core.nw7.FileUploaderImpl.java
public String[] upload(File[] archives) throws CoreException { // check if there are any credentials already set if (client == null) { // trigger the mechanism for requesting user for credentials throw new NotAuthorizedException(FAULT_UNAUTHORIZED.getFaultReason()); }/* w w w.j a v a2 s . com*/ PostMethod method = null; try { Part[] parts = new Part[archives.length]; for (int i = 0; i < archives.length; i++) { parts[i] = new FilePart(archives[i].getName(), archives[i]); } method = new PostMethod(url); method.setDoAuthentication(true); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new NotAuthorizedException(FAULT_INVALID_CREDENTIALS.getFaultReason()); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new NotAuthorizedException(FAULT_PERMISSION_DENIED.getFaultReason()); } else if (statusCode == HttpStatus.SC_NOT_FOUND) { throw new NoWSGateException(null, url); } else if (statusCode != HttpStatus.SC_OK) { throw new CoreException(method.getStatusText()); } InputStream responseStream = method.getResponseBodyAsStream(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream)); String line; List<String> paths = new ArrayList<String>(); while ((line = responseReader.readLine()) != null) { paths.add(line); } responseReader.close(); responseStream.close(); return paths.toArray(new String[] {}); } catch (HttpException e) { throw new CoreException(e); } catch (IOException e) { throw new CoreException(e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:com.discogs.api.webservice.impl.HttpClientWebService.java
@Override public Resp doGet(String url) throws WebServiceException { HttpMethod method = new GZipCapableGetMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); method.setDoAuthentication(true);/*from w w w . ja v a 2s . c o m*/ try { // execute the method int statusCode = this.httpClient.executeMethod(method); if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } switch (statusCode) { case HttpStatus.SC_OK: return createResp(method.getResponseBodyAsStream()); case HttpStatus.SC_NOT_FOUND: throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString()); case HttpStatus.SC_BAD_REQUEST: throw new RequestException(method.getResponseBodyAsString()); case HttpStatus.SC_FORBIDDEN: throw new AuthorizationException(method.getResponseBodyAsString()); case HttpStatus.SC_UNAUTHORIZED: throw new AuthorizationException(method.getResponseBodyAsString()); default: String em = "web service returned unknown status '" + statusCode + "', response was: " + method.getResponseBodyAsString(); logger.error(em); throw new WebServiceException(em); } } catch (HttpException e) { logger.error("Fatal protocol violation: " + e.getMessage()); throw new WebServiceException(e.getMessage(), e); } catch (IOException e) { logger.error("Fatal transport error: " + e.getMessage()); throw new WebServiceException(e.getMessage(), e); } finally { method.releaseConnection(); } }
From source file:com.owncloud.android.operations.RemoteOperationResult.java
private RemoteOperationResult(boolean success, int httpCode) { mSuccess = success;//from w w w .ja va 2s. com mHttpCode = httpCode; if (success) { mCode = ResultCode.OK; } else if (httpCode > 0) { switch (httpCode) { case HttpStatus.SC_UNAUTHORIZED: mCode = ResultCode.UNAUTHORIZED; break; case HttpStatus.SC_NOT_FOUND: mCode = ResultCode.FILE_NOT_FOUND; break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: mCode = ResultCode.INSTANCE_NOT_CONFIGURED; break; case HttpStatus.SC_CONFLICT: mCode = ResultCode.CONFLICT; break; case HttpStatus.SC_INSUFFICIENT_STORAGE: mCode = ResultCode.QUOTA_EXCEEDED; break; default: mCode = ResultCode.UNHANDLED_HTTP_CODE; Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode); } } }
From source file:com.cloud.utils.rest.RESTValidationStrategy.java
public void executeMethod(final HttpMethodBase method, final HttpClient client, final String protocol) throws CloudstackRESTException, HttpException, IOException { if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null || password.isEmpty()) {/*from w w w.j a v a 2 s . c o m*/ throw new CloudstackRESTException("Hostname/credentials are null or empty"); } client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { method.releaseConnection(); // login and try again login(protocol, client); client.executeMethod(method); } }
From source file:com.owncloud.android.operations.DetectAuthenticationMethodOperation.java
/** * Performs the operation./* w w w .j a v a2s .c o m*/ * * Triggers a check of existence on the root folder of the server, granting * that the request is not authenticated. * * Analyzes the result of check to find out what authentication method, if * any, is requested by the server. */ @Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; AuthenticationMethod authMethod = AuthenticationMethod.UNKNOWN; RemoteOperation operation = new ExistenceCheckRemoteOperation("", mContext, false); client.clearCredentials(); client.setFollowRedirects(false); // try to access the root folder, following redirections but not SAML SSO redirections result = operation.execute(client); String redirectedLocation = result.getRedirectedLocation(); while (redirectedLocation != null && redirectedLocation.length() > 0 && !result.isIdPRedirection()) { client.setBaseUri(Uri.parse(result.getRedirectedLocation())); result = operation.execute(client); redirectedLocation = result.getRedirectedLocation(); } // analyze response if (result.getHttpCode() == HttpStatus.SC_UNAUTHORIZED) { String authRequest = ((result.getAuthenticateHeader()).trim()).toLowerCase(); if (authRequest.startsWith("basic")) { authMethod = AuthenticationMethod.BASIC_HTTP_AUTH; } else if (authRequest.startsWith("bearer")) { authMethod = AuthenticationMethod.BEARER_TOKEN; } // else - fall back to UNKNOWN } else if (result.isSuccess()) { authMethod = AuthenticationMethod.NONE; } else if (result.isIdPRedirection()) { authMethod = AuthenticationMethod.SAML_WEB_SSO; } // else - fall back to UNKNOWN Log_OC.d(TAG, "Authentication method found: " + authenticationMethodToString(authMethod)); if (!authMethod.equals(AuthenticationMethod.UNKNOWN)) { result = new RemoteOperationResult(true, result.getHttpCode(), null); } ArrayList<Object> data = new ArrayList<Object>(); data.add(authMethod); result.setData(data); return result; // same result instance, so that other errors // can be handled by the caller transparently }
From source file:com.owncloud.android.oc_framework.operations.RemoteOperationResult.java
private RemoteOperationResult(boolean success, int httpCode) { mSuccess = success;/*ww w .jav a 2 s . c o m*/ mHttpCode = httpCode; if (success) { mCode = ResultCode.OK; } else if (httpCode > 0) { switch (httpCode) { case HttpStatus.SC_UNAUTHORIZED: mCode = ResultCode.UNAUTHORIZED; break; case HttpStatus.SC_NOT_FOUND: mCode = ResultCode.FILE_NOT_FOUND; break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: mCode = ResultCode.INSTANCE_NOT_CONFIGURED; break; case HttpStatus.SC_CONFLICT: mCode = ResultCode.CONFLICT; break; case HttpStatus.SC_INSUFFICIENT_STORAGE: mCode = ResultCode.QUOTA_EXCEEDED; break; default: mCode = ResultCode.UNHANDLED_HTTP_CODE; Log.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode); } } }