List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED
int HTTP_UNAUTHORIZED
To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.
Click Source Link
From source file:de.lohndirekt.print.IppHttpConnection.java
public boolean execute() throws HttpException, IOException { if (this.method.validate()) { httpConn.executeMethod(method);/*from ww w .j av a2 s .co m*/ if (this.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new AuthenticationException(method.getStatusText()); } return true; } else { return false; } }
From source file:org.betaconceptframework.astroboa.resourceapi.locator.RepositoryLocator.java
@Path("{repositoryId}") public ResourceLocator connectToAstroboaRepository(@HeaderParam("Authorization") String authorization, @PathParam("repositoryId") String repositoryId, @Context ServletContext servletContext) { if (StringUtils.isBlank(repositoryId)) { throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND); }/*from w w w . j a v a 2s. c o m*/ try { AstroboaClient astroboaClient = null; long start = System.currentTimeMillis(); if (authorization != null) { String cacheKey = authorization + repositoryId; astroboaClient = AstroboaClientCache.Instance.get(cacheKey); if (astroboaClient == null) { String encodedUsernamePass = authorization.substring(5); String usernamePass = Base64.base64Decode(encodedUsernamePass); String[] usernamePassSplitted = usernamePass.split(":"); if (usernamePassSplitted.length == 2) { astroboaClient = new AstroboaClient(AstroboaClient.INTERNAL_CONNECTION); AstroboaCredentials credentials = new AstroboaCredentials(usernamePassSplitted[0], usernamePassSplitted[1]); astroboaClient.login(repositoryId, credentials); astroboaClient = AstroboaClientCache.Instance.cache(astroboaClient, cacheKey); } else { logger.error( "provided authorization in header (BASIC AUTH) cannot be decoded to username and password. Encoded Authorization String found in header is: " + authorization); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } } } else { // login as anonymous final String anonymousCacheKey = repositoryId + IdentityPrincipal.ANONYMOUS; astroboaClient = AstroboaClientCache.Instance.get(anonymousCacheKey); if (astroboaClient == null) { astroboaClient = new AstroboaClient(AstroboaClient.INTERNAL_CONNECTION); String permanentKey = retrievePermanentKeyForAnonymousUser(repositoryId, servletContext); astroboaClient.loginAsAnonymous(repositoryId, permanentKey); astroboaClient = AstroboaClientCache.Instance.cache(astroboaClient, anonymousCacheKey); } } logger.debug("Retrieve/Create astroboa repository client {} in {}", System.identityHashCode(astroboaClient), DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start)); return new ResourceLocator(astroboaClient); } catch (CmsInvalidPasswordException e) { logger.error("Login to Astroboa Repository was not successfull"); throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED); } catch (Exception e) { logger.error("A problem occured while connecting repository client to Astroboa Repository", e); throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND); } }
From source file:org.apache.sentry.api.service.thrift.TestSentryWebServerWithKerberos.java
@Test public void testPingUsingHttpURLConnection() throws Exception { final URL url = new URL("http://" + SentryServiceIntegrationBase.SERVER_HOST + ":" + SentryServiceIntegrationBase.webServerPort + "/ping"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); String errorMessage = IOUtils.toString(conn.getErrorStream()); Assert.assertTrue(errorMessage.contains("Authentication required")); }
From source file:co.cask.cdap.client.util.RESTClient.java
private HttpResponse execute(HttpRequest request, int... allowedErrorCodes) throws IOException, UnauthorizedException, DisconnectedException { int currentTry = 0; HttpResponse response;// w w w .j a v a 2 s . c o m do { onRequest(request, currentTry); response = HttpRequests.execute(request, clientConfig.getDefaultRequestConfig()); int responseCode = response.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) { currentTry++; try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { break; } continue; } onResponse(request, response, currentTry); if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException("Unauthorized status code received from the server."); } if (!isSuccessful(responseCode) && !ArrayUtils.contains(allowedErrorCodes, responseCode)) { throw new IOException(responseCode + ": " + response.getResponseBodyAsString()); } return response; } while (currentTry <= clientConfig.getUnavailableRetryLimit()); return response; }
From source file:net.mceoin.cominghome.api.NestUtil.java
/** * Make HTTP/JSON call to Nest and set away status. * * @param access_token OAuth token to allow access to Nest * @param structure_id ID of structure with thermostat * @param away_status Either "home" or "away" * @return Equal to "Success" if successful, otherwise it contains a hint on the error. *///from www . j a v a2s. c o m public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) { String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try { URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); String payload = "\"" + away_status + "\""; OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); log.info(payload); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); urlConnection.setRequestProperty("Accept", "application/json"); // System.out.println("Redirect to URL : " + newUrl); wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) { return "Error: " + errorResult; } else { return "Success"; } }
From source file:com.aptana.jira.core.JiraManager.java
/** * Logs into JIRA with a username and password. * /*from w w w .ja v a 2 s . co m*/ * @param username * the username * @param password * the password * @throws JiraException */ public void login(String username, String password) throws JiraException { HttpURLConnection connection = null; try { connection = createConnection(getUserURL(username), username, password); int code = connection.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { this.user = new JiraUser(username, password); saveCredentials(); return; } if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { throw new JiraException(Messages.JiraManager_BadCredentialsErrMsg); } throw new JiraException(Messages.JiraManager_UnknownErrMsg); } catch (Exception e) { throw new JiraException(e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:org.debux.webmotion.shiro.Shiro.java
/** * Check if the user is authenticated. Try to connect user if found login * information.//from w ww . j a v a 2 s .c om * * @param username * @param password * @param rememberMe * @return */ public Render isAuthenticated(HttpContext context, String username, String password, Boolean rememberMe) { Subject currentUser = getSubject(context); if (!currentUser.isAuthenticated()) { if (username != null && !username.isEmpty()) { // Try to log the user UsernamePasswordToken token = new UsernamePasswordToken(username, password); if (rememberMe != null) { token.setRememberMe(rememberMe); } try { currentUser.login(token); doProcess(); return null; } catch (AuthenticationException e) { log.error(e.getMessage(), e); throw e; } } return renderError(HttpURLConnection.HTTP_UNAUTHORIZED); } doProcess(); return null; }
From source file:com.alphabetbloc.accessmrs.tasks.CheckConnectivityTask.java
protected DataInputStream getServerStream() throws Exception { HttpPost request = new HttpPost(mServer); request.setEntity(new OdkAuthEntity()); HttpResponse response = httpClient.execute(request); response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); responseEntity.getContentLength();//from w w w . j a va 2 s. c om DataInputStream zdis = new DataInputStream(new GZIPInputStream(responseEntity.getContent())); int status = zdis.readInt(); if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { zdis.close(); throw new IOException("Access denied. Check your username and password."); } else if (status <= 0 || status >= HttpURLConnection.HTTP_BAD_REQUEST) { zdis.close(); throw new IOException("Connection Failed. Please Try Again."); } else { assert (status == HttpURLConnection.HTTP_OK); // success return zdis; } }
From source file:org.sofun.core.security.oauth.OAuthSofunProvider.java
private OAuthRequestToken doGetRequestToken(String customerKey, String requestKey) throws OAuthException { // get is atomic OAuthRequestToken ret = requestTokens.get(requestKey); checkCustomerKey(ret, customerKey);//from www.ja v a 2 s .c o m if (ret == null) throw new OAuthException(HttpURLConnection.HTTP_UNAUTHORIZED, "No such request key " + requestKey); return ret; }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testNotAuthorizedUnknownTokenGetTTL() throws IOException { AuthenticationClient authClient = Mockito.mock(AuthenticationClient.class); AccessToken accessToken = Mockito.mock(AccessToken.class); Mockito.when(authClient.getAccessToken()).thenReturn(accessToken); Mockito.when(accessToken.getValue()).thenReturn("test"); Mockito.when(accessToken.getTokenType()).thenReturn("Bearer"); streamClient = RestStreamClient.builder(testServerHost, testServerPort).authClient(authClient).build(); try {/*from www .ja v a 2s .c o m*/ streamClient.getTTL(TestUtils.AUTH_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode()); } }