List of usage examples for org.apache.commons.httpclient HttpException getMessage
public String getMessage()
From source file:org.camera.service.CAMERARESTService.java
/** * File & regular parameters are passed as two separate lists and they are treated * little differently. If flPairList is not null or empty then this method uses Part * Object else no./*w w w. j a va2s . co m*/ * @param pmPairList List of the name and value parameters that user has provided * @param flPairList List of the name and value (full file path)of file parameters. * It is essentially a list of files that user wishes to attach. * @return the results after executing the Post service. */ public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList, String serSiteURL) throws IllegalActionException { if (_debugging) { _debug("I AM IN POST METHOD"); } log.debug("I AM IN POST METHOD"); String postAddress = serSiteURL; HttpClient client = new HttpClient(); MultipartPostMethod method = new MultipartPostMethod(postAddress); List<NameValuePair> fullNameValueList = pmPairList; if (flPairList != null && flPairList.size() > 0) { fullNameValueList.addAll(flPairList); int totalSize = fullNameValueList.size(); Part[] parts = new Part[totalSize]; try { for (int i = 0; i < parts.length; i++) { String nm = fullNameValueList.get(i).getName(); String vl = fullNameValueList.get(i).getValue(); if (i > totalSize - flPairList.size() - 1) { System.out.println("FILE NAME: " + nm); File file = getFileObject(vl); System.out.println("FILE NAME: " + file.getName()); parts[i] = new FilePart(nm, file); method.addPart(parts[i]); System.out.println("PARTS: " + i + " " + parts[i].getName()); System.out.println("file Name: " + vl); } else { System.out.println("PARAMETER NAME: " + nm); System.out.println("PARAMETER Value: " + vl); parts[i] = new StringPart(nm, vl); method.addPart(parts[i]); } if (_debugging) { _debug("Value of i: " + i); } } } catch (FileNotFoundException fnfe) { if (_debugging) { _debug("File Not Found Exception: " + fnfe.getMessage()); } fnfe.printStackTrace(); throw new IllegalActionException("File Not Found: " + fnfe.getMessage()); } } else { for (NameValuePair nmPair : fullNameValueList) { method.addParameter(nmPair.getName(), nmPair.getValue()); System.out.println("Name: " + nmPair.getName() + " Value:" + nmPair.getValue()); } } InputStream rstream = null; StringBuilder results = new StringBuilder(); try { messageBldr = new StringBuilder(); messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL) .append(" STATUS Code: "); int statusCode = client.executeMethod(method); messageBldr.append(statusCode); log.debug("DEBUG: " + messageBldr.toString()); System.out.println(messageBldr.toString()); rstream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); log.debug("BEFORE WHILE LOOP"); String s; while ((s = br.readLine()) != null) { results.append(s).append(ServiceUtils.LINESEP); } } catch (HttpException httpe) { if (_debugging) { _debug("Fatal protocol violation: " + httpe.getMessage()); } httpe.printStackTrace(); // return "Protocol Violation"; throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage()); } catch (ConnectException conExp) { if (_debugging) { _debug("Perhaps service not reachable: " + conExp.getMessage()); } conExp.printStackTrace(); throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage()); // return "Perhaps service not reachable"; } catch (IOException ioe) { if (_debugging) { _debug("Fatal transport error: " + ioe.getMessage()); } ioe.printStackTrace(); // return "IOException: Perhaps could not connect to the service."; throw new IllegalActionException("Fatal transport error: " + ioe.getMessage()); } catch (Exception e) { if (_debugging) { _debug("Unknown error: " + e.getMessage()); } e.printStackTrace(); // return "Exception: Unknown type error"; throw new IllegalActionException("Error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return results.toString(); }
From source file:org.camera.service.CAMERARESTService.java
/** * //w ww.j av a 2s. c o m * @param pmPairList List of the name and value parameters that user has provided * through paramInputPort. However in method this list is combined with * the user configured ports and the combined list name value pair parameters are * added to the service URL separated by ampersand. * @param nvPairList List of the name and value parameters that user has provided * @return the results after executing the Get service. */ public String executeGetMethod(List<NameValuePair> nvPairList, String serSiteURL) throws IllegalActionException { if (_debugging) { _debug("I AM IN GET METHOD"); } HttpClient client = new HttpClient(); StringBuilder results = new StringBuilder(); results.append(serSiteURL); //Files cannot be attached with GET List<NameValuePair> fullPairList = nvPairList;// getCombinedPairList(nvPairList); if (fullPairList.size() > 0) { results.append("?"); int pairListSize = fullPairList.size(); for (int j = 0; j < pairListSize; j++) { NameValuePair nvPair = fullPairList.get(j); results.append(nvPair.getName()).append(ServiceUtils.EQUALDELIMITER).append(nvPair.getValue()); if (j < pairListSize - 1) { results.append("&"); } } } if (_debugging) { _debug("RESULTS :" + results.toString()); } // Create a method instance. GetMethod method = new GetMethod(results.toString()); InputStream rstream = null; StringBuilder resultsForDisplay = new StringBuilder(); try { messageBldr = new StringBuilder(); messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL) .append(" STATUS Code: "); int statusCode = client.executeMethod(method); messageBldr.append(statusCode); log.debug("DEBUG: " + messageBldr.toString()); System.out.println(messageBldr.toString()); rstream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(rstream)); String s; while ((s = br.readLine()) != null) { resultsForDisplay.append(s).append(ServiceUtils.LINESEP); } } catch (HttpException httpe) { if (_debugging) { _debug("Fatal protocol violation: " + httpe.getMessage()); } httpe.printStackTrace(); // return "Protocol Violation"; throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage()); } catch (ConnectException conExp) { if (_debugging) { _debug("Perhaps service not reachable: " + conExp.getMessage()); } conExp.printStackTrace(); throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage()); } catch (IOException ioe) { if (_debugging) { _debug("Fatal transport error: " + ioe.getMessage()); } ioe.printStackTrace(); // return "IOException: fatal transport error"; throw new IllegalActionException("Fatal transport error: " + ioe.getMessage()); } catch (Exception e) { if (_debugging) { _debug("Unknown error: " + e.getMessage()); } e.printStackTrace(); // return "Exception: Unknown type error"; throw new IllegalActionException("Error: " + e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return resultsForDisplay.toString(); }
From source file:org.cancergrid.ws.util.HttpContentReader.java
public static String getHttpContent(String httpUrl, String query, Method method) { LOG.debug("getHttpContent(httpUrl): " + httpUrl); LOG.debug("getHttpContent(query): " + query); LOG.debug("getHttpContent(method): " + method); HttpMethod httpMethod = null;//from ww w.j a v a 2 s . c o m if (httpUrl.contains("&")) { httpUrl = httpUrl.replace("&", "&"); } if (query != null && query.length() > 0 && query.startsWith("?") && query.contains("&")) { query = query.replace("&", "&"); } try { //LOG.debug("Querying: " + httpUrl); if (method == Method.GET) { httpMethod = new GetMethod(httpUrl); if (query != null && query.length() > 0) { httpMethod.setQueryString(query); } } else if (method == Method.POST) { httpMethod = new PostMethod(httpUrl); if (query != null && query.length() > 0) { RequestEntity entity = new StringRequestEntity(query, "text/xml", "UTF-8"); ((PostMethod) httpMethod).setRequestEntity(entity); } } httpMethod.setFollowRedirects(true); httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Protocol.registerProtocol("https", new Protocol("https", new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), 443)); HttpClient client = new HttpClient(); int statusCode = client.executeMethod(httpMethod); if (statusCode != HttpStatus.SC_OK) { LOG.error("Method failed: " + httpMethod.getStatusLine()); LOG.error("Error querying: " + httpMethod.getURI().toString()); throw new Exception("Method failed: " + httpMethod.getStatusLine()); } byte[] responseBody = httpMethod.getResponseBody(); return new String(responseBody, "UTF-8"); } catch (HttpException e) { LOG.error("Fatal protocol violation: " + e.getMessage()); } catch (IOException e) { LOG.error("Fatal transport error: " + e.getMessage()); } catch (Exception e) { LOG.error(e.getMessage()); } finally { httpMethod.releaseConnection(); } return null; }
From source file:org.codinjutsu.tools.jenkins.security.BasicSecurityClient.java
private void doAuthentication(URL jenkinsUrl) throws AuthenticationException { if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) { httpClient.getState().setCredentials(new AuthScope(jenkinsUrl.getHost(), jenkinsUrl.getPort()), new UsernamePasswordCredentials(username, password)); }/*from w ww . j a v a 2s . c om*/ httpClient.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(jenkinsUrl.toString()); try { if (isCrumbDataSet()) { post.addRequestHeader(CRUMB_NAME, crumbData); } post.setDoAuthentication(true); int responseCode = httpClient.executeMethod(post); final String responseBody; try (InputStream inputStream = post.getResponseBodyAsStream();) { responseBody = IOUtils.toString(inputStream, post.getResponseCharSet()); } if (responseCode != HttpURLConnection.HTTP_OK) { checkResponse(responseCode, responseBody); } } catch (HttpException httpEx) { throw new ConfigurationException(String.format("HTTP Error during method execution '%s': %s", jenkinsUrl.toString(), httpEx.getMessage()), httpEx); } catch (IOException ioEx) { throw new ConfigurationException(String.format("IO Error during method execution '%s': %s", jenkinsUrl.toString(), ioEx.getMessage()), ioEx); } finally { post.releaseConnection(); } }
From source file:org.codinjutsu.tools.jenkins.security.DefaultSecurityClient.java
private void runMethod(String url, ResponseCollector responseCollector) { PostMethod post = new PostMethod(url); if (isCrumbDataSet()) { post.addRequestHeader(CRUMB_NAME, crumbData); }//from ww w.j a v a 2 s .co m post = addFiles(post); try { if (files.isEmpty()) { httpClient.getParams().setParameter("http.socket.timeout", DEFAULT_SOCKET_TIMEOUT); httpClient.getParams().setParameter("http.connection.timeout", DEFAULT_CONNECTION_TIMEOUT); } else { httpClient.getParams().setParameter("http.socket.timeout", 0); httpClient.getParams().setParameter("http.connection.timeout", 0); } int statusCode = httpClient.executeMethod(post); final String responseBody; try (InputStream inputStream = post.getResponseBodyAsStream();) { responseBody = IOUtils.toString(inputStream, post.getResponseCharSet()); } checkResponse(statusCode, responseBody); if (HttpURLConnection.HTTP_OK == statusCode) { responseCollector.collect(statusCode, responseBody); } if (isRedirection(statusCode)) { responseCollector.collect(statusCode, post.getResponseHeader("Location").getValue()); } } catch (HttpException httpEx) { throw new ConfigurationException( String.format("HTTP Error during method execution '%s': %s", url, httpEx.getMessage()), httpEx); } catch (UnknownHostException uhEx) { throw new ConfigurationException(String.format("Unknown server: %s", uhEx.getMessage()), uhEx); } catch (IOException ioEx) { throw new ConfigurationException( String.format("IO Error during method execution '%s': %s", url, ioEx.getMessage()), ioEx); } finally { post.releaseConnection(); } }
From source file:org.conqat.engine.bugzilla.BugzillaWebScope.java
/** Read bugs from the Bugzilla server. */ protected Set<Bug> obtainBugs() throws ConQATException { // this constructor also works with null values for username/password BugzillaWebClient client = new BugzillaWebClient(serverURL, httpAuthUsername, httpAuthPassword); try {// w w w . j a va2 s.c o m if (username != null && password != null) { client.authenticate(username, password); } return client.query(products, components, statuses); } catch (HttpException e) { throw new ConQATException("Error accessing Bugzilla: " + e.getMessage(), e); } catch (BugzillaException e) { throw new ConQATException("Error accessing Bugzilla: " + e.getMessage(), e); } catch (IOException e) { throw new ConQATException("Error accessing Bugzilla: " + e.getMessage(), e); } }
From source file:org.craftercms.cstudio.share.service.impl.TranslationServiceBingImpl.java
/** * fire the bing service/* ww w . j av a2 s . c om*/ */ protected String fireBingService(String content, String fromLang, String toLang) { String translatedContent = content; HttpClient client = new HttpClient(); String url = getTranslateServiceUrl(); url = url.replace("{appId}", getApiKey()); url = url.replace("{fl}", fromLang); url = url.replace("{tl}", toLang); url = url.replace("{text}", content); GetMethod method = null; try { method = new GetMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + method.getStatusLine()); } else { byte[] responseBody = method.getResponseBody(); translatedContent = new String(responseBody); translatedContent = translatedContent.replaceAll("\\/", "/"); translatedContent = translatedContent.substring(1, translatedContent.length() - 1); } } catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage(), e); } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage(), e); } finally { // Release the connection. method.releaseConnection(); } return translatedContent; }
From source file:org.craftercms.cstudio.share.service.impl.WcmWorkflowServiceImpl.java
private String callRESTService(final String targetURI, final String xmlString) throws Exception { String xmlResponseString = ""; int result = -1; //TODO: Use Alfresco Endpoint instead of httpclient PostMethod postMethod = null;/* ww w.j a va2 s .c o m*/ BufferedReader br = null; HttpClient httpClient = new HttpClient(); // PRECONDITIONS assert targetURI != null && targetURI.trim().length() > 0 : "path must not be null, empty or blank."; // Body postMethod = new PostMethod(targetURI); postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); // Get the Alfresco Ticket SeamlessAppContext context = SeamlessAppContext.currentApplicationContext(); String alfTicketCookie = (String) cookieManager.getCookieValue(context.getRequest(), this.COOKIE_ALFRESCO_TICKET); // Set the Parameter //getMethod.setQueryString(new NameValuePair[] {new NameValuePair("formId", formId)}); postMethod.setQueryString("?xml=" + xmlString + "&" + COOKIE_ALFRESCO_TICKET + "=" + alfTicketCookie); try { result = httpClient.executeMethod(postMethod); if (result == HttpStatus.SC_NOT_IMPLEMENTED) { if (LOGGER.isErrorEnabled()) { LOGGER.error("The POST method is not implemented by this URI"); throw new Exception("The POST method is not implemented by this URI"); } // still consume the response body xmlResponseString = postMethod.getResponseBodyAsString(); } else { if (result == HttpStatus.SC_OK) { br = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream())); String readLine; while (((readLine = br.readLine()) != null)) { xmlResponseString = xmlString + readLine; } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result)); throw new Exception("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result)); } } } } catch (HttpException he) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Push to Alfresco Service Failed due to HttpException: " + he.getMessage(), he); throw he; } } catch (IOException ie) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Push to Alfresco Service Failed due to IOException: " + ie.getMessage(), ie); } } finally { postMethod.releaseConnection(); if (br != null) try { br.close(); } catch (Exception fe) { } } return (xmlResponseString); }
From source file:org.dasein.persist.riak.RiakCache.java
@Override public long count(SearchTerm... terms) throws PersistenceException { if (terms == null || terms.length < 1) { return count(); }//from w w w .j av a 2 s .co m if (wire.isDebugEnabled()) { startCall("count"); } try { String mapFunction = buildMapFunction(true, terms); HashMap<String, Object> request = new HashMap<String, Object>(); HashMap<String, Object> inputs = new HashMap<String, Object>(); terms = matchKeys(inputs, terms); if (inputs.size() < 1) { request.put("inputs", getBucket()); } else { inputs.put("bucket", getBucket()); request.put("inputs", inputs); } ArrayList<Map<String, Object>> query = new ArrayList<Map<String, Object>>(); HashMap<String, Object> maps = new HashMap<String, Object>(); HashMap<String, Object> reduces = new HashMap<String, Object>(); HashMap<String, Object> map = new HashMap<String, Object>(); HashMap<String, Object> reduce = new HashMap<String, Object>(); map.put("language", "javascript"); map.put("source", mapFunction); map.put("keep", true); maps.put("map", map); reduce.put("language", "javascript"); reduce.put("keep", true); reduce.put("name", "Riak.reduceSum"); reduces.put("reduce", reduce); query.add(maps); query.add(reduces); request.put("query", query); String json = (new JSONObject(request)).toString(); HttpClient client = getClient(); PostMethod post = new PostMethod(getEndpoint() + "mapred"); int code; try { post.setRequestEntity(new StringRequestEntity(json, "application/json", "utf-8")); if (wire.isDebugEnabled()) { try { wire.debug(post.getName() + " " + getEndpoint() + "mapred"); wire.debug(""); for (Header h : post.getRequestHeaders()) { wire.debug(h.getName() + ": " + h.getValue()); } wire.debug("Content-length: " + post.getRequestEntity().getContentLength()); wire.debug("Content-type: " + post.getRequestEntity().getContentType()); wire.debug(""); wire.debug(((StringRequestEntity) post.getRequestEntity()).getContent()); wire.debug(""); } catch (Throwable ignore) { // ignore } } code = client.executeMethod(post); } catch (HttpException e) { throw new PersistenceException("HttpException during POST: " + e.getMessage()); } catch (IOException e) { throw new PersistenceException("IOException during POST: " + e.getMessage()); } try { String body = post.getResponseBodyAsString(); try { if (wire.isDebugEnabled()) { wire.debug("----------------------------------------"); wire.debug(""); wire.debug(post.getStatusLine().getStatusCode() + " " + post.getStatusLine().getReasonPhrase()); wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } } catch (Throwable ignore) { // ignore } if (code != HttpStatus.SC_OK) { if (code == HttpStatus.SC_NOT_FOUND) { return 0; } throw new PersistenceException(code + ": " + body); } JSONArray results = new JSONArray(body); return results.getJSONArray(0).getLong(0); } catch (Exception e) { throw new PersistenceException(e); } catch (Throwable t) { throw new PersistenceException(t.getMessage()); } } finally { endCall("count"); } }
From source file:org.dasein.persist.riak.RiakCache.java
private JSONObject findKeysInBucketAsJSON() throws PersistenceException { startCall("findKeysInBucket"); try {/*from www . j a v a2 s . c o m*/ StringBuilder url = new StringBuilder(); url.append(getEndpoint()); url.append("buckets/"); url.append(getBucket()); url.append("/index/$bucket/"); url.append(getBucket()); HttpClient client = getClient(); GetMethod get = new GetMethod(url.toString()); int code; if (wire.isDebugEnabled()) { try { wire.debug(get.getName() + " " + url.toString()); wire.debug(""); for (Header h : get.getRequestHeaders()) { wire.debug(h.getName() + ": " + h.getValue()); } wire.debug(""); } catch (Throwable ignore) { // ignore } } try { code = client.executeMethod(get); } catch (HttpException e) { throw new PersistenceException("HttpException during GET: " + e.getMessage()); } catch (IOException e) { throw new PersistenceException("IOException during GET: " + e.getMessage()); } try { String json = get.getResponseBodyAsString(); try { if (wire.isDebugEnabled()) { wire.debug("----------------------------------------"); wire.debug(""); wire.debug( get.getStatusLine().getStatusCode() + " " + get.getStatusLine().getReasonPhrase()); wire.debug(""); if (json != null) { wire.debug(json); wire.debug(""); } } } catch (Throwable ignore) { // ignore } if (code != HttpStatus.SC_OK) { if (code == HttpStatus.SC_NOT_FOUND) { return new JSONObject("{\"keys\" : []}"); } else { throw new PersistenceException(code + ": " + json); } } return new JSONObject(json); } catch (JSONException e) { throw new PersistenceException(e); } catch (IOException e) { std.error("Failed to load JSON key list from Riak: " + e.getMessage()); throw new PersistenceException(e); } } finally { endCall("findKeysInBucket"); } }