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:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from//from w w w .ja va 2s . c o m * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:ste.xtest.net.BugFreeStubURLConnection.java
@Test public void set_status() throws Exception { then(C.status(HttpURLConnection.HTTP_ACCEPTED)).isSameAs(C); then(C.getStatus()).isEqualTo(HttpURLConnection.HTTP_ACCEPTED); then(C.status(HttpURLConnection.HTTP_FORBIDDEN)).isSameAs(C); then(C.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN); }
From source file:org.jboss.test.web.security.AuthenticatorsExternalizationTestCase.java
/** * Test custom header based authentication * // w w w. j a v a 2 s. c o m * @throws Exception */ public void testHeaderBasedAuthentication() throws Exception { String location = baseURLNoAuth + "header-auth/index.jsp"; int responseCode = 0; HttpClient httpConn = new HttpClient(); GetMethod indexGet = null; try { indexGet = new GetMethod(location); indexGet.setFollowRedirects(false); responseCode = httpConn.executeMethod(indexGet); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, responseCode); } finally { indexGet.releaseConnection(); } indexGet = null; try { indexGet = new GetMethod(location); indexGet.setFollowRedirects(false); //Add the request headers indexGet.addRequestHeader("JBOSS_TEST_USER_NAME", "jduke"); indexGet.addRequestHeader("JBOSS_TEST_CREDENTIAL", "theduke"); responseCode = httpConn.executeMethod(indexGet); assertEquals(HttpURLConnection.HTTP_OK, responseCode); } finally { indexGet.releaseConnection(); } }
From source file:msearch.filmeSuchen.sender.MediathekSrf.java
public static boolean ping(String url) throws SRFException { url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates. try {// w w w . j a v a 2s .c o m HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity connection.setReadTimeout(0); int responseCode = connection.getResponseCode(); connection.disconnect(); if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { throw new SRFException("TEST"); } //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url); return false; } return (200 <= responseCode && responseCode <= 399); } catch (IOException exception) { return false; } }
From source file:eu.dime.userresolver.service.basicauth.BasicAuthenticationInterceptor.java
/** * org.apache.cxf.message.Message.PROTOCOL_HEADERS -- * {Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp, *;q=0.8], * accept-encoding=[gzip,deflate,sdch], * accept-language=[de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4], * Authorization=[Basic Og==], //from w w w . j av a2 s. c om * cache-control=[max-age=0], * connection=[keep-alive], * Content-Type=[null], * dnt=[1], * host=[141.99.159.223], * user-agent=[...]} */ @Override public void handleMessage(Message message) throws Fault { AuthorizationPolicy policy = message.get(AuthorizationPolicy.class); Set<Entry<String, Object>> set = message.entrySet(); if (policy == null) { sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED); return; } String address; if (message != null && message.get(Message.ENDPOINT_ADDRESS) != null) { address = message.get(Message.ENDPOINT_ADDRESS).toString(); } else { address = ""; } if (!address.endsWith("register")) { User user = userProvider.getBySaid(policy.getUserName()); String key = DigestUtils.sha256Hex(policy.getPassword()); if (!user.getKey().equals(key)) { log.warn("Invalid username or password for user: " + policy.getUserName()); sendErrorResponse(message, HttpURLConnection.HTTP_FORBIDDEN); return; } } }
From source file:no.uis.fsws.proxy.ProxySoapHeaderInterceptor.java
@Override public void handleMessage(Message message) { AuthorizationPolicy policy = message.get(AuthorizationPolicy.class); // If the policy is not set, the user did not specify credentials // A 401 is sent to the client to indicate that authentication is required if (policy == null) { log.warn("User attempted to log in with no credentials"); sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED); return;/* w ww . j a v a 2 s.com*/ } if (log.isInfoEnabled()) { log.info("Logged in user: " + policy.getUserName()); } boolean authorized = false; ProxyPrincipal principal = authorizer.authenticate(policy.getUserName(), policy.getPassword()); if (principal != null) { if (authorizer.hasAuthorization(principal, policy.getAuthorizationType(), policy.getAuthorization())) { message.setContextualProperty(AbstractFswsProxy.PRINCIPAL, principal); authorized = true; } } if (!authorized) { if (log.isEnabledFor(Level.WARN)) { log.warn("User not authorized: " + policy.getUserName()); } sendErrorResponse(message, HttpURLConnection.HTTP_FORBIDDEN); } }
From source file:org.apache.geronimo.testsuite.servlets.ServletsTest.java
/** * Test4/*from w w w . j ava2s. c o m*/ */ @Test public void test_SampleServlet2_GET_RoleB_Fail() throws Exception { Assert.assertEquals(invoke("/SampleServlet2", "GET", "george", "bone"), HttpURLConnection.HTTP_FORBIDDEN); }
From source file:play.modules.resteasy.crud.RESTResource.java
/** * Throws a FORBIDDEN exception if the user doesn't have the given permission * @param target the object we want a permission for, can be a Class if this is a general permission * @param name the name of the permission *//*from w ww . ja va2 s . c o m*/ protected void checkPermission(Object target, String name) { if (!hasPermission(target, name)) throw new WebApplicationException(HttpURLConnection.HTTP_FORBIDDEN); }
From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java
@Test public void testGetUsersForbidden() throws IOException, SAXException { WebConversation webConversation = new WebConversation(); webConversation.setExceptionsThrownOnErrorStatus(false); WebRequest request = getGetUsersRequest("", false); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getResponseCode()); boolean wasJson = true; try {/*from w w w .j av a 2s . c o m*/ new JSONObject(response.getText()); } catch (JSONException e) { wasJson = false; } assertFalse("Returned a jsonObject in reponse where FORBIDDEN should be returned", wasJson); }
From source file:eionet.cr.web.action.PingActionBean.java
/** * The default handler of this API's calls. * * @return//from w w w. j a va 2 s. c o m */ @DefaultHandler public Resolution defaultHandler() { // Get client host/IP, ensure that it's in the whitelist. HttpServletRequest request = getContext().getRequest(); String ip = request.getRemoteAddr(); String host = processClientHostName(request.getRemoteHost(), ip); if (!isTrustedRequester(host, ip)) { LOGGER.debug("Client denied: host = " + host + ", IP = " + ip); return new ErrorResolution(HttpURLConnection.HTTP_FORBIDDEN); } // The default result-message and error code that will be printed into XML response. int errorCode = 0; String message = ""; try { // Ensure that the pinged URI is not blank, is legal URI, does not have a fragment part and is not broken. if (StringUtils.isBlank(uri)) { errorCode = ERR_BLANK_URI; message = "No URI given, no action taken."; } else if (!URLUtil.isURL(uri)) { if (create) { errorCode = ERR_INVALID_URL; message = "Not a valid URL, source cannot be created."; } else { message = "URL not in catalogue of sources, no action taken."; } } else if (create && new URL(uri).getRef() != null) { errorCode = ERR_FRAGMENT_URL; message = "URL with a fragment part not allowed, source cannot be created."; } else if (create && URLUtil.isNotExisting(uri)) { errorCode = ERR_BROKEN_URL; message = "Could not make a connection to this URL, source cannot be created."; } else { // Helper flag that will be raised if a harvest is indeed needed. boolean doHarvest = false; // Check if a graph by this URI exists. boolean exists = DAOFactory.get().getDao(HelperDAO.class).isGraphExists(uri); if (exists) { doHarvest = true; } else if (create) { // Graph does not exist, but must be created as indicated in request parameters HarvestSourceDTO source = new HarvestSourceDTO(); source.setUrl(uri); source.setIntervalMinutes( GeneralConfig.getIntProperty(GeneralConfig.HARVESTER_REFERRALS_INTERVAL, 60480)); DAOFactory.get().getDao(HarvestSourceDAO.class).addSource(source); doHarvest = true; } else { message = "URL not in catalogue of sources, no action taken."; } if (doHarvest) { UrgentHarvestQueue.addPullHarvest(uri); message = "URL added to the urgent harvest queue: " + uri; } } } catch (Exception e) { LOGGER.error("PING request failed: " + e.toString(), e); return new ErrorResolution(HttpURLConnection.HTTP_INTERNAL_ERROR); } LOGGER.debug(message); String response = RESPONSE_XML.replace("@message@", message); response = response.replace("@errorCode@", String.valueOf(errorCode)); return new StreamingResolution("text/xml", response); }