List of usage examples for org.apache.commons.httpclient HttpException getMessage
public String getMessage()
From source file:org.dasein.persist.riak.RiakCache.java
@Override public T get(Object keyValue) throws PersistenceException { if (keyValue == null) { return null; }/*from ww w .j a va 2s .c o m*/ final String primaryKey = keyValue.toString(); try { CacheLoader<T> loader; loader = new CacheLoader<T>() { public T load(Object... args) { startCall("loadObject"); try { if (std.isDebugEnabled()) { std.debug("get - cache miss, loading " + primaryKey); } StringBuilder url = new StringBuilder(); url.append(getEndpoint()); url.append("buckets/"); url.append(getBucket()); url.append("/keys/"); url.append(primaryKey); HttpClient client = getClient(); GetMethod get = new GetMethod(url.toString()); int code; try { 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 } } code = client.executeMethod(get); } catch (HttpException e) { throw new RuntimeException("HttpException during GET: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("IOException during GET: " + e.getMessage()); } try { final String body = get.getResponseBodyAsString(); if (wire.isDebugEnabled()) { try { wire.debug("----------------------------------------"); wire.debug(""); wire.debug(get.getStatusLine().getStatusCode() + " " + get.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 null; } throw new RuntimeException(code + ": " + body); } JSONObject ob = new JSONObject(body); String version = "0"; if (ob.has("SCHEMA_VERSION")) { version = ob.getString("SCHEMA_VERSION"); } return toTargetFromJSON(version, ob); } catch (IOException e) { throw new RuntimeException(e); } catch (PersistenceException e) { throw new RuntimeException(e); } catch (JSONException e) { throw new RuntimeException(e); } } finally { endCall("loadObject"); } } }; if (std.isDebugEnabled()) { std.debug("get - looking in cache for " + keyValue); } return getCache().find(getPrimaryKeyField(), keyValue, loader, getPrimaryKeyField(), keyValue); } catch (CacheManagementException e) { throw new PersistenceException(e); } catch (RuntimeException e) { Throwable t = e.getCause(); if (t != null && t instanceof PersistenceException) { throw (PersistenceException) t; } throw new PersistenceException(e); } }
From source file:org.dasein.persist.riak.RiakCache.java
private @Nonnull Iterable<T> list(boolean asCursor, @Nonnull String listEndpoint, final @Nullable JiteratorFilter<T> filter) throws PersistenceException { if (std.isTraceEnabled()) { std.trace("ENTER: " + RiakCache.class.getName() + ".list(" + listEndpoint + ")"); }/* www. jav a 2s. com*/ try { startCall("list"); try { HttpClient client = getClient(); GetMethod get = new GetMethod(listEndpoint); int code; if (wire.isDebugEnabled()) { try { wire.debug(get.getName() + " " + listEndpoint); 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 { final String body = get.getResponseBodyAsString(); try { if (wire.isDebugEnabled()) { wire.debug("----------------------------------------"); wire.debug(""); wire.debug(get.getStatusLine().getStatusCode() + " " + get.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 Collections.emptyList(); } throw new PersistenceException(code + ": " + body); } JSONObject ob = new JSONObject(body); if (ob.has("keys")) { final JSONArray keys = ob.getJSONArray("keys"); final int len = keys.length(); if (asCursor) { CursorPopulator<T> populator = new CursorPopulator<T>(getTarget().getName() + ".list", null) { @Override public void populate(ForwardCursor<T> cursor) { try { for (int i = 0; i < len; i++) { String key = keys.getString(i); T item = get(key); if (item != null) { try { if (filter == null || filter.filter(item)) { cursor.push(item); } } catch (Throwable t) { throw new JiteratorLoadException(t); } } } } catch (JSONException e) { throw new JiteratorLoadException(e); } catch (PersistenceException e) { throw new JiteratorLoadException(e); } } }; populator.populate(); if (filter == null) { populator.setSize(len); } return populator.getCursor(); } else { PopulatorThread<T> populator; populator = new PopulatorThread<T>(new JiteratorPopulator<T>() { public void populate(@Nonnull Jiterator<T> iterator) throws Exception { for (int i = 0; i < len; i++) { String key = keys.getString(i); T item = get(key); if (item != null) { try { if (filter == null || filter.filter(item)) { iterator.push(item); } } catch (Throwable t) { throw new RuntimeException(t); } } } } }); populator.populate(); if (filter == null) { populator.setSize(len); } return populator.getResult(); } } return Collections.emptyList(); } catch (IOException e) { throw new PersistenceException(e); } catch (JSONException e) { throw new PersistenceException(e); } } finally { endCall("list"); } } finally { if (std.isTraceEnabled()) { std.trace("EXIT: " + RiakCache.class.getName() + ".list()"); } } }
From source file:org.dasein.persist.riak.RiakCache.java
@Override public void remove(Transaction xaction, T item) throws PersistenceException { startCall("remove"); try {//from w ww. j a v a2 s . c om StringBuilder url = new StringBuilder(); url.append(getEndpoint()); url.append("buckets/"); url.append(getBucket()); url.append("/keys/"); url.append(getKeyValue(item)); HttpClient client = getClient(); DeleteMethod delete = new DeleteMethod(url.toString()); int code; try { if (wire.isDebugEnabled()) { try { wire.debug(delete.getName() + " " + url.toString()); wire.debug(""); for (Header h : delete.getRequestHeaders()) { wire.debug(h.getName() + ": " + h.getValue()); } wire.debug(""); } catch (Throwable ignore) { // ignore } } code = client.executeMethod(delete); } catch (HttpException e) { throw new PersistenceException("HttpException during GET: " + e.getMessage()); } catch (IOException e) { throw new PersistenceException("IOException during GET: " + e.getMessage()); } try { String body = delete.getResponseBodyAsString(); if (wire.isDebugEnabled()) { try { wire.debug("----------------------------------------"); wire.debug(""); wire.debug(delete.getStatusLine().getStatusCode() + " " + delete.getStatusLine().getReasonPhrase()); wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } catch (Throwable ignore) { // ignore } } if (code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_NOT_FOUND) { throw new PersistenceException(code + ": " + body); } getCache().release(item); } catch (IOException e) { throw new PersistenceException(e); } } finally { endCall("remove"); } }
From source file:org.dbpedia.spotlight.sparql.SparqlQueryExecuter.java
public String request(URL url) throws SparqlExecutionException { GetMethod method = new GetMethod(url.toString()); String response = null;/*from w ww . j a va 2 s . c om*/ // Provide custom retry handler is necessary 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("SparqlQuery failed: " + method.getStatusLine()); throw new SparqlExecutionException(String.format("%s (%s). %s", method.getStatusLine(), method.getURI(), method.getResponseBodyAsString())); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Deal with the response. // Use caution: ensure correct character encoding and is not binary data response = new String(responseBody); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); throw new SparqlExecutionException(e); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); throw new SparqlExecutionException(e); } finally { // Release the connection. method.releaseConnection(); } return response; }
From source file:org.deegree.ogcwebservices.wcs.RemoteWCService.java
/** * performs a GetCoverage request against a remote service. The result contains the Coverage * decoded in the desired format as a byte array. * * @param request// www. ja v a 2 s . co m * GetCoverage request * @return the requested coverage * @throws OGCWebServiceException * if the url in the request is <code>null</code> */ protected Object handleGetCoverage(GetCoverage request) throws OGCWebServiceException { URL url = addresses.get(GETCOVERAGE_NAME); String us = constructRequestURL(request.getRequestParameter(), OWSUtils.validateHTTPGetBaseURL(url.toExternalForm())); LOG.logDebug("remote wcs GetCoverage", us); Object result = null; try { HttpClient client = new HttpClient(); WebUtils.enableProxyUsage(client, new URL(us)); int timeout = 25000; if (properties != null && properties.getProperty("timeout") != null) { timeout = Integer.parseInt(properties.getProperty("timeout")); } LOG.logDebug("timeout is:", timeout); client.getHttpConnectionManager().getParams().setSoTimeout(timeout); GetMethod get = new GetMethod(us); client.executeMethod(get); InputStream is = get.getResponseBodyAsStream(); Header header = get.getResponseHeader("Content-type"); String contentType = header.getValue(); String[] tmp = StringTools.toArray(contentType, ";", true); contentType = tmp[0]; if ("application/vnd.ogc.se_xml".equals(contentType)) { String res = "Remote-WCS message: " + getInputStreamContent(is); throw new OGCWebServiceException("RemoteWCS:handleGetCoverage", res); } else if (MimeTypeMapper.isImageType(contentType) && MimeTypeMapper.isKnownImageType(contentType)) { MemoryCacheSeekableStream mcss = new MemoryCacheSeekableStream(is); RenderedOp rop = JAI.create("stream", mcss); BufferedImage bi = rop.getAsBufferedImage(); mcss.close(); DescribeCoverage dscC = new DescribeCoverage(UUID.randomUUID().toString(), capabilities.getVersion(), new String[] { request.getSourceCoverage() }); CoverageDescription cd = handleDescribeCoverage(dscC); CoverageOffering co = cd.getCoverageOfferings()[0]; result = new ImageGridCoverage(co, request.getDomainSubset().getSpatialSubset().getEnvelope(), bi); } else { // must be something else; e.g. GML or XYZ-text result = getInputStreamContent(is); } } catch (HttpException e) { LOG.logError(e.getMessage(), e); String msg = Messages.getMessage("REMOTEWMS_GETMAP_GENERAL_ERROR", capabilities.getService().getLabel(), us); throw new OGCWebServiceException("RemoteWCS:handleGetCoverage", msg); } catch (IOException e) { LOG.logError(e.getMessage(), e); String msg = Messages.getMessage("REMOTEWMS_GETMAP_GENERAL_ERROR", capabilities.getService().getLabel(), us); throw new OGCWebServiceException("RemoteWCS:handleGetCoverage", msg); } return new ResultCoverage(result, result.getClass(), request.getOutput().getFormat(), request); }
From source file:org.deegree.test.services.util.HTTPTempFile.java
private void doRequest() throws IOException { tmpFile = File.createTempFile("http_tmp_file_", ".bin"); tmpFile.deleteOnExit();//w w w . ja v a 2 s. c o m try { HttpClient client = new HttpClient(); status = client.executeMethod(method); writeStreamToFile(method.getResponseBodyAsStream(), tmpFile); } catch (HttpException e) { throw new IOException(e.getMessage(), e); } }
From source file:org.deri.pipes.endpoints.SindiceProxy.java
public String readHTTP(String url) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method.addRequestHeader("Accept", "application/json"); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); //TODO:set Accept : "Accept: application/json" try {/*from ww w . jav a 2 s. com*/ int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); return null; } // Read the response body. return new String(method.getResponseBody()); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } return null; }
From source file:org.devproof.portal.module.bookmark.service.SynchronizeServiceImpl.java
@Override public DeliciousBean getDataFromDelicious(String username, String password, String tags) { logger.debug("Retrieve data from delicious"); HttpClient httpClient = new HttpClient(); HttpClientParams httpClientParams = new HttpClientParams(); DefaultHttpMethodRetryHandler defaultHttpMethodRetryHandler = new DefaultHttpMethodRetryHandler(0, false); httpClientParams.setParameter("User-Agent", BookmarkConstants.USER_AGENT); httpClientParams.setParameter(HttpClientParams.RETRY_HANDLER, defaultHttpMethodRetryHandler); httpClient.setParams(httpClientParams); httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); String urlTag = ""; if (StringUtils.isNotEmpty(tags)) { urlTag = "tag=" + tags; }/*from w ww . j a v a 2 s . c om*/ HttpMethod method = new GetMethod(BookmarkConstants.DELICIOUS_API + urlTag); method.setDoAuthentication(true); DeliciousBean bean = new DeliciousBean(); try { int httpCode = httpClient.executeMethod(method); bean.setHttpCode(httpCode); if (!bean.hasError()) { XStream xstream = new XStream(new DomDriver()); xstream.alias("posts", DeliciousBean.class); xstream.alias("post", DeliciousPostBean.class); xstream.addImplicitCollection(DeliciousBean.class, "posts"); xstream.useAttributeFor(String.class); xstream.useAttributeFor(Integer.class); bean = (DeliciousBean) xstream.fromXML(method.getResponseBodyAsStream()); bean.setHttpCode(httpCode); } else { bean.setErrorMessage("Unknown Error: Http Status: " + httpCode); } } catch (HttpException e) { bean.setErrorMessage(e.getMessage()); } catch (IOException e) { bean.setErrorMessage(e.getMessage()); } method.releaseConnection(); return bean; }
From source file:org.easyframework.core.crawl.GetSample.java
public static Map<String, String> get(String url) { Map<String, String> result = new HashMap<String, String>(); HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try {//from w w w .j a v a2 s. co m int statusCode = client.executeMethod(method); String charset = method.getResponseCharSet(); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); result.put(GetSample.RESPONSE_TEXT, new String(responseBody, charset)); result.put(GetSample.CHARSET, charset); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { method.releaseConnection(); return result; } }
From source file:org.energy_home.jemma.ah.internal.hac.lib.HacService.java
public boolean postConfiguration(String data) { synchronized (lockHacService) { // url of the energy at home application String applUrl = bc.getProperty("org.energy_home.jemma.energyathome.url"); if (applUrl == null) { applUrl = "http://163.162.180.229:8282/energyathome"; }// w w w .j a va2s .com String wsncId = bc.getProperty("org.telecomitalia.gal.wsnc.id"); if (wsncId == null) { return false; } HttpClient client = new HttpClient(); PostMethod method = new PostMethod(applUrl + "/store?n=" + wsncId); InputStream inputStream = null; method.setRequestEntity(new StringRequestEntity(data)); // Execute the method. int statusCode = 0; try { statusCode = client.executeMethod(method); } catch (HttpException e) { LOG.warn(e.getMessage(), e); return false; } catch (IOException e) { LOG.warn(e.getMessage(), e); return false; } if (statusCode != HttpStatus.SC_OK) { LOG.warn("method failed: " + method.getStatusLine()); return false; } String responseBody = null; try { responseBody = method.getResponseBodyAsString(); } catch (IOException e1) { LOG.warn(e1.getMessage(), e1); return false; } if (LOG.isDebugEnabled()) LOG.debug(new String(responseBody)); return true; } }