List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream
public abstract InputStream getResponseBodyAsStream() throws IOException;
From source file:org.deegree.portal.standard.routing.control.ValidateGeographicNameListener.java
public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException { // 1.read out request and configuration parameters // address of the nominatim web application String address = getInitParameter("address"); // location name we will send to nominatim String queryString = (String) event.getParameter().get("QUERYSTRING"); // we use the bounding box of the current map to limit nominatim search area // the will make searches faster and reduce number of useless matches String searchBox = null;//from w w w.ja va2s .com try { searchBox = getSearchBox(); } catch (Exception e) { LOG.logError(e.getMessage(), e); ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage()); responseHandler.writeAndClose(true, eb); return; } // 2.create a q request against Nominatim gazetteer service queryString = "q=" + URLEncoder.encode(queryString, "UTF-8") + "&bounded=1&osm_type=N&format=xml&limit=50&viewbox=" + searchBox; LOG.logDebug("Nominatim search query: ", address + "?" + queryString); // 3.perform request against Nominatim gazetteer service HttpMethod method = HttpUtils.performHttpGet(address, queryString, 60000, null, null, null); // 4.receive the result and parse it as an XML document InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"); XMLFragment xml = new XMLFragment(); try { xml.load(isr, address); } catch (Exception e) { LOG.logError(e.getMessage(), e); ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage()); responseHandler.writeAndClose(true, eb); return; } finally { isr.close(); } if (LOG.getLevel() == ILogger.LOG_DEBUG) { LOG.logDebug(xml.getAsPrettyString()); } // 5. parse the content of the result document and create response to the client // // extract required information from the nominatim result XML. This is: // - names of the locations (we possibly have more than one matching location) // - bounding box of the locations // Form the bounding box we can calculate its center that will be used for // displaying the location and calculating a route List<String[]> result = new ArrayList<String[]>(50); HttpSession session = ((HttpServletRequest) getRequest()).getSession(true); ViewContext vc = (ViewContext) session.getAttribute(Constants.CURRENTMAPCONTEXT); CoordinateSystem modelCrs = vc.getGeneral().getBoundingBox()[0].getCoordinateSystem(); GeoTransformer gt = new GeoTransformer(modelCrs); try { NamespaceContext nsc = CommonNamespaces.getNamespaceContext(); List<Node> nodes = XMLTools.getNodes(xml.getRootElement(), "place", nsc); for (Node node : nodes) { String place = XMLTools.getNodeAsString(node, "@display_name", nsc, ""); // get location of an object in geographic and map CRS double lat = XMLTools.getNodeAsDouble(node, "@lat", nsc, 0); double lon = XMLTools.getNodeAsDouble(node, "@lon", nsc, 0); // location coordinates mst be available in: // - WGS84 for route calculation // - in CRS of current map model for displaying in the client Point point = GeometryFactory.createPoint(lon, lat, CRSFactory.EPSG_4326); Point pointMap = point; if (!modelCrs.equals(CRSFactory.EPSG_4326)) { pointMap = (Point) gt.transform(point); } String p = point.getX() + " " + point.getY(); String pm = pointMap.getX() + " " + pointMap.getY(); // add location to the result array result.add(new String[] { place, p, pm }); } } catch (Exception e) { LOG.logError(e.getMessage(), e); ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage()); responseHandler.writeAndClose(true, eb); return; } // 6.return response back to the client String charEnc = getRequest().getCharacterEncoding(); if (charEnc == null) { charEnc = Charset.defaultCharset().displayName(); } responseHandler.setContentType("application/json; charset=" + charEnc); responseHandler.writeAndClose(false, result); }
From source file:org.deegree.portal.standard.wms.control.GetFeatureInfoListener.java
private Table readDataFromWFS(Map<String, Object> parameter, String request, String url) throws HttpException, IOException, SAXException, XMLParsingException, TransformerException { XMLFragment xml = new XMLFragment(); HttpMethod method = HttpUtils.performHttpGet(url, request, timeout, null, null, null); xml.load(method.getResponseBodyAsStream(), url); if (xslt != null) { // if a XSLT for transforming get feature info results has been defined: // perform a transformation to ensure that feature info result is a valid // GML document xml = xslt.transform(xml);// w w w . ja v a 2 s .c o m } if (LOG.isDebug()) { LOG.logDebug("feature info performed : ", url + " " + request); LOG.logDebug("feature info result : ", xml.getAsPrettyString()); } NamespaceContext nsc = CommonNamespaces.getNamespaceContext(); List<Element> featureMember = XMLTools.getElements(xml.getRootElement(), "//gml:featureMember", nsc); if (featureMember.size() == 0) { featureMember = XMLTools.getElements(xml.getRootElement(), "//gml3_2:featureMember", nsc); } // get column header List<String> header = new ArrayList<String>(); for (int i = 0; i < featureMember.size(); i++) { // get feature; there should be exactly one ElementList el = XMLTools.getChildElements(featureMember.get(i)); if (el.getLength() > 0 && el.item(0) != null) { // get properties ElementList el2 = XMLTools.getChildElements(el.item(0)); for (int j = 0; j < el2.getLength(); j++) { String name = el2.item(j).getLocalName(); if (!header.contains(name) && !"boundedBy".equalsIgnoreCase(name)) { header.add(name); } } } } // remember index positions (column number) for each property (name) Map<String, Integer> map = new HashMap<String, Integer>(); for (int i = 0; i < header.size(); i++) { map.put(header.get(i), new Integer(i)); } // get column data String[][] data = new String[featureMember.size()][]; for (int i = 0; i < featureMember.size(); i++) { data[i] = new String[header.size()]; // get feature; there should be exactly one ElementList el = XMLTools.getChildElements(featureMember.get(i)); if (el.getLength() > 0 && el.item(0) != null) { // get properties ElementList el2 = XMLTools.getChildElements(el.item(0)); for (int j = 0; j < el2.getLength(); j++) { String name = el2.item(j).getLocalName(); if (!"boundedBy".equalsIgnoreCase(name)) { int idx = map.get(name); data[i][idx] = XMLTools.getStringValue(el2.item(j)); } } } } Table table = new Table(); table.setName((String) parameter.get("title")); table.setColumns(header.toArray(new String[header.size()])); table.setData(data); return table; }
From source file:org.deegree.tools.metadata.InspireValidator.java
/** * reads a number of random records from a CSW and validates them against INSPIRE metadata validator * //from w w w . jav a 2 s . c o m * @param mr * number of records to be tested */ public void runRandomQuery(String mr) { int maxQueries = 50; if (mr != null) { maxQueries = Integer.parseInt(mr); LOG.logInfo(Messages.get("m1", mr)); } else { LOG.logInfo(Messages.get("m2", mr)); } try { int max = getNumberOfAvailableRecords(); if (maxQueries > max) { maxQueries = max; LOG.logInfo(Messages.get("m3", max)); } // create base GetRecords request without constraint but with startPosition and maxRecords = 1 String s = Messages.get("getRecordsWithoutFilter"); XMLFragment request = new XMLFragment(new StringReader(s), XMLFragment.DEFAULT_URL); Random random = new Random(); outputWriter = new PrintWriter(new File(outputFile)); for (int i = 0; i < maxQueries; i++) { // set index of record to read Node node = XMLTools.getNode(request.getRootElement(), Messages.get("xPathStartPosition"), nsc); node.setNodeValue(Integer.toString(random.nextInt(max) + 1)); HttpMethod m = HttpUtils.performHttpPost(cswAddress, request, 60000, null, null, null); XMLFragment xml = new XMLFragment(); xml.load(m.getResponseBodyAsStream(), cswAddress); List<org.w3c.dom.Element> list = XMLTools.getElements(xml.getRootElement(), Messages.get("xPathMetadata"), nsc); System.out.println(Messages.get("m4", i + 1, maxQueries)); outputWriter.println("---------------------------------------------------------------------"); String id = XMLTools.getNodeAsString(list.get(0), Messages.get("xPathIdentifier"), nsc, "none"); outputWriter.println(Messages.get("m5", id)); validateINSPIRE(list.get(0)); } System.out.println(); } catch (Exception e) { LOG.logError(e); } finally { if (outputWriter != null) { outputWriter.flush(); outputWriter.close(); } } System.out.println(Messages.get("m6", new File(outputFile).getAbsolutePath())); }
From source file:org.deegree.tools.metadata.InspireValidator.java
/** * @return//from w w w .j a v a 2 s . co m * @throws IOException * @throws SAXException */ private int getNumberOfAvailableRecords() throws Exception { String s = Messages.get("getRecordsHits"); XMLFragment xml = new XMLFragment(new StringReader(s), XMLFragment.DEFAULT_URL); HttpMethod m = HttpUtils.performHttpPost(cswAddress, xml, 60000, null, null, null); XMLFragment result = new XMLFragment(); result.load(m.getResponseBodyAsStream(), cswAddress); return XMLTools.getNodeAsInt(result.getRootElement(), Messages.get("xPathNumberOfRecordsMatched"), nsc, 0); }
From source file:org.deegree.tools.metadata.InspireValidator.java
/** * reads a records from a CSW defined by a GetRecord request and validates them against INSPIRE metadata validator * // w w w . ja v a2s . c o m * @param queryFile * reference to GetRecords request */ public void runDefinedQuery(String queryFile) { try { query = new XMLFragment(new File(queryFile)); HttpMethod m = HttpUtils.performHttpPost(cswAddress, query, 60000, null, null, null); XMLFragment xml = new XMLFragment(); xml.load(m.getResponseBodyAsStream(), cswAddress); List<org.w3c.dom.Element> list = XMLTools.getElements(xml.getRootElement(), Messages.get("xPathMetadata"), nsc); outputWriter = new PrintWriter(new File(outputFile)); int cnt = 1; for (org.w3c.dom.Element element : list) { System.out.println(Messages.get("m7", cnt, list.size())); outputWriter.println("---------------------------------------------------------------------"); String id = XMLTools.getNodeAsString(element, Messages.get("xPathIdentifier"), nsc, "none"); outputWriter.println(Messages.get("m8", id)); validateINSPIRE(element); cnt++; } System.out.println(); } catch (Exception e) { LOG.logError(e); } finally { if (outputWriter != null) { outputWriter.flush(); outputWriter.close(); } } System.out.println("report stored at: " + new File(outputFile).getAbsolutePath()); }
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 ww w . ja va 2s .c o m*/ 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.eclipse.e4.opensocial.container.internal.browserHandlers.core.MakeXmlHttpRequestHandler.java
protected String retrieveResponseBody(HttpMethod httpMethod) throws IOException, UnsupportedEncodingException { String responseBodyAsString = ""; InputStream bodyAsStream = httpMethod.getResponseBodyAsStream(); BufferedReader reader = null; StringBuilder sb = new StringBuilder(); String line;/*ww w . j a v a2 s.com*/ try { reader = new BufferedReader(new InputStreamReader(bodyAsStream, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) reader.close(); } responseBodyAsString = sb.toString(); return responseBodyAsString; }
From source file:org.eclipse.e4.ui.internal.gadgets.opensocial.browserfunctions.MakeXmlHttpRequest.java
protected String retrieveResponseBody(HttpMethod httpMethod) throws IOException, UnsupportedEncodingException { String responseBodyAsString = ""; InputStream bodyAsStream = httpMethod.getResponseBodyAsStream(); StringBuilder sb = new StringBuilder(); String line;//from ww w.ja v a 2s . co m try { BufferedReader reader = new BufferedReader(new InputStreamReader(bodyAsStream, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } finally { bodyAsStream.close(); } responseBodyAsString = sb.toString(); return responseBodyAsString; }
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.//from ww w.ja v a 2 s. 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//w w w .java 2 s . c o 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; }