List of usage examples for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR
int SC_INTERNAL_SERVER_ERROR
To view the source code for org.apache.commons.httpclient HttpStatus SC_INTERNAL_SERVER_ERROR.
Click Source Link
From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java
private int computeStatus(int status) { switch (status) { case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_METHOD_NOT_ALLOWED: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_NOT_ACCEPTABLE: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: case HttpStatus.SC_REQUEST_TIMEOUT: case HttpStatus.SC_CONFLICT: case HttpStatus.SC_GONE: case HttpStatus.SC_LENGTH_REQUIRED: case HttpStatus.SC_PRECONDITION_FAILED: case HttpStatus.SC_REQUEST_TOO_LONG: case HttpStatus.SC_REQUEST_URI_TOO_LONG: case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE: case HttpStatus.SC_EXPECTATION_FAILED: case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE: case HttpStatus.SC_METHOD_FAILURE: case HttpStatus.SC_UNPROCESSABLE_ENTITY: case HttpStatus.SC_LOCKED: case HttpStatus.SC_FAILED_DEPENDENCY: case HttpStatus.SC_INTERNAL_SERVER_ERROR: case HttpStatus.SC_NOT_IMPLEMENTED: case HttpStatus.SC_BAD_GATEWAY: case HttpStatus.SC_SERVICE_UNAVAILABLE: case HttpStatus.SC_GATEWAY_TIMEOUT: case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED: case HttpStatus.SC_INSUFFICIENT_STORAGE: return 0; case HttpStatus.SC_CONTINUE: case HttpStatus.SC_SWITCHING_PROTOCOLS: case HttpStatus.SC_PROCESSING: case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION: case HttpStatus.SC_NO_CONTENT: case HttpStatus.SC_RESET_CONTENT: case HttpStatus.SC_PARTIAL_CONTENT: case HttpStatus.SC_MULTI_STATUS: case HttpStatus.SC_MULTIPLE_CHOICES: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_NOT_MODIFIED: case HttpStatus.SC_USE_PROXY: case HttpStatus.SC_TEMPORARY_REDIRECT: return 1; default:// w w w.j a v a 2 s. c om return 1; } }
From source file:org.opensaml.ws.soap.client.http.HttpSOAPClient.java
/** {@inheritDoc} */ public void send(String endpoint, SOAPMessageContext messageContext) throws SOAPException, SecurityException { PostMethod post = null;//w ww .java 2s. com try { post = createPostMethod(endpoint, (HttpSOAPRequestParameters) messageContext.getSOAPRequestParameters(), (Envelope) messageContext.getOutboundMessage()); int result = httpClient.executeMethod(post); log.debug("Received HTTP status code of {} when POSTing SOAP message to {}", result, endpoint); if (result == HttpStatus.SC_OK) { processSuccessfulResponse(post, messageContext); } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) { processFaultResponse(post, messageContext); } else { throw new SOAPClientException( "Received " + result + " HTTP response status code from HTTP request to " + endpoint); } } catch (IOException e) { throw new SOAPClientException("Unable to send request to " + endpoint, e); } finally { if (post != null) { post.releaseConnection(); } } }
From source file:org.pentaho.di.baserver.utils.inspector.InspectorTest.java
@Test public void testInspectModuleNames() throws Exception { doReturn(SERVER_URL).when(inspectorSpy).getServerUrl(); doReturn(null).when(inspectorSpy).callHttp(SERVER_URL + "/api/plugin-manager/ids"); assertFalse(inspectorSpy.inspectModuleNames()); Response response = mock(Response.class); doReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR).when(response).getStatusCode(); doReturn(response).when(inspectorSpy).callHttp(SERVER_URL + "/api/plugin-manager/ids"); assertFalse(inspectorSpy.inspectModuleNames()); doReturn(HttpStatus.SC_OK).when(response).getStatusCode(); doReturn("{ strings: ['url','data-access','cgg','marketplace','xaction','jpivot']}").when(response) .getResult();/*from ww w . j a v a 2 s. c o m*/ assertTrue(inspectorSpy.inspectModuleNames()); assertEquals(inspectorSpy.getEndpointsTree().size(), 7); }
From source file:org.pentaho.di.baserver.utils.inspector.InspectorTest.java
@Test public void testInspectEndpoints() throws Exception { String moduleName = "myModule", applicationWadlEndpoint = SERVER_URL + moduleName + "/application.wadl"; doReturn("").when(inspectorSpy).getApplicationWadlEndpoint(moduleName); doReturn(null).when(inspectorSpy).callHttp(anyString()); assertFalse(inspectorSpy.inspectEndpoints(moduleName)); Response response = mock(Response.class); doReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR).when(response).getStatusCode(); doReturn(response).when(inspectorSpy).callHttp(anyString()); assertFalse(inspectorSpy.inspectEndpoints(moduleName)); doReturn(HttpStatus.SC_OK).when(response).getStatusCode(); doReturn(null).when(inspectorSpy).getDocument(anyString()); assertFalse(inspectorSpy.inspectEndpoints(moduleName)); Document doc = mock(Document.class); doReturn(doc).when(inspectorSpy).getDocument(anyString()); WadlParser parser = mock(WadlParser.class); List<Endpoint> endpointList = new ArrayList<Endpoint>(); Endpoint endpoint1 = new Endpoint(), endpoint2 = new Endpoint(), endpoint3 = new Endpoint(); endpoint1.setPath("path"); endpoint2.setPath("path"); endpoint3.setPath(""); endpointList.add(endpoint1);/*from w w w . j a va 2 s . c om*/ endpointList.add(endpoint2); endpointList.add(endpoint3); doReturn(endpointList).when(parser).getEndpoints(doc); doReturn(parser).when(inspectorSpy).getParser(); assertTrue(inspectorSpy.inspectEndpoints(moduleName)); }
From source file:org.sakaiproject.nakamura.grouper.changelog.util.NakamuraHttpUtils.java
/** * Prepare an HTTP request to Sakai OAE and parse the response (if JSON). * @param client an {@link HttpClient} to execute the request. * @param method an HTTP method to send//from ww w.ja v a 2s .com * @return a JSONObject of the response if the request returns JSON * @throws GroupModificationException if there was an error updating the group information. */ public static JSONObject http(HttpClient client, HttpMethod method) throws GroupModificationException { method.setRequestHeader("User-Agent", HTTP_USER_AGENT); method.setRequestHeader("Referer", HTTP_REFERER); String errorMessage = null; String responseString = null; JSONObject responseJSON = null; boolean isJSONRequest = !method.getPath().toString().endsWith(".html"); if (log.isDebugEnabled() && method instanceof PostMethod) { log.debug(method.getName() + " " + method.getPath() + " params:"); for (NameValuePair nvp : ((PostMethod) method).getParameters()) { log.debug(nvp.getName() + " = " + nvp.getValue()); } } int responseCode = -1; try { responseCode = client.executeMethod(method); responseString = StringUtils.trimToNull(IOUtils.toString(method.getResponseBodyAsStream())); if (isJSONRequest) { responseJSON = parseJSONResponse(responseString); } if (log.isDebugEnabled()) { log.debug(responseCode + " " + method.getName() + " " + method.getPath()); } if (log.isTraceEnabled()) { log.trace("reponse: " + responseString); } switch (responseCode) { case HttpStatus.SC_OK: // 200 case HttpStatus.SC_CREATED: // 201 break; case HttpStatus.SC_BAD_REQUEST: // 400 case HttpStatus.SC_UNAUTHORIZED: // 401 case HttpStatus.SC_NOT_FOUND: // 404 case HttpStatus.SC_INTERNAL_SERVER_ERROR: // 500 if (isJSONRequest && responseJSON != null) { errorMessage = responseJSON.getString("status.message"); } if (errorMessage == null) { errorMessage = "Empty " + responseCode + " error. Check the logs on the Sakai OAE server."; } break; default: errorMessage = "Unknown HTTP response " + responseCode; break; } } catch (Exception e) { errorMessage = "An exception occurred communicatingSakai OAE. " + e.toString(); } finally { method.releaseConnection(); } if (errorMessage != null) { log.error(errorMessage); errorToException(responseCode, errorMessage); } return responseJSON; }
From source file:org.smartfrog.projects.alpine.transport.http.HttpTransmitter.java
/** * Transmit a file containing an XML message. * the file is not deleted afterwards, so the transport can be used to push up existing messages * @param outputFile file to upload.//from w ww . j a v a 2s. c o m * @throws AlpineRuntimeException in case of trouble. */ public void transmitPayload(File outputFile) { String destination = wsa.getDestination(); log.debug("Posting to " + destination); PostMethod method = new ProgressingPostMethod(destination); //REVISIT. Its not clear that this method should stay around. //method.setFollowRedirects(true); method.addRequestHeader("SOAPAction", ""); method.addRequestHeader("User-Agent", HttpConstants.ALPINE_VERSION); //fill in the details //1. get the message into a byte array //2. add it //3. TODO: add files? RequestEntity re = null; String contentType = HttpConstants.CONTENT_TYPE_TEXT_XML; String ctxContentType = (String) tx.getContext().get(ContextConstants.ATTR_SOAP_CONTENT_TYPE); if (ctxContentType != null) { contentType = ctxContentType; } re = new ProgressiveFileUploadRequestEntity(tx, request, outputFile, contentType, tx.getUploadFeedback(), BLOCKSIZE); method.setRequestEntity(re); InputStream responseStream = null; try { int statusCode = httpclient.executeMethod(method); final boolean requestFailed = statusCode != HttpStatus.SC_OK; boolean responseIsXml; //get the content type and drop anything following a semicolon //this can be null on an empty response contentType = getResponseContentType(method); if (contentType != null) { contentType = HttpBinder.extractBaseContentType(contentType); responseIsXml = HttpBinder.isValidSoapContentType(contentType); } else { responseIsXml = false; } if (requestFailed && (!responseIsXml || statusCode != HttpStatus.SC_INTERNAL_SERVER_ERROR)) { //TODO: treat 500+text/xml response specially, as it is probably a SOAPFault log.error("Method failed: " + method.getStatusLine()); throw new HttpTransportFault(destination, method); } //response is 200, but is it HTML? if (!responseIsXml) { HttpTransportFault fault = new HttpTransportFault(destination, method, "Wrong content type: expected " + HttpConstants.CONTENT_TYPE_TEXT_XML + " or " + HttpConstants.CONTENT_TYPE_SOAP_XML + " but got [" + contentType + ']'); throw fault; } //extract the response responseStream = new CachingInputStream(method.getResponseBodyAsStream(), "utf8"); //parse it SoapMessageParser parser = tx.getContext().createParser(); MessageDocument response; if (!requestFailed) { response = parser.parseStream(responseStream); //set our response tx.getContext().setResponse(response); } else { // if is a fault, turn it into an exception. try { response = parser.parseStream(responseStream); //set our response tx.getContext().setResponse(response); } catch (Exception e) { //this is here to catch XML Responses that cannot be //parsed, and to avoid the underlying problem 'remote server error' //from being lost. String text = responseStream.toString(); SoapException ex = new SoapException("The remote endpoint returned an error,\n" + "but the response could not be parsed\n" + "and turned into a SOAPFault.\n" + "XML:" + text + "\nParse Error:" + e.toString(), e, null); ex.addAddressDetails(request); throw ex; } SoapException ex = new SoapException(response); throw ex; } } catch (IOException ioe) { throw new HttpTransportFault(destination, ioe); } catch (SAXException e) { throw new HttpTransportFault(destination, e); } catch (ParsingException e) { throw new HttpTransportFault(destination, e); } finally { if (responseStream != null) { try { responseStream.close(); } catch (IOException e) { //ignore this. } } method.releaseConnection(); } }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
@Override protected boolean checkRemoteAvailability(long newerThen, ProxyRepository repository, ResourceStoreRequest request, boolean isStrict) throws RemoteStorageException { URL remoteURL = getAbsoluteUrlFromBase(repository, request); HttpMethodBase method = new HeadMethod(remoteURL.toString()); int response = HttpStatus.SC_BAD_REQUEST; // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails boolean doGet = false; try {// www.ja v a 2s . c o m response = executeMethod(repository, request, method, remoteURL); } catch (RemoteStorageException e) { // If HEAD failed, attempt a GET. Some repos may not support HEAD method doGet = true; getLogger().debug("HEAD method failed, will attempt GET. Exception: " + e.getMessage(), e); } finally { method.releaseConnection(); // HEAD returned error, but not exception, try GET before failing if (!doGet && response != HttpStatus.SC_OK) { doGet = true; getLogger().debug("HEAD method failed, will attempt GET. Status: " + response); } } if (doGet) { // create a GET method = new GetMethod(remoteURL.toString()); try { // execute it response = executeMethod(repository, request, method, remoteURL); } finally { // and release it immediately method.releaseConnection(); } } // if we are not strict and remote is S3 if (!isStrict && isRemotePeerAmazonS3Storage(repository)) { // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of // repository (how could we do that?) // this "relaxed" check will help us to "pass" S3 remote storage. return response >= HttpStatus.SC_OK && response <= HttpStatus.SC_INTERNAL_SERVER_ERROR; } else { // non relaxed check is strict, and will select only the OK response if (response == HttpStatus.SC_OK) { // we have it // we have newer if this below is true return makeDateFromHeader(method.getResponseHeader("last-modified")) > newerThen; } else if ((response >= HttpStatus.SC_MULTIPLE_CHOICES && response < HttpStatus.SC_BAD_REQUEST) || response == HttpStatus.SC_NOT_FOUND) { return false; } else { throw new RemoteStorageException("Unexpected response code while executing " + method.getName() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]. Expected: \"SUCCESS (200)\". Received: " + response + " : " + HttpStatus.getStatusText(response)); } } }
From source file:org.svenk.redmine.core.client.AbstractRedmineClient.java
/** * Execute the given method - handle authentication concerns. * //w w w.j av a 2 s .c om * @param method * @param hostConfiguration * @param monitor * @param authenticated * @return * @throws RedmineException */ protected int executeMethod(HttpMethod method, HostConfiguration hostConfiguration, IProgressMonitor monitor) throws RedmineException { monitor = Policy.monitorFor(monitor); int statusCode = performExecuteMethod(method, hostConfiguration, monitor); if (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { Header statusHeader = method.getResponseHeader(HEADER_STATUS); String msg = Messages.AbstractRedmineClient_SERVER_ERROR; if (statusHeader != null) { msg += " : " + statusHeader.getValue().replace("" + HttpStatus.SC_INTERNAL_SERVER_ERROR, "").trim(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } throw new RedmineRemoteException(msg); } //TODO testen, sollte ohne gehen // if (statusCode==HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // hostConfiguration = refreshCredentials(AuthenticationType.PROXY, method, monitor); // return executeMethod(method, hostConfiguration, monitor, authenticated); // } // // if(statusCode==HttpStatus.SC_UNAUTHORIZED && supportAdditionalHttpAuth()) { // hostConfiguration = refreshCredentials(AuthenticationType.HTTP, method, monitor); // return executeMethod(method, hostConfiguration, monitor, authenticated); // } // // if (statusCode>=400 && statusCode<=599) { // throw new RedmineRemoteException(method.getStatusLine().toString()); // } Header respHeader = method.getResponseHeader(HEADER_REDIRECT); if (respHeader != null && (respHeader.getValue().endsWith(REDMINE_URL_LOGIN) || respHeader.getValue().indexOf(REDMINE_URL_LOGIN_CALLBACK) >= 0)) { throw new RedmineException(Messages.AbstractRedmineClient_LOGIN_FORMALY_INEFFECTIVE); } return statusCode; }
From source file:org.tuleap.mylyn.task.core.internal.client.rest.RestOperation.java
/** * Throws a CoreException that encapsulates useful info about a server error. * * @param response/*w ww. j a va 2 s . com*/ * The error response received from the server. * @throws CoreException * If the given response does not have a status OK (200). */ protected void checkServerError(ServerResponse response) throws CoreException { if (!response.isOk()) { String responseBody = response.getBody(); TuleapErrorMessage message = gson.fromJson(responseBody, TuleapErrorMessage.class); TuleapErrorPart errorPart = null; TuleapDebugPart debugPart = null; if (message != null) { errorPart = message.getError(); debugPart = message.getDebug(); } String msg; int statusCode = response.getStatus(); if (statusCode >= 1000) { // Communication error msg = TuleapCoreMessages.getString(TuleapCoreKeys.communicationError, Integer.toString(statusCode)); } else { if (errorPart == null) { String arg = Integer.toString(statusCode) + ' ' + HttpStatus.getStatusText(statusCode); if (!responseBody.isEmpty()) { arg += '/' + responseBody; } if (statusCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR) { // Server error msg = TuleapCoreMessages.getString(TuleapCoreKeys.internalServerError, fullUrl, method.name(), arg); } else { msg = TuleapCoreMessages.getString(TuleapCoreKeys.errorReturnedByServer, fullUrl, method.name(), arg, TuleapCoreMessages.getString(TuleapCoreKeys.noMessage)); } } else { if (debugPart != null) { msg = TuleapCoreMessages.getString(TuleapCoreKeys.errorReturnedByServerWithDebug, fullUrl, method.name(), Integer.valueOf(errorPart.getCode()), errorPart.getMessage(), debugPart.getSource()); } else { msg = TuleapCoreMessages.getString(TuleapCoreKeys.errorReturnedByServer, fullUrl, method.name(), Integer.valueOf(errorPart.getCode()), errorPart.getMessage()); } } } throw new CoreException(new Status(IStatus.ERROR, TuleapCoreActivator.PLUGIN_ID, msg)); } }
From source file:org.wso2.am.integration.tests.other.APIMANAGER4373BrokenAPIInStoreTestCase.java
@Test(groups = "wso2.am", description = "Test effect of changing the role of subscribed API") public void testAPIRoleChangeEffectInStore() throws Exception { // create two apis apiPublisher.login(contextUsername, contextUserPassword); APIRequest brokenApiRequest = new APIRequest(BROKEN_API, BROKEN_API, new URL(EP_URL)); brokenApiRequest.setVersion(API_VERSION); brokenApiRequest.setProvider(contextUsername); brokenApiRequest.setVisibility("restricted"); brokenApiRequest.setRoles(FIRST_ROLE); apiPublisher.addAPI(brokenApiRequest); APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(BROKEN_API, contextUsername, APILifeCycleState.PUBLISHED); apiPublisher.changeAPILifeCycleStatus(updateRequest); APIRequest healthyApiRequest = new APIRequest(HEALTHY_API, HEALTHY_API, new URL(EP_URL)); healthyApiRequest.setVersion(API_VERSION); healthyApiRequest.setProvider(contextUsername); healthyApiRequest.setVisibility("restricted"); healthyApiRequest.setRoles(FIRST_ROLE); apiPublisher.addAPI(healthyApiRequest); updateRequest = new APILifeCycleStateRequest(HEALTHY_API, contextUsername, APILifeCycleState.PUBLISHED); apiPublisher.changeAPILifeCycleStatus(updateRequest); // subscribe both apis apiStoreRestClient.login(FIRST_USER, USER_PASSWORD); apiStoreRestClient.addApplication(APP_NAME, "Unlimited", "", ""); SubscriptionRequest subscriptionRequest = new SubscriptionRequest(BROKEN_API, contextUsername); subscriptionRequest.setApplicationName(APP_NAME); apiStoreRestClient.subscribe(subscriptionRequest); subscriptionRequest = new SubscriptionRequest(HEALTHY_API, contextUsername); subscriptionRequest.setApplicationName(APP_NAME); apiStoreRestClient.subscribe(subscriptionRequest); brokenApiRequest.setRoles(SECOND_ROLE); brokenApiRequest.setTags("updated"); Thread.sleep(1000);/*from w ww . java 2 s .c om*/ apiPublisher.updateAPI(brokenApiRequest); HttpResponse response = new HttpResponse("", HttpStatus.SC_INTERNAL_SERVER_ERROR); try { response = apiStoreRestClient.getAllSubscriptions(); } catch (Exception e) { // Expectation of this test case is to test whether permitted apis are returned to the store. // therefore exception thrown from the registry for unauthorized api is not handled here. } assertTrue(response.getData().contains(HEALTHY_API), "Subscription retrieval failed when one API is broken"); }