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.leafhut.open_source.VerifyReceipt.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { // Set up logger LoggerService logger = serviceProvider.getLoggerService(VerifyReceipt.class); String startMessage = "Processing receipt..."; logger.info(startMessage);/*www .j av a 2 s . com*/ HttpService http; try { http = serviceProvider.getHttpService(); } catch (ServiceNotActivatedException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); logger.error(exceptionLogMessage); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } if (http == null) { String failureReason = "HTTP Service is null."; logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } // Fetch parameters sent via POST String encodedReceipt = null; try { JSONObject jsonObj = new JSONObject(request.getBody()); if (!jsonObj.isNull(kReceiptParameter)) { encodedReceipt = jsonObj.getString(kReceiptParameter); } } catch (JSONException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "Invalid or missing parameter."; logger.error(exceptionLogMessage); logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } // Create JSON representation of receipt JSONObject validationBodyJSON = new JSONObject(); try { validationBodyJSON.put(kReceiptValidationKey, encodedReceipt); } catch (JSONException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "Could not create JSON for receipt validation server."; logger.error(exceptionLogMessage); logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } String validationBodyString = validationBodyJSON.toString(); // create the HTTP request PostRequest req; try { req = new PostRequest(validationServerURL, validationBodyString); } catch (MalformedURLException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "Invalid URL for receipt validation server."; logger.error(exceptionLogMessage); logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailingURLStringKey, validationServerURL); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } // Send the request. This method call will not return until the server returns. // note that this method may throw AccessDeniedException if the URL is whitelisted or rate limited, // or TimeoutException if the server took too long to return HttpResponse response; try { response = http.post(req); } catch (AccessDeniedException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "HTTP request refused by StackMob custom code environment."; String suggestionMessage = "Check rate limiting, whitelisting, and blacklisting in the StackMob custom code environment."; logger.error(exceptionLogMessage); logger.error(failureReason); logger.debug(suggestionMessage); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_FORBIDDEN); errorMap.put(kErrorDescriptionKey, kErrorCode403Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailureReasonKey, failureReason); errorMap.put(kRecoverySuggestionKey, suggestionMessage); return new ResponseToProcess(HttpURLConnection.HTTP_FORBIDDEN, errorMap); } catch (TimeoutException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "HTTP request to receipt validation server timed out."; logger.error(exceptionLogMessage); logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_GATEWAY_TIMEOUT); errorMap.put(kErrorDescriptionKey, kErrorCode504Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_GATEWAY_TIMEOUT, errorMap); } if (response == null) { String failureReason = "Response from receipt validation server is null."; logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } // Parse the response from the server JSONObject serverResponseJSON; try { serverResponseJSON = new JSONObject(response.getBody()); } catch (JSONException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "Could not parse JSON response from receipt validation server."; logger.error(exceptionLogMessage); logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } int validationStatus = -1; try { if (!serverResponseJSON.isNull(kValidationResponseStatusKey)) { validationStatus = serverResponseJSON.getInt(kValidationResponseStatusKey); } } catch (JSONException e) { String exceptionLogMessage = e.getClass().getName() + ": " + e.getMessage(); String failureReason = "Missing or invalid status code from receipt validation server."; logger.error(exceptionLogMessage); logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_INTERNAL_ERROR); errorMap.put(kErrorDescriptionKey, kErrorCode500Description); errorMap.put(kExceptionNameKey, e.getClass().getName()); errorMap.put(kExceptionMessageKey, e.getMessage()); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_INTERNAL_ERROR, errorMap); } // Take action based on receipt validation if (validationStatus == 0) { // // Receipt is valid // // This is where you could take any server-side actions that were required to fulfill the purchase. // See the StackMob custom code documentation for more details: // https://developer.preview.stackmob.com/tutorials/custom%20code // } else { // // Receipt is invalid // String failureReason = "Invalid receipt."; logger.error(failureReason); Map<String, Object> errorMap = new HashMap<String, Object>(); errorMap.put(kErrorCodeKey, HttpURLConnection.HTTP_PAYMENT_REQUIRED); errorMap.put(kErrorDescriptionKey, kErrorCode402Description); errorMap.put(kFailureReasonKey, failureReason); return new ResponseToProcess(HttpURLConnection.HTTP_PAYMENT_REQUIRED, errorMap); } // Send human-readable server response to calling client // Note: The parsing below is brittle (depends on there never being more than two layers of JSON). // This probably should be generalized using recursion. Map<String, Object> returnMap = new HashMap<String, Object>(); Iterator<?> keys = serverResponseJSON.keys(); while (keys.hasNext()) { String key = (String) keys.next(); try { if (serverResponseJSON.get(key) instanceof JSONObject) { JSONObject nestedJSON = (JSONObject) serverResponseJSON.get(key); Iterator<?> nestedKeys = nestedJSON.keys(); while (nestedKeys.hasNext()) { String nestedKey = (String) nestedKeys.next(); Object nestedValue = nestedJSON.get(nestedKey); returnMap.put(nestedKey, nestedValue.toString()); } } else { Object value = serverResponseJSON.get(key); returnMap.put(key, value.toString()); } } catch (JSONException e) { logger.debug(e.getMessage()); e.printStackTrace(); } } String finishMessage = "Receipt is valid."; logger.info(finishMessage); return new ResponseToProcess(HttpURLConnection.HTTP_OK, returnMap); }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
@Override public String execute(String request, int connectTimeout, int readTimeout) { // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection() // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in // max 1 second. String response = null;/*from ww w .ja v a2 s . co m*/ HttpsURLConnection connection = null; try { String correctedRequest = checkSessionToken(request); connection = getConnection(correctedRequest, connectTimeout, readTimeout); if (connection != null) { connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) { if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { response = IOUtils.toString(connection.getErrorStream()); } else { response = IOUtils.toString(connection.getInputStream()); } if (response != null) { if (!response.contains("Authentication failed")) { if (loginCounter > 0) { connectionManager.checkConnection(responseCode); } loginCounter = 0; } else { connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM); loginCounter++; } } } connection.disconnect(); if (response == null && connectionManager != null && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) { if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()), connectTimeout, readTimeout); loginCounter++; } else { connectionManager.checkConnection(responseCode); loginCounter++; return null; } } return response; } } catch (SocketTimeoutException e) { informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION); } catch (java.net.ConnectException e) { informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION); } catch (MalformedURLException e) { informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION); } catch (java.net.UnknownHostException e) { informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION); } catch (IOException e) { logger.error("An IOException occurred: ", e); if (connectionManager != null) { informConnectionManager(ConnectionManager.GENERAL_EXCEPTION); } } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testForbiddenSetTTL() throws IOException { try {//ww w. j ava 2 s. co m streamClient.setTTL(TestUtils.FORBIDDEN_STREAM_NAME, STREAM_TTL); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, e.getStatusCode()); } }
From source file:com.box.androidlib.BoxFileDownload.java
/** * Execute a file download.//w w w. j a v a2s . co m * * @param fileId * The file_id of the file to be downloaded * @param destinationOutputStreams * OutputStreams to which the data should be written to as it is downloaded. * @param versionId * The version_id of the version of the file to download. Set to null to download the latest version of the file. * @return a response handler * @throws IOException * Can be thrown if there was a connection error, or if destination file could not be written. */ public DefaultResponseParser execute(final long fileId, final OutputStream[] destinationOutputStreams, final Long versionId) throws IOException { final DefaultResponseParser handler = new DefaultResponseParser(); final Uri.Builder builder = new Uri.Builder(); builder.scheme(BoxConfig.getInstance().getDownloadUrlScheme()); builder.encodedAuthority(BoxConfig.getInstance().getDownloadUrlAuthority()); builder.path(BoxConfig.getInstance().getDownloadUrlPath()); builder.appendPath(mAuthToken); builder.appendPath(String.valueOf(fileId)); if (versionId != null) { builder.appendPath(String.valueOf(versionId)); } List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters(); if (customQueryParams != null && customQueryParams.size() > 0) { for (BasicNameValuePair param : customQueryParams) { builder.appendQueryParameter(param.getName(), param.getValue()); } } // We normally prefer to use HttpUrlConnection, however that appears to fail for certain types of files. For downloads, it appears DefaultHttpClient // works more reliably. final DefaultHttpClient httpclient = new DefaultHttpClient(); HttpProtocolParams.setUserAgent(httpclient.getParams(), BoxConfig.getInstance().getUserAgent()); HttpGet httpGet; String theUri = builder.build().toString(); if (BoxConfig.getInstance().getHttpLoggingEnabled()) { //DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpclient.getParams())); DevUtils.logcat("Box Request: " + theUri); } try { httpGet = new HttpGet(new URI(theUri)); } catch (URISyntaxException e) { throw new IOException("Invalid Download URL"); } httpGet.setHeader("Connection", "close"); httpGet.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage()); HttpResponse httpResponse = httpclient.execute(httpGet); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (BoxConfig.getInstance().getHttpLoggingEnabled()) { DevUtils.logcat("Box Response: " + responseCode); // Header[] headers = httpResponse.getAllHeaders(); // for (Header header : headers) { // DevUtils.logcat("Response Header: " + header.toString()); // } } // Server returned a 503 Service Unavailable. Usually means a temporary unavailability. if (responseCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { // if (BoxConfig.getInstance().getHttpLoggingEnabled()) { // DevUtils.logcat("HTTP Response Code: " + HttpStatus.SC_SERVICE_UNAVAILABLE); // } handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE); return handler; } InputStream is = httpResponse.getEntity().getContent(); if (responseCode == HttpURLConnection.HTTP_OK) { // Grab the first 100 bytes and check for an error string. // Not a good way for the server to respond with errors but that's the way it is for now. final byte[] errorCheckBuffer = new byte[FILE_ERROR_SIZE]; // Three cases here: error, no error && file size == 0, no error && file size > 0. // The first case will be handled by parsing the error check buffer. The second case will result in mBytesTransferred == 0, // no real bytes will be transferred but we still treat as success case. The third case is normal success case. mBytesTransferred = Math.max(0, is.read(errorCheckBuffer)); final String str = new String(errorCheckBuffer).trim(); if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN)) { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_WRONG_AUTH_TOKEN); } else if (str.equals(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED)) { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_RESTRICTED); } // No error detected else { // Copy the file to destination if > 0 bytes of file transferred. if (mBytesTransferred > 0) { for (int i = 0; i < destinationOutputStreams.length; i++) { destinationOutputStreams[i].write(errorCheckBuffer, 0, (int) mBytesTransferred); // Make sure we don't lose that first 100 bytes. } // Read the rest of the stream and write to the destination OutputStream. final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE]; int bufferLength = 0; long lastOnProgressPost = 0; while (!Thread.currentThread().isInterrupted() && (bufferLength = is.read(buffer)) > 0) { for (int i = 0; i < destinationOutputStreams.length; i++) { destinationOutputStreams[i].write(buffer, 0, bufferLength); } mBytesTransferred += bufferLength; long currTime = SystemClock.uptimeMillis(); if (mListener != null && mHandler != null && currTime - lastOnProgressPost > ON_PROGRESS_UPDATE_THRESHOLD) { lastOnProgressPost = currTime; mHandler.post(mOnProgressRunnable); } } mHandler.post(mOnProgressRunnable); } for (int i = 0; i < destinationOutputStreams.length; i++) { destinationOutputStreams[i].close(); } handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_OK); // If download thread was interrupted, set to // STATUS_DOWNLOAD_CANCELED if (Thread.currentThread().isInterrupted()) { httpGet.abort(); handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_CANCELLED); } } } else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_PERMISSIONS_ERROR); } else { handler.setStatus(FileDownloadListener.STATUS_DOWNLOAD_FAIL); } httpResponse.getEntity().consumeContent(); if (httpclient != null && httpclient.getConnectionManager() != null) { httpclient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS); } is.close(); return handler; }
From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientFileSystemBrowser.java
protected void runRequest() throws Exception { Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "runRequest"); //$NON-NLS-1$ setupProxies();//from ww w . ja v a 2 s .c o m // set timeout initHttpClientConnectionManager(); String urlString = directoryOrFile.toString(); CredentialsProvider credProvider = new HttpClientProxyCredentialProvider() { protected Proxy getECFProxy() { return getProxy(); } protected Credentials getNTLMCredentials(Proxy lp) { if (hasForceNTLMProxyOption()) return HttpClientRetrieveFileTransfer.createNTLMCredentials(lp); return null; } }; // setup authentication setupAuthentication(urlString); // setup https host and port setupHostAndPort(credProvider, urlString); headMethod = new HeadMethod(hostConfigHelper.getTargetRelativePath()); headMethod.setFollowRedirects(true); // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod) // Seems to be another way to select the credentials. headMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider); // set max-age for cache control to 0 for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=249990 headMethod.addRequestHeader("Cache-Control", "max-age=0"); //$NON-NLS-1$//$NON-NLS-2$ headMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$ long lastModified = 0; long fileLength = -1; connectingSockets.clear(); int code = -1; try { Trace.trace(Activator.PLUGIN_ID, "browse=" + urlString); //$NON-NLS-1$ code = httpClient.executeMethod(getHostConfiguration(), headMethod); Trace.trace(Activator.PLUGIN_ID, "browse resp=" + code); //$NON-NLS-1$ // Check for NTLM proxy in response headers // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002 boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(headMethod); if (ntlmProxyFound && !hasForceNTLMProxyOption()) throw new BrowseFileTransferException( "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$ HttpClientOptions.NTLM_PROXY_RESPONSE_CODE); if (code == HttpURLConnection.HTTP_OK) { fileLength = headMethod.getResponseContentLength(); lastModified = getLastModifiedTimeFromHeader(); } else if (code == HttpURLConnection.HTTP_NOT_FOUND) { throw new BrowseFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code); } else if (code == HttpURLConnection.HTTP_FORBIDDEN) { throw new BrowseFileTransferException("Forbidden", code); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) { throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required, code); } else { throw new BrowseFileTransferException( NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE, new Integer(code)), code); } remoteFiles = new IRemoteFile[1]; remoteFiles[0] = new URLRemoteFile(lastModified, fileLength, fileID); } catch (Exception e) { Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "runRequest", e); //$NON-NLS-1$ BrowseFileTransferException ex = (BrowseFileTransferException) ((e instanceof BrowseFileTransferException) ? e : new BrowseFileTransferException(NLS .bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString), e, code)); throw ex; } finally { headMethod.releaseConnection(); } }
From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java
@Test public void testRawHttpCalls() throws Exception { final Server jetty = createJettyServer(); Context context = new Context(); context.setContextPath("/foo"); jetty.setHandler(context);/*from ww w . j a v a2 s .c o m*/ context.addFilter(new FilterHolder(AFilter.class), "/*", 0); context.addServlet(new ServletHolder(PingServlet.class), "/bar"); try { jetty.start(); URL nonAuthURL = new URL(getJettyURL() + "/foo/bar"); URL authURL = new URL(getJettyURL() + "/foo/bar?authenticated=foo"); // unauthenticated access to URL HttpURLConnection conn = (HttpURLConnection) nonAuthURL.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); // authenticated access to URL conn = (HttpURLConnection) authURL.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); // unauthenticated access to get delegation token URL url = new URL(nonAuthURL.toExternalForm() + "?op=GETDELEGATIONTOKEN"); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); // authenticated access to get delegation token url = new URL(authURL.toExternalForm() + "&op=GETDELEGATIONTOKEN&renewer=foo"); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); ObjectMapper mapper = new ObjectMapper(); Map map = mapper.readValue(conn.getInputStream(), Map.class); String dt = (String) ((Map) map.get("Token")).get("urlString"); Assert.assertNotNull(dt); // delegation token access to URL url = new URL(nonAuthURL.toExternalForm() + "?delegation=" + dt); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); // delegation token and authenticated access to URL url = new URL(authURL.toExternalForm() + "&delegation=" + dt); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); // renewew delegation token, unauthenticated access to URL url = new URL(nonAuthURL.toExternalForm() + "?op=RENEWDELEGATIONTOKEN&token=" + dt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); // renewew delegation token, authenticated access to URL url = new URL(authURL.toExternalForm() + "&op=RENEWDELEGATIONTOKEN&token=" + dt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); // renewew delegation token, authenticated access to URL, not renewer url = new URL(getJettyURL() + "/foo/bar?authenticated=bar&op=RENEWDELEGATIONTOKEN&token=" + dt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode()); // cancel delegation token, nonauthenticated access to URL url = new URL(nonAuthURL.toExternalForm() + "?op=CANCELDELEGATIONTOKEN&token=" + dt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); // cancel canceled delegation token, nonauthenticated access to URL url = new URL(nonAuthURL.toExternalForm() + "?op=CANCELDELEGATIONTOKEN&token=" + dt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, conn.getResponseCode()); // get new delegation token url = new URL(authURL.toExternalForm() + "&op=GETDELEGATIONTOKEN&renewer=foo"); conn = (HttpURLConnection) url.openConnection(); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); mapper = new ObjectMapper(); map = mapper.readValue(conn.getInputStream(), Map.class); dt = (String) ((Map) map.get("Token")).get("urlString"); Assert.assertNotNull(dt); // cancel delegation token, authenticated access to URL url = new URL(authURL.toExternalForm() + "&op=CANCELDELEGATIONTOKEN&token=" + dt); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); } finally { jetty.stop(); } }
From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient29.java
private List<SubmitRecord> currentSubmitRecord(String uri, IProgressMonitor monitor) throws GerritException { List<SubmitRecord> submitRecordList = new ArrayList<SubmitRecord>(); SubmitRecord[] submitRecordArray = executePostRestRequest(uri, new SubmitRecord(), SubmitRecord[].class, new ErrorHandler() { @Override// ww w .j a va 2 s. com public void handleError(HttpMethodBase method) throws GerritException { String errorMsg = getResponseBodyAsString(method); if (isNotPermitted(method, errorMsg) || isConflict(method)) { throw new GerritException(NLS.bind("Cannot get submit change: {0}", errorMsg)); //$NON-NLS-1$ } } private String getResponseBodyAsString(HttpMethodBase method) { try { return method.getResponseBodyAsString(); } catch (IOException e) { return null; } } private boolean isNotPermitted(HttpMethodBase method, String msg) { return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN && "submit not permitted\n".equals(msg); //$NON-NLS-1$ } private boolean isConflict(HttpMethodBase method) { return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT; } }, monitor); for (SubmitRecord element : submitRecordArray) { List<SubmitRecord.Label> list = null; if (element.getStatus().equalsIgnoreCase("OK")) { //$NON-NLS-1$ list = element.createLabel(element, element.getOkMap(), OK); } else if (element.getStatus().equalsIgnoreCase("NOT_READY")) { //$NON-NLS-1$ list = element.createLabel(element, element.getNeedMap(), NEED); } else if (element.getStatus().equalsIgnoreCase("REJECT")) { //$NON-NLS-1$ list = element.createLabel(element, element.getRejectMap(), REJECT); } else if (element.getStatus().equalsIgnoreCase("MAY")) { //$NON-NLS-1$ list = element.createLabel(element, element.getMayMap(), MAY); } element.setLabels(list); submitRecordList.add(element); } return submitRecordList; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Get a default message for an HTTP code. * * @param context the context to use. * @param responseCode the http code. * @param defaultOkMessage an optional message for the ok code. * @return the message./*from w w w . j a v a 2 s.c o m*/ */ public static String getMessageForCode(Context context, int responseCode, String defaultOkMessage) { Resources resources = context.getResources(); switch (responseCode) { case HttpURLConnection.HTTP_OK: if (defaultOkMessage != null) { return defaultOkMessage; } else { return resources.getString(R.string.http_ok_msg); } case HttpURLConnection.HTTP_FORBIDDEN: return resources.getString(R.string.http_forbidden_msg); case HttpURLConnection.HTTP_UNAUTHORIZED: return resources.getString(R.string.http_forbidden_msg); case HttpURLConnection.HTTP_NOT_FOUND: return resources.getString(R.string.http_not_found_msg); default: return resources.getString(R.string.http_not_implemented_code_msg) + " " + responseCode; } }
From source file:org.eclipse.orion.server.tests.servlets.site.HostingTest.java
@Test // Test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=382760 public void testDisallowedSiteAccess() throws SAXException, IOException, JSONException, URISyntaxException, CoreException { User userBObject = createUser("userB", "userB"); String userB = userBObject.getLogin(); // User "test": create file in test's workspace final String filename = "foo.html"; final String fileContent = "<html><body>This is a test file</body></html>"; WebResponse createdFile = createFileOnServer("", filename, fileContent); URL fileLocation = createdFile.getURL(); IPath filepath = new Path(fileLocation.getPath()); filepath = filepath.removeFirstSegments(new Path(FILE_SERVLET_LOCATION).segmentCount()); // chop off leading /file/ filepath = filepath.removeLastSegments(1); // chop off trailing /foo.html filepath = filepath.makeAbsolute();//from w w w .ja v a2 s . co m filepath = filepath.addTrailingSeparator(); String parentFolder = filepath.toString(); // User B: Create a workspace that User B has access to WebResponse createWorkspaceResp = basicCreateWorkspace("userB"); String bWorkspaceId = new JSONObject(createWorkspaceResp.getText()).getString(ProtocolConstants.KEY_ID); AuthorizationService.addUserRight(userBObject.getUid(), createWorkspaceResp.getURL().getPath()); AuthorizationService.addUserRight(userBObject.getUid(), createWorkspaceResp.getURL().getPath() + "/*"); // User B: create a site against B's workspace that exposes a file in test's workspace final String siteName = "My hosted site"; final String filePath = parentFolder; //"/" + filename; final String mountAt = "/"; //"/file.html"; final JSONArray mappings = makeMappings(new String[][] { { mountAt, filePath } }); WebRequest createSiteReq = getCreateSiteRequest(siteName, bWorkspaceId, mappings, null); setAuthentication(createSiteReq, userB, userB); WebResponse createSiteResp = webConversation.getResponse(createSiteReq); assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode()); JSONObject siteObject = new JSONObject(createSiteResp.getText()); // User B: Start the site String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION); siteObject = startSite(location, userB, userB); final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS); final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL); // Attempt to access file on user B's site, should fail WebRequest getFileReq = new GetMethodWebRequest(hostedURL + mountAt); WebResponse getFileResp = webConversation.getResponse(getFileReq); assertEquals(HttpURLConnection.HTTP_FORBIDDEN, getFileResp.getResponseCode()); }
From source file:com.github.pascalgn.jiracli.web.HttpClient.java
private <T> T doExecute(HttpUriRequest request, boolean retry, Function<HttpEntity, T> function) { LOGGER.debug("Calling URL: {} [{}]", request.getURI(), request.getMethod()); // disable XSRF check: if (!request.containsHeader("X-Atlassian-Token")) { request.addHeader("X-Atlassian-Token", "nocheck"); }//from ww w .jav a 2 s.com HttpResponse response; try { response = httpClient.execute(request, httpClientContext); } catch (IOException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw new IllegalStateException("Could not call URL: " + request.getURI(), e); } } LOGGER.debug("Response received ({})", response.getStatusLine().toString().trim()); HttpEntity entity = response.getEntity(); try { if (Thread.interrupted()) { throw new InterruptedError(); } int statusCode = response.getStatusLine().getStatusCode(); if (isSuccess(statusCode)) { T result; try { result = function.apply(entity, Hint.none()); } catch (NotAuthenticatedException e) { if (retry) { resetAuthentication(); setCredentials(); return doExecute(request, false, function); } else { throw e.getCause(); } } catch (RuntimeException e) { if (Thread.interrupted()) { LOGGER.trace("Could not call URL: {}", request.getURI(), e); throw new InterruptedError(); } else { throw e; } } if (Thread.interrupted()) { throw new InterruptedError(); } return result; } else { if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { resetAuthentication(); if (retry) { setCredentials(); return doExecute(request, false, function); } else { String error = readErrorResponse(request.getURI(), entity); LOGGER.debug("Unauthorized [401]: {}", error); throw new AccessControlException("Unauthorized [401]: " + request.getURI()); } } else if (statusCode == HttpURLConnection.HTTP_FORBIDDEN) { resetAuthentication(); checkAccountLocked(response); if (retry) { setCredentials(); return doExecute(request, false, function); } else { throw new AccessControlException("Forbidden [403]: " + request.getURI()); } } else { String status = response.getStatusLine().toString().trim(); String message; if (entity == null) { message = status; } else { String error = readErrorResponse(request.getURI(), entity); message = status + (error.isEmpty() ? "" : ": " + error); } if (Thread.interrupted()) { throw new InterruptedError(); } if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) { throw new NoSuchElementException(message); } else { throw new IllegalStateException(message); } } } } finally { EntityUtils.consumeQuietly(entity); } }