List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN
int HTTP_FORBIDDEN
To view the source code for java.net HttpURLConnection HTTP_FORBIDDEN.
Click Source Link
From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java
@Test public void testUpdateUsers() throws IOException, SAXException, JSONException, URISyntaxException { WebConversation webConversation = new WebConversation(); webConversation.setExceptionsThrownOnErrorStatus(false); // create user Map<String, String> params = new HashMap<String, String>(); params.put("login", "user" + System.currentTimeMillis()); params.put("Name", "username_" + System.currentTimeMillis()); // params.put("email", "test@test_" + System.currentTimeMillis()); // params.put("workspace", "workspace_" + System.currentTimeMillis()); params.put("roles", "admin"); String oldPass = "pass_" + System.currentTimeMillis(); params.put("password", oldPass); WebRequest request = getPostUsersRequest("", params, true); WebResponse response = webConversation.getResponse(request); assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject responseObject = new JSONObject(response.getText()); assertTrue("Response should contian user location", responseObject.has(ProtocolConstants.KEY_LOCATION)); String location = responseObject.getString(ProtocolConstants.KEY_LOCATION); // update user JSONObject updateBody = new JSONObject(); updateBody.put("Name", "usernameUpdate_" + System.currentTimeMillis()); updateBody.put("oldPassword", oldPass); updateBody.put("password", "passUpdate_" + System.currentTimeMillis()); updateBody.put("roles", ""); request = getAuthenticatedRequest(location, METHOD_PUT, true, null, updateBody); response = webConversation.getResponse(request); assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode()); // check user details request = getAuthenticatedRequest(location, METHOD_GET, true); response = webConversation.getResponse(request); assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode()); responseObject = new JSONObject(response.getText()); assertEquals("Invalid user login", params.get("login"), responseObject.getString("login")); assertEquals("Invalid user name", updateBody.getString("Name"), responseObject.getString("Name")); // assertEquals("Invalid user email", updatedParams.get("email"), responseObject.getString("email")); // assertEquals("Invalid user workspace", updatedParams.get("workspace"), responseObject.getString("workspace")); // JSONArray roles = responseObject.getJSONArray("roles"); // assertEquals("Invalid number of user roles", 0, roles.length()); assertFalse("Response shouldn't contain password", responseObject.has("password")); // check if user can authenticate and does not have admin role request = getGetUsersRequest("", true); setAuthentication(request, params.get("login"), updateBody.getString("password")); response = webConversation.getResponse(request); assertEquals("User with no roles has admin privilegges", HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode()); // delete user request = getAuthenticatedRequest(location, METHOD_DELETE, true); response = webConversation.getResponse(request); assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode()); }
From source file:org.projectbuendia.client.ui.OdkActivityLauncher.java
private static void handleFetchError(VolleyError error) { FetchXformFailedEvent.Reason reason = FetchXformFailedEvent.Reason.SERVER_UNKNOWN; if (error.networkResponse != null) { switch (error.networkResponse.statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: case HttpURLConnection.HTTP_UNAUTHORIZED: reason = FetchXformFailedEvent.Reason.SERVER_AUTH; break; case HttpURLConnection.HTTP_NOT_FOUND: reason = FetchXformFailedEvent.Reason.SERVER_BAD_ENDPOINT; break; case HttpURLConnection.HTTP_INTERNAL_ERROR: default:// w ww . j a v a 2 s . co m reason = FetchXformFailedEvent.Reason.SERVER_UNKNOWN; } } EventBus.getDefault().post(new FetchXformFailedEvent(reason, error)); }
From source file:org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter.java
private void doUploadMessage(final RoutingContext ctx, final String tenant, final String deviceId, final Buffer payload, final String contentType, final Future<MessageSender> senderTracker, final String endpointName) { if (!isPayloadOfIndicatedType(payload, contentType)) { HttpUtils.badRequest(ctx,//w w w. jav a 2s .c om String.format("Content-Type %s does not match with the payload", contentType)); } else { final Integer qosHeader = getQoSLevel(ctx.request().getHeader(Constants.HEADER_QOS_LEVEL)); if (contentType == null) { HttpUtils.badRequest(ctx, String.format("%s header is missing", HttpHeaders.CONTENT_TYPE)); } else if (qosHeader != null && qosHeader == HEADER_QOS_INVALID) { HttpUtils.badRequest(ctx, "Bad QoS Header Value"); } else { final Device authenticatedDevice = getAuthenticatedDevice(ctx); final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice); final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant); // AtomicBoolean to control if the downstream message was sent successfully final AtomicBoolean downstreamMessageSent = new AtomicBoolean(false); // AtomicReference to a Handler to be called to close an open command receiver link. final AtomicReference<Handler<Void>> closeLinkAndTimerHandlerRef = new AtomicReference<>(); // Handler to be called with a received command. If the timer expired, null is provided as command. final Handler<Message> commandReceivedHandler = commandMessage -> { // reset the closeHandler reference, since it is not valid anymore at this time. closeLinkAndTimerHandlerRef.set(null); if (downstreamMessageSent.get()) { // finish the request, since the response is now complete (command was added) if (!ctx.response().closed()) { ctx.response().end(); } } }; CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> { if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) { final MessageSender sender = senderTracker.result(); final Message downstreamMessage = newMessage( ResourceIdentifier.from(endpointName, tenant, deviceId), sender.isRegistrationAssertionRequired(), ctx.request().uri(), contentType, payload, tokenTracker.result(), HttpUtils.getTimeTilDisconnect(ctx)); customizeDownstreamMessage(downstreamMessage, ctx); // first open the command receiver link (if needed) return openCommandReceiverLink(ctx, tenant, deviceId, commandReceivedHandler) .compose(closeLinkAndTimerHandler -> { closeLinkAndTimerHandlerRef.set(closeLinkAndTimerHandler); if (qosHeader == null) { return sender.send(downstreamMessage); } else { return sender.sendAndWaitForOutcome(downstreamMessage); } }); } else { // this adapter is not enabled for the tenant return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN)); } }).compose(delivery -> { LOG.trace( "successfully processed message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName); metrics.incrementProcessedHttpMessages(endpointName, tenant); ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED); downstreamMessageSent.set(true); // if no command timer was created, the request now can be responded if (closeLinkAndTimerHandlerRef.get() == null) { ctx.response().end(); } return Future.succeededFuture(); }).recover(t -> { LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName, t); cancelResponseTimer(closeLinkAndTimerHandlerRef); if (ClientErrorException.class.isInstance(t)) { final ClientErrorException e = (ClientErrorException) t; ctx.fail(e.getErrorCode()); } else { metrics.incrementUndeliverableHttpMessages(endpointName, tenant); HttpUtils.serviceUnavailable(ctx, 2); } return Future.failedFuture(t); }); } } }
From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java
private GetMethod connectInternal(String serverURL) throws MarshalException, ValidationException, HttpException, FogBugzClientException, IOException { WebClientUtil.setupHttpClient(httpClient, proxy, serverURL, null, null); for (int attempt = 0; attempt < 2; attempt++) { // force authentication if (!authenticated && hasAuthenticationCredentials()) { authenticate();/*from w w w. j a va2 s.co m*/ } String requestUrl = WebClientUtil.getRequestPath(serverURL + "&token=" + token); GetMethod method = new GetMethod(requestUrl); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); int code; try { code = httpClient.executeMethod(method); } catch (IOException e) { method.releaseConnection(); e.printStackTrace(); throw e; } if (code == HttpURLConnection.HTTP_OK) { return method; } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { // login or re-authenticate due to an expired session method.releaseConnection(); authenticated = false; authenticate(); } else { throw new FogBugzClientException("code = " + code); } } throw new FogBugzClientException("Session might have expired!"); }
From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java
@Override public void removeAll(final String tenantId, final String deviceId, final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) { Objects.requireNonNull(tenantId); Objects.requireNonNull(deviceId); Objects.requireNonNull(resultHandler); if (getConfig().isModificationEnabled()) { final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId); if (credentialsForTenant == null) { resultHandler//from www . j ava2s . c o m .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND))); } else { boolean removedAnyElement = false; // delete based on type (no authId provided) - this might consume more time on large data sets and is thus // handled explicitly for (final JsonArray credentialsForAuthId : credentialsForTenant.values()) { if (removeCredentialsFromCredentialsArray(deviceId, CredentialsConstants.SPECIFIER_WILDCARD, credentialsForAuthId)) { removedAnyElement = true; } } // there might be empty credentials arrays left now, so remove them in a second run cleanupEmptyCredentialsArrays(credentialsForTenant); if (removedAnyElement) { dirty = true; resultHandler.handle( Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NO_CONTENT))); } else { resultHandler.handle( Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND))); } } } else { resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_FORBIDDEN))); } }
From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private <T> T call(HttpURLConnection conn, Map jsonOutput, int expectedResponse, Class<T> klass, int authRetryCount) throws IOException { T ret = null;/* w w w . j ava2 s . c om*/ try { if (jsonOutput != null) { writeJson(jsonOutput, conn.getOutputStream()); } } catch (IOException ex) { IOUtils.closeStream(conn.getInputStream()); throw ex; } if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN && (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) || conn.getResponseMessage().contains(INVALID_SIGNATURE))) || conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { // Ideally, this should happen only when there is an Authentication // failure. Unfortunately, the AuthenticationFilter returns 403 when it // cannot authenticate (Since a 401 requires Server to send // WWW-Authenticate header as well).. KMSClientProvider.this.authToken = new DelegationTokenAuthenticatedURL.Token(); if (authRetryCount > 0) { String contentType = conn.getRequestProperty(CONTENT_TYPE); String requestMethod = conn.getRequestMethod(); URL url = conn.getURL(); conn = createConnection(url, requestMethod); conn.setRequestProperty(CONTENT_TYPE, contentType); return call(conn, jsonOutput, expectedResponse, klass, authRetryCount - 1); } } try { AuthenticatedURL.extractToken(conn, authToken); } catch (AuthenticationException e) { // Ignore the AuthExceptions.. since we are just using the method to // extract and set the authToken.. (Workaround till we actually fix // AuthenticatedURL properly to set authToken post initialization) } HttpExceptionUtils.validateResponse(conn, expectedResponse); if (conn.getContentType() != null && conn.getContentType().trim().toLowerCase().startsWith(APPLICATION_JSON_MIME) && klass != null) { ObjectMapper mapper = new ObjectMapper(); InputStream is = null; try { is = conn.getInputStream(); ret = mapper.readValue(is, klass); } finally { IOUtils.closeStream(is); } } return ret; }
From source file:org.kohsuke.github.Requester.java
/** * Handle API error by either throwing it or by returning normally to retry. *///from www . ja v a 2 s.c o m /*package*/ void handleApiError(IOException e) throws IOException { int responseCode; try { responseCode = uc.getResponseCode(); } catch (IOException e2) { // likely to be a network exception (e.g. SSLHandshakeException), // uc.getResponseCode() and any other getter on the response will cause an exception if (LOGGER.isLoggable(FINE)) LOGGER.log(FINE, "Silently ignore exception retrieving response code for '" + uc.getURL() + "'" + " handling exception " + e, e); throw e; } InputStream es = wrapStream(uc.getErrorStream()); if (es != null) { try { String error = IOUtils.toString(es, "UTF-8"); if (e instanceof FileNotFoundException) { // pass through 404 Not Found to allow the caller to handle it intelligently e = (IOException) new FileNotFoundException(error).initCause(e); } else if (e instanceof HttpException) { HttpException http = (HttpException) e; e = new HttpException(error, http.getResponseCode(), http.getResponseMessage(), http.getUrl(), e); } else { e = (IOException) new IOException(error).initCause(e); } } finally { IOUtils.closeQuietly(es); } } if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) // 401 / Unauthorized == bad creds throw e; if ("0".equals(uc.getHeaderField("X-RateLimit-Remaining"))) { root.rateLimitHandler.onError(e, uc); return; } // Retry-After is not documented but apparently that field exists if (responseCode == HttpURLConnection.HTTP_FORBIDDEN && uc.getHeaderField("Retry-After") != null) { this.root.abuseLimitHandler.onError(e, uc); return; } throw e; }
From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java
private Future<Void> uploadMessage(final MqttContext ctx, final String tenant, final String deviceId, final Buffer payload, final Future<MessageSender> senderTracker, final String endpointName) { if (!isPayloadOfIndicatedType(payload, ctx.contentType())) { return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, String.format("Content-Type %s does not match with the payload", ctx.contentType()))); } else {/*from ww w .j av a 2 s . co m*/ final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId, ctx.authenticatedDevice()); final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant); return CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> { if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) { final MessageSender sender = senderTracker.result(); final Message downstreamMessage = newMessage( ResourceIdentifier.from(endpointName, tenant, deviceId), sender.isRegistrationAssertionRequired(), ctx.message().topicName(), ctx.contentType(), payload, tokenTracker.result(), null); customizeDownstreamMessage(downstreamMessage, ctx); if (ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) { return sender.sendAndWaitForOutcome(downstreamMessage); } else { return sender.send(downstreamMessage); } } else { // this adapter is not enabled for the tenant return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN)); } }).compose(delivery -> { LOG.trace( "successfully processed message [topic: {}, QoS: {}] for device [tenantId: {}, deviceId: {}]", ctx.message().topicName(), ctx.message().qosLevel(), tenant, deviceId); metrics.incrementProcessedMqttMessages(endpointName, tenant); onMessageSent(ctx); // check that the remote MQTT client is still connected before sending PUBACK if (ctx.deviceEndpoint().isConnected() && ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) { ctx.deviceEndpoint().publishAcknowledge(ctx.message().messageId()); } return Future.<Void>succeededFuture(); }).recover(t -> { if (ClientErrorException.class.isInstance(t)) { final ClientErrorException e = (ClientErrorException) t; LOG.debug( "cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]: {} - {}", tenant, deviceId, endpointName, e.getErrorCode(), e.getMessage()); } else { LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]", tenant, deviceId, endpointName, t); metrics.incrementUndeliverableMqttMessages(endpointName, tenant); onMessageUndeliverable(ctx); } return Future.failedFuture(t); }); } }
From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java
private GetMethod connectInternal(String serverURL, IProgressMonitor monitor) throws MarshalException, ValidationException, HttpException, FogBugzClientException, IOException { WebClientUtil.setupHttpClient(httpClient, proxy, serverURL, null, null); for (int attempt = 0; attempt < 2; attempt++) { // force authentication if (!authenticated && hasAuthenticationCredentials()) { monitor.subTask("Authenticating request"); authenticate();/*from ww w . j a va 2s.c o m*/ if (checkMonitor(monitor)) return null; } String requestUrl = WebClientUtil.getRequestPath(serverURL + "&token=" + token); GetMethod method = new GetMethod(requestUrl); method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); int code; try { monitor.subTask("Sending request"); code = httpClient.executeMethod(method); if (checkMonitor(monitor)) return null; } catch (IOException e) { method.releaseConnection(); e.printStackTrace(); throw e; } if (code == HttpURLConnection.HTTP_OK) { return method; } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) { // login or re-authenticate due to an expired session method.releaseConnection(); authenticated = false; authenticate(); } else { throw new FogBugzClientException("code = " + code); } } throw new FogBugzClientException("Session might have expired!"); }