List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER
String RETRY_HANDLER
To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.
Click Source Link
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Perform login/establish a new session. Uses the PIN number and when successful saves the assigned sessionID for * future requests.//w w w .j a va2s .c o m * * @return <code>true</code> if login was successful; <code>false</code> otherwise. * @throws IOException if communication with the radio failed, e.g. because the device is not reachable. */ public boolean doLogin() throws IOException { isLoggedIn = false; // reset login flag if (httpClient == null) { httpClient = new HttpClient(); } final String url = "http://" + hostname + ":" + port + "/fsapi/CREATE_SESSION?pin=" + pin; logger.trace("opening URL:" + url); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Communication with radio failed: " + method.getStatusLine()); if (method.getStatusCode() == 403) { throw new RuntimeException("Radio does not allow connection, maybe wrong pin?"); } throw new IOException("Communication with radio failed, return code: " + statusCode); } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("login response: " + responseBody); } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { logger.trace("login successful"); sessionId = result.getSessionId(); isLoggedIn = true; return true; // login successful :-) } } catch (HttpException he) { logger.debug("Fatal protocol violation: {}", he.toString()); throw he; } catch (IOException ioe) { logger.debug("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } return false; // login not successful }
From source file:org.eclipse.smarthome.binding.fsinternetradio.internal.radio.FrontierSiliconRadioConnection.java
/** * Performs a request to the radio with addition parameters. * * Typically used for changing parameters. * * @param REST/*from www. j av a 2s. co m*/ * API requestString, e.g. "SET/netRemote.sys.power" * @param params * , e.g. "value=1" * @return request result * @throws IOException if the request failed. */ public FrontierSiliconRadioApiResult doRequest(String requestString, String params) throws IOException { // 3 retries upon failure for (int i = 0; i < 2; i++) { if (!isLoggedIn && !doLogin()) { continue; // not logged in and login was not successful - try again! } final String url = "http://" + hostname + ":" + port + "/fsapi/" + requestString + "?pin=" + pin + "&sid=" + sessionId + (params == null || params.trim().length() == 0 ? "" : "&" + params); logger.trace("calling url: '" + url + "'"); final HttpMethod method = new GetMethod(url); method.getParams().setSoTimeout(SOCKET_TIMEOUT); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(2, false)); try { final int statusCode = httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); isLoggedIn = false; method.releaseConnection(); continue; } final String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.trace("got result: " + responseBody); } else { logger.debug("got empty result"); isLoggedIn = false; method.releaseConnection(); continue; } final FrontierSiliconRadioApiResult result = new FrontierSiliconRadioApiResult(responseBody); if (result.isStatusOk()) { return result; } isLoggedIn = false; method.releaseConnection(); continue; // try again } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); isLoggedIn = false; throw he; } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); throw ioe; } finally { method.releaseConnection(); } } isLoggedIn = false; // 3 tries failed. log in again next time, maybe our session went invalid (radio restarted?) return null; }
From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java
/** * Executes the given <code>url</code> with the given <code>httpMethod</code> * //from www. ja va 2 s .c o m * @param httpMethod the HTTP method to use * @param url the url to execute (in milliseconds) * @param httpHeaders optional HTTP headers which has to be set on request * @param content the content to be send to the given <code>url</code> or * <code>null</code> if no content should be send. * @param contentType the content type of the given <code>content</code> * @param timeout the socket timeout to wait for data * @param proxyHost the hostname of the proxy * @param proxyPort the port of the proxy * @param proxyUser the username to authenticate with the proxy * @param proxyPassword the password to authenticate with the proxy * @param nonProxyHosts the hosts that won't be routed through the proxy * @return the response body or <code>NULL</code> when the request went wrong */ public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content, String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser, String proxyPassword, String nonProxyHosts) { HttpClient client = new HttpClient(); // only configure a proxy if a host is provided if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); if (StringUtils.isNotBlank(proxyUser)) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxyPassword)); } } HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url); method.getParams().setSoTimeout(timeout); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); if (httpHeaders != null) { for (String httpHeaderKey : httpHeaders.stringPropertyNames()) { method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey))); } } // add content if a valid method is given ... if (method instanceof EntityEnclosingMethod && content != null) { EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method; eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType)); } Credentials credentials = extractCredentials(url); if (credentials != null) { client.getParams().setAuthenticationPreemptive(true); client.getState().setCredentials(AuthScope.ANY, credentials); } if (logger.isDebugEnabled()) { try { logger.debug("About to execute '" + method.getURI().toString() + "'"); } catch (URIException e) { logger.debug(e.getMessage()); } } try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.warn("Method failed: " + method.getStatusLine()); } String responseBody = IOUtils.toString(method.getResponseBodyAsStream()); if (!responseBody.isEmpty()) { logger.debug(responseBody); } return responseBody; } catch (HttpException he) { logger.error("Fatal protocol violation: {}", he.toString()); } catch (IOException ioe) { logger.error("Fatal transport error: {}", ioe.toString()); } finally { method.releaseConnection(); } return null; }
From source file:org.eclipse.smila.connectivity.framework.crawler.web.http.HttpResponse.java
/** * Sets the http parameters./*from www .j av a 2 s .com*/ * * @param http * the http * @param httpMethod * the http method */ private void setHttpParameters(HttpBase http, HttpMethodBase httpMethod) { httpMethod.setFollowRedirects(false); httpMethod.setRequestHeader("User-Agent", http.getUserAgent()); httpMethod.setRequestHeader("Referer", http.getReferer()); httpMethod.setDoAuthentication(true); for (Header header : http.getHeaders()) { httpMethod.addRequestHeader(header); } final HttpMethodParams params = httpMethod.getParams(); if (http.getUseHttp11()) { params.setVersion(HttpVersion.HTTP_1_1); } else { params.setVersion(HttpVersion.HTTP_1_0); } params.makeLenient(); params.setContentCharset("UTF-8"); if (http.isCookiesEnabled()) { params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); } else { params.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); } params.setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); // the default is to retry 3 times; if // the request body was sent the method is not retried, so there is // little danger in retrying // retries are handled on the higher level params.setParameter(HttpMethodParams.RETRY_HANDLER, null); }
From source file:org.eclipse.swordfish.registry.tooling.popup.actions.UploadJob.java
@Override @SuppressWarnings("unchecked") public IStatus run(IProgressMonitor monitor) { IStatus status = Status.OK_STATUS;/*from w w w . j a va 2s .co m*/ monitor.beginTask(JOB_NAME, structuredSelection.size()); try { HttpClient httpClient = new HttpClient(); HttpMethodRetryHandler retryhandler = new HttpMethodRetryHandler() { /** * {@inheritDoc} */ public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) { return false; } }; final String serviceRegistryURL = Activator.getDefault().getPreferenceStore() .getString(PreferenceConstants.REGISTRY_URL); Iterator selectedObjects = structuredSelection.iterator(); while (selectedObjects.hasNext()) { Object element = selectedObjects.next(); if (element instanceof IFile) { IFile file = (IFile) element; setName(JOB_NAME + ": " + file.getName()); monitor.subTask("Processing " + file.getName()); PutMethod putMethod = new PutMethod(serviceRegistryURL + "/" + file.getName()); putMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); RequestEntity entity = new InputStreamRequestEntity(file.getContents()); putMethod.setRequestEntity(entity); try { int statusCode = httpClient.executeMethod(putMethod); if (statusCode != HttpStatus.SC_OK) { status = new Status(IStatus.ERROR, Activator.getId(), "Error in Service Registry Upload: [" + statusCode + "] " + putMethod.getStatusText()); break; } status = new Status(IStatus.INFO, Activator.getId(), "Response from the Registry: " + putMethod.getResponseBodyAsString()); Activator.getDefault().getLog().log(status); } finally { // Release the connection. putMethod.releaseConnection(); } } monitor.worked(1); } } catch (Exception e) { status = new Status(IStatus.ERROR, Activator.getId(), IStatus.ERROR, e.getClass().getName() + " : " + e.getMessage(), e); } finally { monitor.done(); } return status; }
From source file:org.eclipse.swordfish.tools.deployer.SwordfishClientCommandProvider.java
private PutMethod createPutRequest(String ius, String operation, String profile) { PutMethod putMethod = new PutMethod(targetHost + servletPath + "/" + repository); putMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); putMethod.setRequestHeader(new Header(IU_OPERATION, operation)); String[] iuList = ius.split(","); for (int i = 0; i < iuList.length; i++) { putMethod.setRequestHeader(new Header(IU_ID + i, iuList[i])); }/*from ww w .j a v a2 s. c o m*/ if ((profile != null) && !("".equals(profile))) { putMethod.setRequestHeader(new Header(IU_TARGET_PROFILE, profile)); } return putMethod; }
From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java
public CommonsHttpTransport(Settings settings, String host) { this.settings = settings; httpInfo = host;//from w w w . j a v a 2 s . c om HttpClientParams params = new HttpClientParams(); params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(settings.getHttpRetries(), false) { @Override public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) { if (super.retryMethod(method, exception, executionCount)) { stats.netRetries++; return true; } return false; } }); params.setConnectionManagerTimeout(settings.getHttpTimeout()); params.setSoTimeout((int) settings.getHttpTimeout()); HostConfiguration hostConfig = new HostConfiguration(); hostConfig = setupSSLIfNeeded(settings, hostConfig); hostConfig = setupSocksProxy(settings, hostConfig); Object[] authSettings = setupHttpProxy(settings, hostConfig); hostConfig = (HostConfiguration) authSettings[0]; try { hostConfig.setHost(new URI(escapeUri(host, settings.getNetworkSSLEnabled()), false)); } catch (IOException ex) { throw new EsHadoopTransportException("Invalid target URI " + host, ex); } client = new HttpClient(params, new SocketTrackingConnectionManager()); client.setHostConfiguration(hostConfig); addHttpAuth(settings, authSettings); completeAuth(authSettings); HttpConnectionManagerParams connectionParams = client.getHttpConnectionManager().getParams(); // make sure to disable Nagle's protocol connectionParams.setTcpNoDelay(true); if (log.isTraceEnabled()) { log.trace("Opening HTTP transport to " + httpInfo); } }
From source file:org.esgf.legacydatacart.LegacyOldFileTemplateController.java
private static String querySolrForFiles(String queryString, String dataset_id) { String marker = "\"response\":"; String responseBody = null;//from w w w .j av a 2 s . c o m // create an http client HttpClient client = new HttpClient(); //attact the dataset id to the query string GetMethod method = new GetMethod(searchAPIURL); //add the dataset to the query string queryString += "&dataset_id=" + dataset_id; method.setQueryString(queryString); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // execute the method int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + method.getStatusLine()); } // read the response responseBody = method.getResponseBodyAsString(); } catch (HTTPException e) { LOG.error("Fatal protocol violation"); e.printStackTrace(); } catch (IOException e) { LOG.error("Fatal transport error"); e.printStackTrace(); } finally { method.releaseConnection(); } //just get the important part of the response (i.e. leave off the header and the facet info) int start = responseBody.lastIndexOf(marker) + marker.length(); int end = responseBody.length(); String responseString = responseBody.substring(start, end); return responseString; }
From source file:org.esgf.legacydatacart.LegacyOldFileTemplateController.java
/** * /*from w w w . j a va 2 s . c om*/ * @param queryString * @param dataset_id * @return */ private static String getResponseBodyUsingSearchAPI(String queryString, String dataset_id) { String responseBody = null; System.out.println("In getResponseBodyUsingSearchAPI"); System.out.println("\tDatasetId: " + dataset_id + "\n\tqueryString: " + queryString); // create an http client HttpClient client = new HttpClient(); //attact the dataset id to the query string GetMethod method = null; method = new GetMethod(searchAPIURL); //add distributed search to the query string //queryString += "&distrib=false"; //add the dataset to the query string queryString += "&dataset_id=" + dataset_id;//replica=false";//"&dataset_id=" + "a";//dataset_id; //take this out queryString = "format=application%2Fsolr%2Bjson&type=File&shards=localhost:8983/solr&variable=hus&dataset_id=obs4MIPs.NASA-JPL.AIRS.mon.v1:esg-datanode.jpl.nasa.gov"; System.out.println("\nResponse Body QueryString: " + queryString + "\n"); method.setQueryString(queryString); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // execute the method int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + method.getStatusLine()); } // read the response responseBody = method.getResponseBodyAsString(); } catch (HTTPException e) { LOG.error("Fatal protocol violation"); e.printStackTrace(); } catch (IOException e) { LOG.error("Fatal transport error"); e.printStackTrace(); } finally { method.releaseConnection(); } //System.out.println("-----RESPONSEBODY-----"); //System.out.println(responseBody.substring(startCharIndex, endCharIndex)); //System.out.println("-----END RESPONSEBODY-----"); return responseBody; }
From source file:org.esgf.legacydatacart.LegacyOldFileTemplateController.java
/** (String id) * This method extracts all file records for a given dataset id and assembles them in json format * //w ww. j a va2 s . c o m * @param id Dataset Id * @return Solr response for all files given the dataset id */ private static String getResponseBody(String queryString, String dataset_id) { //System.out.println("In getResponseBody"); String responseBody = null; // create an http client HttpClient client = new HttpClient(); //attact the dataset id to the query string GetMethod method = null; String combinedQueryStr = ""; combinedQueryStr += queryString + "&fq=dataset_id:" + dataset_id + "&wt=json"; method = new GetMethod(solrURL); method.setQueryString(combinedQueryStr); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { // execute the method int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + method.getStatusLine()); } // read the response responseBody = method.getResponseBodyAsString(); } catch (HTTPException e) { LOG.error("Fatal protocol violation"); e.printStackTrace(); } catch (IOException e) { LOG.error("Fatal transport error"); e.printStackTrace(); } finally { method.releaseConnection(); } return responseBody; }