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:rapture.kernel.Login.java
/** * Given a username, validate the user exists, create a context for this user * * @param user//from www . j a v a 2 s . co m * @return * @throws Exception */ public ContextResponseData getContextForUser(String user) { long functionStartTime = System.currentTimeMillis(); log.info("Checking user " + user + " exists."); RaptureUser usr = Kernel.getAdmin().getUser(ContextFactory.getKernelUser(), user); if (usr != null) { log.info("Found user " + usr.getUsername()); } else { throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, String.format("No such user: '%s'", user)); } String contextId = IDGenerator.getUUID(); log.info("Context id is " + contextId); ContextResponseData resp = new ContextResponseData(); resp.setContextId(contextId); resp.setSalt(IDGenerator.getUUID()); CallingContext logContext = new CallingContext(); logContext.setContext(contextId); logContext.setSalt(resp.getSalt()); logContext.setUser(user); getEphemeralRepo().addToStage(RaptureConstants.OFFICIAL_STAGE, "session/" + contextId, JacksonUtil.jsonFromObject(logContext), false); getEphemeralRepo().commitStage(RaptureConstants.OFFICIAL_STAGE, "admin", "session creation"); long endFunctionTime = System.currentTimeMillis(); Kernel.getMetricsService().recordTimeDifference( "apiMetrics.loginApi.getContextForUser.fullFunctionTime.succeeded", (endFunctionTime - functionStartTime)); return resp; }
From source file:me.philio.ghost.sync.SyncAdapter.java
/** * Access tokens only last 60 minutes so we need to manage this and refresh it frequently. If * token has less than 30 minutes remaining it will be refreshed and as a last resort we can * use the email/password combination that was saved on login to re-authenticate from scratch. * * TODO Review later//from ww w. j a va 2s .c o m */ private void refreshAccessToken(Account account) throws AuthenticatorException, OperationCanceledException, IOException, RetrofitError { // Check expiry first Long expiry = Long .parseLong(mAccountManager.getUserData(account, AccountConstants.KEY_ACCESS_TOKEN_EXPIRES)); if (System.currentTimeMillis() + (30 * 60 * 1000) < expiry) { Log.d(TAG, "Access token has more than 30 minutes remaining, won't refresh"); return; } // Get blog url and refresh token String blogUrl = mAccountManager.getUserData(account, AccountConstants.KEY_BLOG_URL); String refreshToken = mAccountManager.blockingGetAuthToken(account, TOKEN_TYPE_REFRESH, false); // Get authentication client GhostClient client = new GhostClient(blogUrl); Authentication authentication = client.createAuthentication(); try { // Request a new access token Token token = authentication.blockingGetAccessToken(GRANT_TYPE_REFRESH_TOKEN, CLIENT_ID, refreshToken); // Save new access token mAccountManager.setAuthToken(account, TOKEN_TYPE_ACCESS, token.accessToken); mAccountManager.setUserData(account, KEY_ACCESS_TOKEN_EXPIRES, Long.toString(System.currentTimeMillis() + (token.expires * 1000))); } catch (RetrofitError e) { // Check for a 401/403 as we can try and re-authenticate with an email/password if (e.getResponse() != null && (e.getResponse().getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED || e.getResponse().getStatus() == HttpURLConnection.HTTP_FORBIDDEN)) { String email = mAccountManager.getUserData(account, AccountConstants.KEY_EMAIL); String password = mAccountManager.getPassword(account); Token token = authentication.blockingGetAccessToken(GRANT_TYPE_PASSWORD, CLIENT_ID, email, password); // Save new tokens mAccountManager.setAuthToken(account, TOKEN_TYPE_ACCESS, token.accessToken); mAccountManager.setAuthToken(account, TOKEN_TYPE_REFRESH, token.refreshToken); mAccountManager.setUserData(account, KEY_ACCESS_TOKEN_EXPIRES, Long.toString(System.currentTimeMillis() + (token.expires * 1000))); } else { // Rethrow the exception if something else went wrong throw e; } } }
From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java
/** * Get action data from database//ww w . j av a 2s . c o m * @param appId applicationId * @return HttpResponse Returned as JSON object */ @GET @Path("/actions/{appId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Fetch the actions"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) public HttpResponse getActions(@ApiParam(value = "Application ID") @PathParam("appId") String appId) { JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } String memberId = name; // try { // if(!initializeDBConnection()){ // logger.info("Cannot connect to database >> "); // objResponse.put("message", "Cannot connect to database"); // L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); // return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); // } // RMI call with parameters try { Object result = this.invokeServiceMethod( "i5.las2peer.services.gamificationActionService.GamificationActionService@0.1", "getActionsRMI", new Serializable[] { appId }); if (result != null) { L2pLogger.logEvent(Event.RMI_SUCCESSFUL, "Get Actions RMI success"); return new HttpResponse((String) result, HttpURLConnection.HTTP_OK); } L2pLogger.logEvent(Event.RMI_FAILED, "Get Actions RMI failed"); objResponse.put("message", "Cannot find actions"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException | TimeoutException e) { e.printStackTrace(); L2pLogger.logEvent(Event.RMI_FAILED, "Get Actions RMI failed. " + e.getMessage()); objResponse.put("message", "Cannot find Actions. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } // } catch (SQLException e) { // e.printStackTrace(); // objResponse.put("message", "DB Error. " + e.getMessage()); // L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); // return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); // // } }
From source file:me.philio.ghost.ui.LoginUrlFragment.java
@Override public void failure(RetrofitError error) { int status = 0; if (error.getResponse() != null) { status = error.getResponse().getStatus(); }/* ww w. j av a 2s .com*/ switch (status) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: // Got a redirect Log.d(TAG, "Url is a redirect!"); // Get the redirect url and examine to attempt to provide most // useful error message String redirectUrl = null; for (Header header : error.getResponse().getHeaders()) { if (header.getName() == null) { continue; } if (header.getName().equals("Location")) { String value = header.getValue(); if (value.endsWith("/ghost/api/v0.1/")) { redirectUrl = value.substring(0, value.length() - 16); } else { redirectUrl = value; } } } if (redirectUrl != null) { mEditUrl.setError(getString(R.string.error_redirect_url_to, redirectUrl)); } else { mEditUrl.setError(getString(R.string.error_redirect_url)); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: // Got a 401 so could be a blog, check that the response is JSON Object body = error.getBodyAs(JsonObject.class); if (body != null && body instanceof JsonObject) { Log.d(TAG, "Url looks good!"); mListener.onValidUrl(mBlogUrl); } else { mEditUrl.setError(getString(R.string.error_invalid_url)); } break; default: mEditUrl.setError(getString(R.string.error_invalid_url)); break; } mBtnValidate.setEnabled(true); ((LoginActivity) getActivity()).setToolbarProgressBarVisibility(false); }
From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java
@Test public void testUnauthorizedClientsDisallowed() throws IOException { URL url = new URL(getServerURL(server), "/echo?a=b"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); }
From source file:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java
/** * @param uri/*from ww w . j a va 2s . c om*/ * @param parameters * @return */ public boolean fetchPageContent(String uri, List<NameValuePair> parameters) { // Set login, ssl, port, host etc; applyConfig(); mErrorText = ""; mErrorTextId = -1; mError = false; mBytes = new byte[0]; if (!uri.startsWith("/")) { uri = "/".concat(uri); } HttpURLConnection conn = null; try { if (mProfile.getSessionId() != null) parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId())); URL url = new URL(buildUrl(uri, parameters)); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(mConnectionTimeoutMillis); if (DreamDroid.featurePostRequest()) conn.setRequestMethod("POST"); setAuth(conn); if (conn.getResponseCode() != 200) { if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) { // Method not allowed, the target device either can't handle // POST or GET requests (old device or Anti-Hijack enabled) DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest()); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD; return fetchPageContent(uri, parameters); } if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) { createSession(); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED; return fetchPageContent(uri, parameters); } mRememberedReturnCode = 0; Log.e(LOG_TAG, Integer.toString(conn.getResponseCode())); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_UNAUTHORIZED: mErrorTextId = R.string.auth_error; break; default: mErrorTextId = -1; } mErrorText = conn.getResponseMessage(); mError = true; return false; } BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; int bufSize = 512; byte[] buffer = new byte[bufSize]; while ((read = bis.read(buffer)) != -1) { baf.append(buffer, 0, read); } mBytes = baf.toByteArray(); if (DreamDroid.dumpXml()) dumpToFile(url); return true; } catch (MalformedURLException e) { mError = true; mErrorTextId = R.string.illegal_host; } catch (UnknownHostException e) { mError = true; mErrorText = null; mErrorTextId = R.string.host_not_found; } catch (ProtocolException e) { mError = true; mErrorText = e.getLocalizedMessage(); } catch (ConnectException e) { mError = true; mErrorTextId = R.string.host_unreach; } catch (IOException e) { e.printStackTrace(); mError = true; mErrorText = e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); if (mError) if (mErrorText == null) mErrorText = "Error text is null"; Log.e(LOG_TAG, mErrorText); } return false; }
From source file:i5.las2peer.services.servicePackage.TemplateService.java
/** * Example method that shows how to retrieve a user email address from a database * and return an HTTP response including a JSON object. * /*from w ww .j a va2 s . c om*/ * WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! * IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE. * */ @GET @Path("/userEmail/{username}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "User Email"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "User not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Server Error") }) @ApiOperation(value = "Email Address Administration", notes = "Example method that retrieves a user email address from a database." + " WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! " + "IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.") public HttpResponse getUserEmail(@PathParam("username") String username) { String result = ""; Connection conn = null; PreparedStatement stmnt = null; ResultSet rs = null; try { // get connection from connection pool conn = dbm.getConnection(); // prepare statement stmnt = conn.prepareStatement("SELECT email FROM users WHERE username = ?;"); stmnt.setString(1, username); // retrieve result set rs = stmnt.executeQuery(); // process result set if (rs.next()) { result = rs.getString(1); // setup resulting JSON Object JSONObject ro = new JSONObject(); ro.put("email", result); // return HTTP Response on success return new HttpResponse(ro.toString(), HttpURLConnection.HTTP_OK); } else { result = "No result for username " + username; // return HTTP Response on error return new HttpResponse(result, HttpURLConnection.HTTP_NOT_FOUND); } } catch (Exception e) { // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } finally { // free resources if (rs != null) { try { rs.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } if (stmnt != null) { try { stmnt.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } if (conn != null) { try { conn.close(); } catch (Exception e) { Context.logError(this, e.getMessage()); // return HTTP Response on error return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } } }
From source file:com.aitangba.volley.BasicNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { long requestStart = SystemClock.elapsedRealtime(); while (true) { HttpResponse httpResponse = null; byte[] responseContents = null; Map<String, String> responseHeaders = Collections.emptyMap(); try {/*from www.j a va 2s . c o m*/ // Gather headers. Map<String, String> headers = new HashMap<String, String>(); addCacheHeaders(headers, request.getCacheEntry()); httpResponse = mHttpStack.performRequest(request, headers); int statusCode = httpResponse.getStatusCode(); responseHeaders = convertHeaders(httpResponse.getAllHeaders()); // Handle cache validation. if (statusCode == HttpURLConnection.HTTP_NOT_MODIFIED) { Cache.Entry entry = request.getCacheEntry(); if (entry == null) { return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, null, responseHeaders, true, SystemClock.elapsedRealtime() - requestStart); } // A HTTP 304 response does not have all header fields. We // have to use the header fields from the cache entry plus // the new ones from the response. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5 entry.responseHeaders.putAll(responseHeaders); return new NetworkResponse(HttpURLConnection.HTTP_NOT_MODIFIED, entry.data, entry.responseHeaders, true, SystemClock.elapsedRealtime() - requestStart); } // Handle moved resources if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { String newUrl = responseHeaders.get("Location"); request.setRedirectUrl(newUrl); } // Some responses such as 204s do not have content. We must check. if (httpResponse.getEntity() != null) { responseContents = entityToBytes(httpResponse.getEntity()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. responseContents = new byte[0]; } // if the request is slow, log it. long requestLifetime = SystemClock.elapsedRealtime() - requestStart; logSlowRequests(requestLifetime, request, responseContents, httpResponse.getStatusCode()); if (statusCode < 200 || statusCode > 299) { throw new IOException(); } return new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); } catch (SocketTimeoutException e) { attemptRetryOnException("socket", request, new TimeoutError()); } catch (ConnectTimeoutException e) { attemptRetryOnException("connection", request, new TimeoutError()); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { int statusCode = 0; NetworkResponse networkResponse = null; if (httpResponse != null) { statusCode = httpResponse.getStatusCode(); } else { throw new NoConnectionError(e); } if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { VolleyLog.e("Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl()); } else { VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl()); } if (responseContents != null) { networkResponse = new NetworkResponse(statusCode, responseContents, responseHeaders, false, SystemClock.elapsedRealtime() - requestStart); if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED || statusCode == HttpURLConnection.HTTP_FORBIDDEN) { attemptRetryOnException("auth", request, new AuthFailureError(networkResponse)); } else if (statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_MOVED_TEMP) { attemptRetryOnException("redirect", request, new RedirectError(networkResponse)); } else { // TODO: Only throw ServerError for 5xx status codes. throw new ServerError(networkResponse); } } else { throw new NetworkError(e); } } } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
public void pullFile(String sessionId, String space, String path, String outputPath) throws Exception { String uriTmpl = (new StringBuilder(restEndpointURL)).append(addSlashIfMissing(restEndpointURL)) .append("scheduler/dataspace/").append(space).append(URLEncoder.encode(path, "UTF-8")).toString(); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();/*from ww w. j a v a2 s . c o m*/ ResteasyWebTarget target = client.target(uriTmpl); Response response = target.request().header("sessionid", sessionId).get(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot retrieve the file. Status code: %s", response.getStatus()), response); } } try { File file = new File(outputPath); if (response.hasEntity()) { copyInputStreamToFile(response.readEntity(InputStream.class), file); } else { // creates an empty file file.createNewFile(); } } catch (Exception e) { throw e; } finally { if (response != null) { response.close(); } if (!client.isClosed()) { client.close(); } } }
From source file:org.apache.hadoop.mapred.TestWebUIAuthorization.java
/** * Validates the given jsp/servlet against different user names who * can(or cannot) view the job./*from w w w .j av a 2 s . c om*/ * (1) jobSubmitter can view the job * (2) mrAdmin can view any job * (3) mrOwner can view any job * (4) qAdmins of the queue to which job is submitted to can view any job in * that queue. * (5) user mentioned in job-view-acl should be able to view the * job irrespective of job-modify-acl. * (6) user mentioned in job-modify-acl but not in job-view-acl * cannot view the job * (7) other unauthorized users cannot view the job */ private void validateViewJob(String url, String method) throws IOException { assertEquals("Incorrect return code for job submitter " + jobSubmitter, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, jobSubmitter, method)); assertEquals("Incorrect return code for admin user " + mrAdminUser, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, mrAdminUser, method)); assertEquals("Incorrect return code for admingroup-member " + mrAdminGroupMember, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, mrAdminGroupMember, method)); assertEquals("Incorrect return code for MR-owner " + mrOwner, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, mrOwner, method)); assertEquals("Incorrect return code for queue admin " + qAdmin, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, qAdmin, method)); assertEquals("Incorrect return code for user in job-view-acl " + viewColleague, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, viewColleague, method)); assertEquals( "Incorrect return code for user in job-view-acl and " + "job-modify-acl " + viewAndModifyColleague, HttpURLConnection.HTTP_OK, getHttpStatusCode(url, viewAndModifyColleague, method)); assertEquals("Incorrect return code for user in job-modify-acl " + modifyColleague, HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, modifyColleague, method)); assertEquals("Incorrect return code for unauthorizedUser " + unauthorizedUser, HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(url, unauthorizedUser, method)); }