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.ldp4j.server.frontend.ServerFrontendITest.java
@Test @Category({ ExceptionPath.class }) @OperateOnDeployment(DEPLOYMENT)//from w w w . ja v a 2 s . c o m public void testGetPostconditionFailure(@ArquillianResource final URL url) throws Exception { LOGGER.info("Started {}", testName.getMethodName()); HELPER.base(url); HELPER.setLegacy(false); HttpGet get = HELPER.newRequest(TestingApplication.ROOT_BAD_RESOURCE_PATH, HttpGet.class); Metadata getResponse = HELPER.httpRequest(get); assertThat(getResponse.status, equalTo(HttpStatus.SC_INTERNAL_SERVER_ERROR)); assertThat(getResponse.body, notNullValue()); assertThat(getResponse.contentType, startsWith("text/plain")); assertThat(getResponse.language, equalTo(Locale.ENGLISH)); }
From source file:org.ldp4j.server.frontend.ServerFrontendITest.java
@Test @Category({ ExceptionPath.class }) @OperateOnDeployment(DEPLOYMENT)//from www . j a v a2 s .c o m public void testQueryPostConditionFailure(@ArquillianResource final URL url) throws Exception { LOGGER.info("Started {}", testName.getMethodName()); HELPER.base(url); HELPER.setLegacy(false); HttpGet get = HELPER.newRequest(TestingApplication.ROOT_BAD_RESOURCE_PATH + "?exampleQuery=parameter", HttpGet.class); Metadata getResponse = HELPER.httpRequest(get); assertThat(getResponse.status, equalTo(HttpStatus.SC_INTERNAL_SERVER_ERROR)); assertThat(getResponse.body, notNullValue()); assertThat(getResponse.contentType, startsWith("text/plain")); assertThat(getResponse.language, equalTo(Locale.ENGLISH)); }
From source file:org.ldp4j.server.frontend.ServerFrontendITest.java
@Test @Category({ ExceptionPath.class }) @OperateOnDeployment(DEPLOYMENT)//from w ww .j a v a2 s . c o m public void testPostPostconditionFailure(@ArquillianResource final URL url) throws Exception { LOGGER.info("Started {}", testName.getMethodName()); HELPER.base(url); HELPER.setLegacy(false); HttpPost post = HELPER.newRequest(TestingApplication.ROOT_BAD_RESOURCE_PATH, HttpPost.class); post.setEntity(new StringEntity(TEST_SUITE_BODY, ContentType.create("text/turtle", "UTF-8"))); Metadata response = HELPER.httpRequest(post); assertThat(response.status, equalTo(HttpStatus.SC_INTERNAL_SERVER_ERROR)); assertThat(response.body, notNullValue()); assertThat(response.contentType, startsWith("text/plain")); assertThat(response.language, equalTo(Locale.ENGLISH)); }
From source file:org.linagora.linshare.webservice.interceptor.GenericExceptionMapper.java
@Override public Response toResponse(Exception exception) { logger.error("A NullPointerException was caught : " + exception.getLocalizedMessage() + ". ", exception); ErrorDto errorDto = new ErrorDto(BusinessErrorCode.WEBSERVICE_FAULT.getCode(), "Unexpected exception : " + exception.getClass().toString() + " : " + exception.getMessage()); ResponseBuilder response = Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.entity(errorDto);// w w w . jav a2 s . co m return response.build(); }
From source file:org.linagora.linshare.webservice.interceptor.SoapExceptionInterceptor.java
private void generateSoapFault(Fault fault, BusinessException e) { fault.setFaultCode(createQName(e.getErrorCode().getCode())); fault.setMessage(e.getMessage());//from w w w . j a v a2 s .c om switch (e.getErrorCode()) { case WEBSERVICE_FAULT: fault.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); break; case WEBSERVICE_FORBIDDEN: fault.setStatusCode(HttpStatus.SC_FORBIDDEN); break; case FORBIDDEN: fault.setStatusCode(HttpStatus.SC_FORBIDDEN); break; case USER_NOT_FOUND: fault.setStatusCode(HttpStatus.SC_NOT_FOUND); break; case WEBSERVICE_NOT_FOUND: fault.setStatusCode(HttpStatus.SC_NOT_FOUND); break; default: fault.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.methodize.nntprss.feed.Channel.java
/** * Retrieves the latest RSS doc from the remote site */// ww w .jav a 2s . c o m public synchronized void poll() { // Use method-level variable // Guard against change in history mid-poll polling = true; // boolean keepHistory = historical; long keepExpiration = expiration; lastPolled = new Date(); int statusCode = -1; HttpMethod method = null; String urlString = url.toString(); try { HttpClient httpClient = getHttpClient(); channelManager.configureHttpClient(httpClient); HttpResult result = null; try { connected = true; boolean redirected = false; int count = 0; do { URL currentUrl = new URL(urlString); method = new GetMethod(urlString); method.setRequestHeader("User-agent", AppConstants.getUserAgent()); method.setRequestHeader("Accept-Encoding", "gzip"); method.setFollowRedirects(false); method.setDoAuthentication(true); // ETag if (lastETag != null) { method.setRequestHeader("If-None-Match", lastETag); } // Last Modified if (lastModified != 0) { final String NAME = "If-Modified-Since"; //defend against such fun like net.freeroller.rickard got If-Modified-Since "Thu, 24 Aug 2028 12:29:54 GMT" if (lastModified < System.currentTimeMillis()) { final String DATE = httpDate.format(new Date(lastModified)); method.setRequestHeader(NAME, DATE); log.debug("channel " + this.name + " using " + NAME + " " + DATE); //ALEK } } method.setFollowRedirects(false); method.setDoAuthentication(true); HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(currentUrl.getHost(), currentUrl.getPort(), currentUrl.getProtocol()); result = executeHttpRequest(httpClient, hostConfig, method); statusCode = result.getStatusCode(); if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) { redirected = true; // Resolve against current URI - may be a relative URI try { urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString(); } catch (URISyntaxException use) { // Fall back to just using location from result urlString = result.getLocation(); } if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY && channelManager.isObserveHttp301()) { try { url = new URL(urlString); if (log.isInfoEnabled()) { log.info("Channel = " + this.name + ", updated URL from HTTP Permanent Redirect"); } } catch (MalformedURLException mue) { // Ignore URL permanent redirect for now... } } } else { redirected = false; } // method.getResponseBody(); // method.releaseConnection(); count++; } while (count < 5 && redirected); } catch (HttpRecoverableException hre) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Temporary Http Problem - " + hre.getMessage()); } status = STATUS_CONNECTION_TIMEOUT; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (ConnectException ce) { // @TODO Might also be a connection refused - not only a timeout... if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Connection Timeout, skipping - " + ce.getMessage()); } status = STATUS_CONNECTION_TIMEOUT; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (UnknownHostException ue) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Unknown Host Exception, skipping"); } status = STATUS_UNKNOWN_HOST; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (NoRouteToHostException re) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - No Route To Host Exception, skipping"); } status = STATUS_NO_ROUTE_TO_HOST; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } catch (SocketException se) { // e.g. Network is unreachable if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - Socket Exception, skipping"); } status = STATUS_SOCKET_EXCEPTION; statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; } // Only process if ok - if not ok (e.g. not modified), don't do anything if (connected && statusCode == HttpStatus.SC_OK) { PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()), PUSHBACK_BUFFER_SIZE); skipBOM(pbis); BufferedInputStream bis = new BufferedInputStream(pbis); DocumentBuilder db = AppConstants.newDocumentBuilder(); try { Document rssDoc = null; if (!parseAtAllCost) { try { rssDoc = db.parse(bis); } catch (InternalError ie) { // Crimson library throws InternalErrors if (log.isDebugEnabled()) { log.debug("InternalError thrown by Crimson", ie); } throw new SAXException("InternalError thrown by Crimson: " + ie.getMessage()); } } else { // Parse-at-all-costs selected // Read in document to local array - may need to parse twice ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead = bis.read(buf); while (bytesRead > -1) { if (bytesRead > 0) { bos.write(buf, 0, bytesRead); } bytesRead = bis.read(buf); } bos.flush(); bos.close(); byte[] rssDocBytes = bos.toByteArray(); try { // Try the XML document parser first - just in case // the doc is well-formed rssDoc = db.parse(new ByteArrayInputStream(rssDocBytes)); } catch (SAXParseException spe) { if (log.isDebugEnabled()) { log.debug("XML parse failed, trying tidy"); } // Fallback to parse-at-all-costs parser rssDoc = LooseParser.parse(new ByteArrayInputStream(rssDocBytes)); } } processChannelDocument(expiration, rssDoc); // Update last modified / etag from headers // lastETag = httpCon.getHeaderField("ETag"); // lastModified = httpCon.getHeaderFieldDate("Last-Modified", 0); Header hdrETag = method.getResponseHeader("ETag"); lastETag = hdrETag != null ? hdrETag.getValue() : null; Header hdrLastModified = method.getResponseHeader("Last-Modified"); lastModified = hdrLastModified != null ? parseHttpDate(hdrLastModified.getValue()) : 0; log.debug("channel " + this.name + " parsed Last-Modifed " + hdrLastModified + " to " + (lastModified != 0 ? "" + (new Date(lastModified)) : "" + lastModified)); //ALEK status = STATUS_OK; } catch (SAXParseException spe) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Error parsing RSS document - check feed"); } status = STATUS_INVALID_CONTENT; } bis.close(); // end if response code == HTTP_OK } else if (connected && statusCode == HttpStatus.SC_NOT_MODIFIED) { if (log.isDebugEnabled()) { log.debug("Channel=" + name + " - HTTP_NOT_MODIFIED, skipping"); } status = STATUS_OK; } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Proxy authentication required"); } status = STATUS_PROXY_AUTHENTICATION_REQUIRED; } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Authentication required"); } status = STATUS_USER_AUTHENTICATION_REQUIRED; } // Update channel in database... channelDAO.updateChannel(this); } catch (FileNotFoundException fnfe) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - File not found returned by web server - check feed"); } status = STATUS_NOT_FOUND; } catch (Exception e) { if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - Exception while polling channel", e); } } catch (NoClassDefFoundError ncdf) { // Throw if SSL / redirection to HTTPS if (log.isEnabledFor(Priority.WARN)) { log.warn("Channel=" + name + " - NoClassDefFound", ncdf); } } finally { connected = false; polling = false; } }
From source file:org.olat.user.propertyhandlers.MSNPropertyHandler.java
/** * @see org.olat.user.propertyhandlers.Generic127CharTextPropertyHandler#isValid(org.olat.core.gui.components.form.flexible.FormItem, java.util.Map) *///from www . j a va2s. com @SuppressWarnings({ "unchecked" }) @Override public boolean isValid(final FormItem formItem, final Map formContext) { boolean result; final TextElement textElement = (TextElement) formItem; OLog log = Tracing.createLoggerFor(this.getClass()); if (StringHelper.containsNonWhitespace(textElement.getValue())) { // Use an HttpClient to fetch a profile information page from MSN. final HttpClient httpClient = HttpClientFactory.getHttpClientInstance(); final HttpClientParams httpClientParams = httpClient.getParams(); httpClientParams.setConnectionManagerTimeout(2500); httpClient.setParams(httpClientParams); final HttpMethod httpMethod = new GetMethod(MSN_NAME_VALIDATION_URL); final NameValuePair idParam = new NameValuePair(MSN_NAME_URL_PARAMETER, textElement.getValue()); httpMethod.setQueryString(new NameValuePair[] { idParam }); // Don't allow redirects since otherwise, we won't be able to get the correct status httpMethod.setFollowRedirects(false); try { // Get the user profile page httpClient.executeMethod(httpMethod); final int httpStatusCode = httpMethod.getStatusCode(); // Looking at the HTTP status code tells us whether a user with the given MSN name exists. if (httpStatusCode == HttpStatus.SC_MOVED_PERMANENTLY) { // If the user exists, we get a 301... result = true; } else if (httpStatusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { // ...and if the user doesn't exist, MSN sends a 500. textElement.setErrorKey("form.name.msn.error", null); result = false; } else { // For HTTP status codes other than 301 and 500 we will assume that the given MSN name is valid, but inform the user about this. textElement.setExampleKey("form.example.msnname.notvalidated", null); log.warn("MSN name validation: Expected HTTP status 301 or 500, but got " + httpStatusCode); result = true; } } catch (final Exception e) { // In case of any exception, assume that the given MSN name is valid (The opposite would block easily upon network problems), and inform the user about // this. textElement.setExampleKey("form.example.msnname.notvalidated", null); log.warn("MSN name validation: Exception: " + e.getMessage()); result = true; } } else { result = true; } log = null; return result; }
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function does the GET http communication to the device * *///from w ww . j ava2s . c o m public byte[] getDataFromService(String service) { byte[] responseBodyB64 = null; int maxNbrGets = 3; int statusCode = 0; // Create an instance of HttpClient. if (client == null) { client = new HttpClient(); } synchronized (client) { // Create a method instance. GetMethod method = new GetMethod("http://" + device.getIP4Address() + service); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Set the right header method.setRequestHeader("Accept", "application/json"); method.addRequestHeader("User-Agent", "TeleHeater/2.2.3"); try { for (int i = 0; i < maxNbrGets && statusCode != HttpStatus.SC_OK; i++) { // Execute the method. statusCode = client.executeMethod(method); // Check the status switch (statusCode) { case HttpStatus.SC_OK: break; case HttpStatus.SC_INTERNAL_SERVER_ERROR: /* Unknown problem with the device, wait and try again */ logger.warn("HTTP GET failed: 500, internal server error, repeating.. "); Thread.sleep(2000L); continue; case HttpStatus.SC_FORBIDDEN: /* Service is available but not readable */ byte[] test = new byte[1]; return test; default: logger.error("HTTP GET failed: {}", method.getStatusLine()); return null; } } device.setCharSet(method.getResponseCharSet()); // Read the response body. responseBodyB64 = ByteStreams.toByteArray(method.getResponseBodyAsStream()); } catch (HttpException e) { logger.error("Fatal protocol violation: {}", e.getMessage()); } catch (InterruptedException e) { logger.error("Sleep was interrupted: {}", e.getMessage()); } catch (IOException e) { logger.error("Fatal transport error: {}", e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return responseBodyB64; } }
From source file:org.openo.gso.roa.impl.DrivermgrRoaModuleImplTest.java
/** * Mock to get rsp throw new application exception<br> * //from w ww . jav a 2s. c o m * @since GSO 0.5 */ private void mockGetRestfulRspException() { new MockUp<RestfulUtil>() { @Mock public RestfulResponse getRemoteResponse(String url, String methodType, RestfulParametes restfulParametes, RestfulOptions options) { throw new ApplicationException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "failed"); } }; }
From source file:org.openo.sdnhub.common.restconf.HttpProxy.java
/** * Authenticate the HTTP request .<br> * * @param authReq HTTP authentication request message * @param request HTTP request message/*from w w w.j a va2 s . co m*/ * @return the HTTP response message * @since SDNHUB 0.5 */ @Override public HTTPReturnMessage restInvoke(HTTPRequestMessage authReq, HTTPRequestMessage request) { HTTPReturnMessage authResponse = new HTTPReturnMessage(); HTTPReturnMessage response = new HTTPReturnMessage(); BufferedReader br = null; try { // Parse out the token_id, and put into the response super.setHttpContentType(MediaType.APPLICATION_JSON); super.setHttpAccept(MediaType.APPLICATION_JSON); sendMsg(authReq, null, authResponse, true); if (HttpCode.isSucess(authResponse.getStatus())) { Map<String, String> tokenMap = new HashMap<>(); tokenMap.put(ACCESS_TOKEN, authResponse.getToken()); super.setHttpContentType(contentType); super.setHttpAccept(contentType); HttpURLConnection conn = sendMsg(request, tokenMap, response, false); LOGGER.info("HttpSender::restInvoke controller status:" + response.getStatus()); if (HttpCode.isSucess(response.getStatus())) { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { br = new BufferedReader(new InputStreamReader(conn.getErrorStream())); LOGGER.warn("HttpSender::restInvoke controller send failed!"); } processReturnMsg(response, br); } else { LOGGER.error("HttpSender::restInvoke controller auth failed!"); throw new ServiceException( "restInvoke controller auth failed! error code is :" + response.getStatus()); } } catch (Exception e) { if (response.getStatus() == 0) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } response.setBody("\"HttpSender::restInvoke controller error! \""); LOGGER.warn("HttpSender::restInvoke controller error! ", e); } finally { IOUtils.closeQuietly(br); } return response; }