List of usage examples for org.apache.commons.httpclient HttpMethod getStatusText
public abstract String getStatusText();
From source file:org.eclipse.orion.server.cf.live.cflauncher.commands.CreateFolderCommand.java
protected ServerStatus executeMethod(HttpMethod method) throws HttpException, IOException, JSONException { try {/*from ww w .java 2 s . c o m*/ int code = CFActivator.getDefault().getHttpClient().executeMethod(method); if (code == 204) { /* no content response */ return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK); } JSONObject result = new JSONObject(); result.put("response", method.getResponseBodyAsString()); if (code != 200 && code != 201) { // TODO parse error from XML and put in description return HttpUtil.createErrorStatus(Status.ERROR, Integer.toString(code), method.getStatusText()); } return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result); } finally { /* ensure connections are released back to the connection manager */ method.releaseConnection(); } }
From source file:org.exoplatform.bonitaextension.connectors.webdav.common.WebDAVClient.java
/** * To delete either a folder or a file//from www . java2 s .c om * * @param uri * @throws Exception */ /* NOT TESTED public WebDAVResponse deleteItem(String uri) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("deleteItem '" + uri +"'"); } DeleteMethod httpMethod = new DeleteMethod(uri); client.executeMethod(httpMethod); WebDAVResponse objResponse = processResponse(httpMethod, true); httpMethod.releaseConnection(); return objResponse; } */ /* NOT TESTED public WebDAVResponse checkout(String uri) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("checkout '" + uri +"'"); } CheckoutMethod httpMethod = new CheckoutMethod(uri); client.executeMethod(httpMethod); WebDAVResponse objResponse = processResponse(httpMethod, true); httpMethod.releaseConnection(); return objResponse; } */ /* NOT TESTED public WebDAVResponse checkin(String uri) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("checkin '" + uri +"'"); } CheckinMethod httpMethod = new CheckinMethod(uri); client.executeMethod(httpMethod); WebDAVResponse objResponse = processResponse(httpMethod, true); httpMethod.releaseConnection(); return objResponse; } */ /* NOT TESTED public WebDAVResponse cancelCheckout(String uri) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("cancelCheckout '" + uri +"'"); } UncheckoutMethod httpMethod = new UncheckoutMethod(uri); client.executeMethod(httpMethod); WebDAVResponse objResponse = processResponse(httpMethod, true); httpMethod.releaseConnection(); return objResponse; } */ /* NOT TESTED public WebDAVResponse report(String uri) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("report '" + uri +"'"); } ReportInfo reportInfo = new ReportInfo(ReportType.VERSION_TREE); ReportMethod httpMethod = new ReportMethod(uri, reportInfo); client.executeMethod(httpMethod); WebDAVResponse objResponse = processResponse(httpMethod, false); MultiStatus multiStatus = httpMethod.getResponseBodyAsMultiStatus(); MultiStatusResponse responses[] = multiStatus.getResponses(); String responseAsString = ""; for (int i = 0; i < responses.length; i++) { responseAsString += responses[i].getHref() + "\n"; } objResponse.setResponse(responseAsString); httpMethod.releaseConnection(); return objResponse; } */ /* NOT TESTED public WebDAVResponse versionControl(String uri) throws Exception { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("versionControl '" + uri +"'"); } VersionControlMethod httpMethod = new VersionControlMethod(uri); client.executeMethod(httpMethod); WebDAVResponse objResponse = processResponse(httpMethod, true); httpMethod.releaseConnection(); return objResponse; } */ private WebDAVResponse processResponse(HttpMethod httpMethod, boolean getResponseAsString) { String statusCode = "-1"; if (httpMethod.getStatusCode() > 0) { statusCode = String.valueOf(httpMethod.getStatusCode()); } String statusText = httpMethod.getStatusText(); String responseString = ""; if (getResponseAsString) { try { responseString = httpMethod.getResponseBodyAsString(); if (responseString == null) { responseString = ""; } } catch (IOException e) { if (LOGGER.isLoggable(Level.WARNING)) { LOGGER.warning("IOException while getting responseAsString: " + e.getMessage()); } e.printStackTrace(); } } if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("status CODE: " + statusCode + ", status TEXT: " + statusText + "\n"); } WebDAVResponse response = new WebDAVResponse(statusCode, statusText, responseString); return response; }
From source file:org.geoserver.wps.Execute.java
/** * Executes//w ww . j a v a 2 s . c o m * * @param ref * @return */ Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception { URL destination = new URL(ref.getHref()); HttpMethod method = null; GetMethod refMethod = null; InputStream input = null; InputStream refInput = null; // execute the request try { if ("http".equalsIgnoreCase(destination.getProtocol())) { // setup the client HttpClient client = new HttpClient(); // setting timeouts (30 seconds, TODO: make this configurable) HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(connectionTimeout); params.setConnectionTimeout(connectionTimeout); // TODO: make the http client a well behaved http client, no more than x connections // per server (x admin configurable maybe), persistent connections and so on HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(params); client.setHttpConnectionManager(manager); // prepare either a GET or a POST request if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) { GetMethod get = new GetMethod(ref.getHref()); get.setFollowRedirects(true); method = get; } else { String encoding = ref.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } PostMethod post = new PostMethod(ref.getHref()); Object body = ref.getBody(); if (body == null) { if (ref.getBodyReference() != null) { URL refDestination = new URL(ref.getBodyReference().getHref()); if ("http".equalsIgnoreCase(refDestination.getProtocol())) { // open with commons http client refMethod = new GetMethod(ref.getBodyReference().getHref()); refMethod.setFollowRedirects(true); client.executeMethod(refMethod); refInput = refMethod.getResponseBodyAsStream(); } else { // open with the built-in url management URLConnection conn = refDestination.openConnection(); conn.setConnectTimeout(connectionTimeout); conn.setReadTimeout(connectionTimeout); refInput = conn.getInputStream(); } post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType())); } else { throw new WPSException("A POST request should contain a non empty body"); } } else if (body instanceof String) { post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding)); } else { throw new WPSException("The request body should be contained in a CDATA section, " + "otherwise it will get parsed as XML instead of being preserved as is"); } method = post; } // add eventual extra headers if (ref.getHeader() != null) { for (Iterator it = ref.getHeader().iterator(); it.hasNext();) { HeaderType header = (HeaderType) it.next(); method.setRequestHeader(header.getKey(), header.getValue()); } } int code = client.executeMethod(method); if (code == 200) { input = method.getResponseBodyAsStream(); } else { throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error " + code + ": " + method.getStatusText()); } } else { // use the normal url connection methods then... URLConnection conn = destination.openConnection(); conn.setConnectTimeout(connectionTimeout); conn.setReadTimeout(connectionTimeout); input = conn.getInputStream(); } // actually parse teh data if (input != null) { return ppio.decode(input); } else { throw new WPSException("Could not find a mean to read input " + inputId); } } finally { // make sure to close the connection and streams no matter what if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } if (refMethod != null) { refMethod.releaseConnection(); } } }
From source file:org.geoserver.wps.executor.RemoteRequestInputProvider.java
@Override protected Object getValueInternal(ProgressListener listener) throws Exception { InputReferenceType ref = input.getReference(); URL destination = new URL(ref.getHref()); HttpMethod method = null; GetMethod refMethod = null;/*from www . java 2s .co m*/ InputStream input = null; InputStream refInput = null; // execute the request listener.started(); try { if ("file".equalsIgnoreCase(destination.getProtocol())) { File file = DataUtilities.urlToFile(destination); if (maxSize > 0 && maxSize < file.length()) { throw new WPSException("Input " + getInputId() + " size " + file.length() + " exceeds maximum allowed size of " + maxSize, "NoApplicableCode", getInputId()); } input = new FileInputStream(file); } else if ("http".equalsIgnoreCase(destination.getProtocol())) { // setup the client HttpClient client = new HttpClient(); // setting timeouts (30 seconds, TODO: make this configurable) HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(timeout); params.setConnectionTimeout(timeout); // TODO: make the http client a well behaved http client, no more than x connections // per server (x admin configurable maybe), persistent connections and so on HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(params); client.setHttpConnectionManager(manager); // prepare either a GET or a POST request if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) { GetMethod get = new GetMethod(ref.getHref()); get.setFollowRedirects(true); method = get; } else { String encoding = ref.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } PostMethod post = new PostMethod(ref.getHref()); Object body = ref.getBody(); if (body == null) { if (ref.getBodyReference() != null) { URL refDestination = new URL(ref.getBodyReference().getHref()); if ("http".equalsIgnoreCase(refDestination.getProtocol())) { // open with commons http client refMethod = new GetMethod(ref.getBodyReference().getHref()); refMethod.setFollowRedirects(true); client.executeMethod(refMethod); refInput = refMethod.getResponseBodyAsStream(); } else { // open with the built-in url management URLConnection conn = refDestination.openConnection(); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); refInput = conn.getInputStream(); } post.setRequestEntity( new InputStreamRequestEntity(refInput, complexPPIO.getMimeType())); } else { throw new WPSException("A POST request should contain a non empty body"); } } else if (body instanceof String) { post.setRequestEntity( new StringRequestEntity((String) body, complexPPIO.getMimeType(), encoding)); } else { throw new WPSException("The request body should be contained in a CDATA section, " + "otherwise it will get parsed as XML instead of being preserved as is"); } method = post; } // add eventual extra headers if (ref.getHeader() != null) { for (Iterator it = ref.getHeader().iterator(); it.hasNext();) { HeaderType header = (HeaderType) it.next(); method.setRequestHeader(header.getKey(), header.getValue()); } } int code = client.executeMethod(method); if (code == 200) { try { Header length = method.getResponseHeader("Content-Lenght"); if (maxSize > 0 && length != null && Long.parseLong(length.getValue()) > maxSize) { throw new WPSException( "Input " + getInputId() + " size " + length.getValue() + " exceeds maximum allowed size of " + maxSize + " according to HTTP Content-Lenght response header", "NoApplicableCode", getInputId()); } } catch (NumberFormatException e) { LOGGER.log(Level.FINE, "Failed to parse content lenght to check input limits respect, " + "moving on and checking data as it comes in", e); } input = method.getResponseBodyAsStream(); if (maxSize > 0) { input = new MaxSizeInputStream(input, getInputId(), maxSize); } } else { throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error " + code + ": " + method.getStatusText()); } } else { // use the normal url connection methods then... URLConnection conn = destination.openConnection(); conn.setConnectTimeout(timeout); conn.setReadTimeout(timeout); input = conn.getInputStream(); if (maxSize > 0) { input = new MaxSizeInputStream(input, getInputId(), maxSize); } } // actually parse the data if (input != null) { CancellingInputStream is = new CancellingInputStream(input, listener); return complexPPIO.decode(is); } else { throw new WPSException("Could not find a mean to read input " + inputId); } } finally { listener.progress(100); listener.complete(); // make sure to close the connection and streams no matter what if (refInput != null) { refInput.close(); } if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } if (refMethod != null) { refMethod.releaseConnection(); } } }
From source file:org.geoserver.wps.executor.SimpleInputProvider.java
/** * Executes// ww w . jav a 2s. co m * * @param ref * @return */ Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception { URL destination = new URL(ref.getHref()); HttpMethod method = null; GetMethod refMethod = null; InputStream input = null; InputStream refInput = null; // execute the request try { if ("http".equalsIgnoreCase(destination.getProtocol())) { // setup the client HttpClient client = new HttpClient(); // setting timeouts (30 seconds, TODO: make this configurable) HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setSoTimeout(executor.getConnectionTimeout()); params.setConnectionTimeout(executor.getConnectionTimeout()); // TODO: make the http client a well behaved http client, no more than x connections // per server (x admin configurable maybe), persistent connections and so on HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(params); client.setHttpConnectionManager(manager); // prepare either a GET or a POST request if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) { GetMethod get = new GetMethod(ref.getHref()); get.setFollowRedirects(true); method = get; } else { String encoding = ref.getEncoding(); if (encoding == null) { encoding = "UTF-8"; } PostMethod post = new PostMethod(ref.getHref()); Object body = ref.getBody(); if (body == null) { if (ref.getBodyReference() != null) { URL refDestination = new URL(ref.getBodyReference().getHref()); if ("http".equalsIgnoreCase(refDestination.getProtocol())) { // open with commons http client refMethod = new GetMethod(ref.getBodyReference().getHref()); refMethod.setFollowRedirects(true); client.executeMethod(refMethod); refInput = refMethod.getResponseBodyAsStream(); } else { // open with the built-in url management URLConnection conn = refDestination.openConnection(); conn.setConnectTimeout(executor.getConnectionTimeout()); conn.setReadTimeout(executor.getConnectionTimeout()); refInput = conn.getInputStream(); } post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType())); } else { throw new WPSException("A POST request should contain a non empty body"); } } else if (body instanceof String) { post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding)); } else { throw new WPSException("The request body should be contained in a CDATA section, " + "otherwise it will get parsed as XML instead of being preserved as is"); } method = post; } // add eventual extra headers if (ref.getHeader() != null) { for (Iterator it = ref.getHeader().iterator(); it.hasNext();) { HeaderType header = (HeaderType) it.next(); method.setRequestHeader(header.getKey(), header.getValue()); } } int code = client.executeMethod(method); if (code == 200) { input = method.getResponseBodyAsStream(); } else { throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error " + code + ": " + method.getStatusText()); } } else { // use the normal url connection methods then... URLConnection conn = destination.openConnection(); conn.setConnectTimeout(executor.getConnectionTimeout()); conn.setReadTimeout(executor.getConnectionTimeout()); input = conn.getInputStream(); } // actually parse teh data if (input != null) { return ppio.decode(input); } else { throw new WPSException("Could not find a mean to read input " + inputId); } } finally { // make sure to close the connection and streams no matter what if (input != null) { input.close(); } if (method != null) { method.releaseConnection(); } if (refMethod != null) { refMethod.releaseConnection(); } } }
From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java
public Collection<Location> find(String location) { final String url = FIND_URL.replace("@KEY@", key).replace("@QUERY@", QuietUrlCodec.encode(location, Constants.URL_ENCODING)); HttpMethod getMethod = new GetMethod(url); InputStream inputStream = null; try {//w ww .java2 s . c o m // Execute the method. int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { final String statusText = getMethod.getStatusText(); throw new DataRetrievalFailureException( "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'"); } // Read the response body inputStream = getMethod.getResponseBodyAsStream(); List<Location> locations = deserializeSearchResults(inputStream); return locations; } catch (HttpException e) { throw new RuntimeException( "http protocol exception while getting data from weather service from: " + url, e); } catch (IOException e) { throw new RuntimeException("IO exception while getting data from weather service from: " + url, e); } catch (JAXBException e) { throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e); } finally { //try to close the inputstream IOUtils.closeQuietly(inputStream); //release the connection getMethod.releaseConnection(); } }
From source file:org.jasig.portlet.weather.dao.worldwide.WorldWeatherOnlineDaoImpl.java
protected Object getAndDeserialize(String url, TemperatureUnit unit) { HttpMethod getMethod = new GetMethod(url); InputStream inputStream = null; try {//from w ww .j ava 2 s . c o m // Execute the method. int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { final String statusText = getMethod.getStatusText(); throw new DataRetrievalFailureException( "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'"); } // Read the response body inputStream = getMethod.getResponseBodyAsStream(); Weather weather = deserializeWeatherResult(inputStream, unit); return weather; } catch (HttpException e) { throw new RuntimeException( "http protocol exception while getting data from weather service from: " + url, e); } catch (IOException e) { throw new RuntimeException("IO exception while getting data from weather service from: " + url, e); } catch (JAXBException e) { throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e); } catch (ParseException e) { throw new RuntimeException("Parsing exception while getting data from weather service from: " + url, e); } finally { //try to close the inputstream IOUtils.closeQuietly(inputStream); //release the connection getMethod.releaseConnection(); } }
From source file:org.jasig.portlet.weather.dao.yahoo.YahooWeatherDaoImpl.java
public Collection<Location> find(String location) { if ((key == null) || (key.length() == 0)) { MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable( new String[] { ERR_API_MISSING_KEY, ERR_GENERAL_KEY }); throw new InvalidConfigurationException(messageSource.getMessage(resolvable, Locale.getDefault())); }/*from w ww . ja v a2 s.c om*/ final String url = FIND_URL.replace("@KEY@", key).replace("@QUERY@", QuietUrlCodec.encode(location, Constants.URL_ENCODING)); HttpMethod getMethod = new GetMethod(url); InputStream inputStream = null; try { // Execute the method. int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { final String statusText = getMethod.getStatusText(); throw new DataRetrievalFailureException( "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'"); } // Read the response body inputStream = getMethod.getResponseBodyAsStream(); List<Location> locations = locationParsingService.parseLocations(inputStream); return locations; } catch (HttpException e) { throw new RuntimeException( "http protocol exception while getting data from weather service from: " + url, e); } catch (IOException e) { throw new RuntimeException("IO exception while getting data from weather service from: " + url, e); } finally { //try to close the inputstream IOUtils.closeQuietly(inputStream); //release the connection getMethod.releaseConnection(); } }
From source file:org.jasig.portlet.weather.dao.yahoo.YahooWeatherDaoImpl.java
protected Object getAndDeserialize(String url) { HttpMethod getMethod = new GetMethod(url); InputStream inputStream = null; try {/*from w w w .j av a2s . c om*/ // Execute the method. int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { final String statusText = getMethod.getStatusText(); throw new DataRetrievalFailureException( "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'"); } // Read the response body inputStream = getMethod.getResponseBodyAsStream(); return weatherParsingService.parseWeather(inputStream); } catch (HttpException e) { throw new RuntimeException( "http protocol exception while getting data from weather service from: " + url, e); } catch (IOException e) { throw new RuntimeException("IO exception while getting data from weather service from: " + url, e); } finally { //try to close the inputstream IOUtils.closeQuietly(inputStream); //release the connection getMethod.releaseConnection(); } }
From source file:org.jbpm.process.workitem.rest.RESTWorkItemHandler.java
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { // extract required parameters String urlStr = (String) workItem.getParameter("Url"); String method = (String) workItem.getParameter("Method"); if (urlStr == null) { throw new IllegalArgumentException("Url is a required parameter"); }//w w w .j a v a 2 s . com if (method == null || method.trim().length() == 0) { method = "GET"; } Map<String, Object> params = workItem.getParameters(); // optional timeout config parameters, defaulted to 60 seconds Integer connectTimeout = (Integer) params.get("ConnectTimeout"); if (connectTimeout == null) connectTimeout = 60000; Integer readTimeout = (Integer) params.get("ReadTimeout"); if (readTimeout == null) readTimeout = 60000; HttpClient httpclient = new HttpClient(); httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectTimeout); httpclient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout); HttpMethod theMethod = null; if ("GET".equals(method)) { theMethod = new GetMethod(urlStr); } else if ("POST".equals(method)) { theMethod = new PostMethod(urlStr); setBody(theMethod, params); } else if ("PUT".equals(method)) { theMethod = new PutMethod(urlStr); setBody(theMethod, params); } else if ("DELETE".equals(method)) { theMethod = new DeleteMethod(urlStr); } else { throw new IllegalArgumentException("Method " + method + " is not supported"); } doAuthorization(httpclient, theMethod, params); try { int responseCode = httpclient.executeMethod(theMethod); Map<String, Object> results = new HashMap<String, Object>(); if (responseCode >= 200 && responseCode < 300) { theMethod.getResponseBody(); postProcessResult(theMethod.getResponseBodyAsString(), results); results.put("StatusMsg", "request to endpoint " + urlStr + " successfully completed " + theMethod.getStatusText()); } else { logger.warn("Unsuccessful response from REST server (status {}, endpoint {}, response {}", responseCode, urlStr, theMethod.getResponseBodyAsString()); results.put("StatusMsg", "endpoint " + urlStr + " could not be reached: " + theMethod.getResponseBodyAsString()); } results.put("Status", responseCode); // notify manager that work item has been completed manager.completeWorkItem(workItem.getId(), results); } catch (Exception e) { handleException(e); } finally { theMethod.releaseConnection(); } }