Example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

List of usage examples for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getResponseBodyAsStream.

Prototype

public abstract InputStream getResponseBodyAsStream() throws IOException;

Source Link

Usage

From source file:org.deegree.enterprise.servlet.ProxyServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    String url = req.getParameter("URL");
    try {//from  www  . ja va2 s .co  m
        HttpMethod result = HttpUtils.performHttpPost(url, req.getInputStream(), 0, null, null,
                req.getContentType(), req.getCharacterEncoding(), null);
        InputStream in = result.getResponseBodyAsStream();
        IOUtils.getInstance().copyStreams(in, resp.getOutputStream());
        in.close();
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.deegree.igeo.dataadapter.wfs.WFS110DataLoader.java

/**
 * reads data from a WFS and returns the result as feature collection. returned data may be limited by a restricting
 * bounding box and/or a filter expression
 * //from www.ja va 2 s. com
 * @param wfs
 * @param property
 * @param bbox
 * @param query, must not be <code>null</code>
 * @param layer
 * @return feature collection
 */
public FeatureCollection readFeatureCollection(URL wfs, QualifiedName property, Envelope bbox, Query query,
        Layer layer) {

    Filter filter = query.getFilter();

    // if all features shall be loaded wether a filter nor a bbox will be set. On the other
    // a user may has defined a general filter but no spatial restrictions should be used
    // loading data (e.g. a WFSDataSource is not LazyLoading).
    Operation op = null;
    if (bbox != null) {
        PropertyName pn = new PropertyName(property);
        try {
            op = new SpatialOperation(OperationDefines.BBOX, pn,
                    GeometryFactory.createSurface(bbox, bbox.getCoordinateSystem()));
        } catch (GeometryException e) {
            LOG.logError(e.getMessage(), e);
            throw new DataAccessException(Messages.getMessage(Locale.getDefault(), "$DG10020"));
        }
    }
    if (op != null && filter != null) {
        List<Operation> list = new ArrayList<Operation>();
        list.add(op);
        list.add(((ComplexFilter) filter).getOperation());
        op = new LogicalOperation(OperationDefines.AND, list);
        filter = new ComplexFilter(op);
    } else if (op != null && filter == null) {
        filter = new ComplexFilter(op);
    }

    query = Query.create(query.getPropertyNames(), query.getFunctions(), query.getSortProperties(),
            query.getHandle(), query.getFeatureVersion(), query.getTypeNames(), query.getAliases(),
            query.getSrsName(), filter, query.getMaxFeatures(), query.getStartPosition(),
            query.getResultType());
    query.setSrsName(layer.getOwner().getCoordinateSystem().getPrefixedName());

    GetFeature getFeature = GetFeature.create("1.1.0", "99", RESULT_TYPE.RESULTS, GetFeature.FORMAT_GML3, null,
            maxFeatures, 0, -1, -1, new Query[] { query });

    ApplicationContainer<?> appCont = layer.getOwner().getApplicationContainer();
    XMLFragment xml = null;
    try {
        xml = XMLFactory.export(getFeature);
        xml = HttpUtils.addAuthenticationForXML(xml, appCont.getUser(), appCont.getPassword(),
                appCont.getCertificate(wfs.toURI().toASCIIString()));
        if (LOG.getLevel() == ILogger.LOG_DEBUG) {
            LOG.logDebug("GetFeature request: ", xml.getAsString());
        }
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new DataAccessException(Messages.getMessage(Locale.getDefault(), "$DG10021"));
    }

    InputStream is = null;
    try {
        HttpMethod m = HttpUtils.performHttpPost(wfs.toURI().toASCIIString(), xml, timeout, appCont.getUser(),
                appCont.getPassword(), null);
        is = m.getResponseBodyAsStream();
        if (LOG.getLevel() == ILogger.LOG_DEBUG) {
            byte[] bs = IOUtils.getInputStreamBytes(is);
            String s = new String(bs, "UTF-8");
            LOG.logDebug("GetFeature Response", s);
            is = new ByteArrayInputStream(s.getBytes("UTF-8"));
        }
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new DataAccessException(
                Messages.getMessage(Locale.getDefault(), "$DG10022", wfs, xml.getAsString()));
    }
    GMLFeatureCollectionDocument gml = new GMLFeatureCollectionDocument();
    FeatureCollection fc = null;
    try {
        gml.load(is, wfs.toExternalForm());
        fc = gml.parse();
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new DataAccessException(
                Messages.getMessage(Locale.getDefault(), "$DG10023", wfs, xml.getAsString()));
    }

    fc = ensureClockwiseSurfaceOrientation(fc);

    return fc;
}

From source file:org.deegree.ogcwebservices.wass.wss.operation.DoServiceHandler.java

/**
 * This method does the actual request to the secured service. It returns the response of the
 * secured service as an inputstream. It also replace the GetCapabilities request - responses
 * with the facadeurl given by the client.
 *
 * @param request/*from  w ww .  ja  va 2 s .  co  m*/
 *            send by the client a DoService Request.
 * @param securedService
 *            the service for which this wss is proxying, must be put in the deegreeparams of
 *            the configuration file.
 * @param requestedCharset
 *            this wss uses, also read from the deegreeparams in the configuration file.
 * @param timeout
 *            how long to wait for a response. Service dependable therefor also read from the
 *            deegreeparams in the config file.
 * @param securedServiceName
 *            the name of the service for which we are proxying -> config.
 * @return the http response of the secured service as an inputstream.
 * @throws DoServiceException
 *             if an error occurs wile sending the request or treating the response. see
 *             org.deegree.ogcwebservices.csw.manager.CatalogueHarvester#getNextMetadataRecord
 */
public DoServiceResponse sendRequest(DoService request, URL securedService, String requestedCharset,
        int timeout, String securedServiceName) throws DoServiceException {
    if (requestAllowed) {

        Header[] headers = null;
        InputStream body = null;
        Header[] footers = null;
        String proxyRequest = null;
        try {
            proxyRequest = URLDecoder.decode(request.getPayload(), CharsetUtils.getSystemCharset());
        } catch (UnsupportedEncodingException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_INTERNAL", "WSS"));
        }
        LOG.logDebug("encoded proxyrequest: " + request.getPayload() + "\ndecoded proxy: " + proxyRequest);
        String dcp = request.getDcp();
        HttpClient client = new HttpClient();
        client = WebUtils.enableProxyUsage(client, securedService);
        StringRequestEntity requestEntity = null;
        HttpClientParams params = client.getParams();
        params.setSoTimeout(timeout);
        HttpMethod requestMethod = null;
        try {
            String contentType = null;
            for (RequestParameter param : request.getRequestParameters()) {
                if (param.getId().toLowerCase().trim().contains("mime-type"))
                    contentType = param.getParameter();
            }
            requestEntity = new StringRequestEntity(proxyRequest, contentType, requestedCharset);
        } catch (UnsupportedEncodingException e1) {
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_ENCODING_NOT_SUPPORTED", "WSS"));
        }
        if (dcp.equalsIgnoreCase("http_post")) {

            // the url to the service must be written in the deegreeparams in the configuration
            // xml
            requestMethod = new PostMethod(securedService.toExternalForm());
            ((PostMethod) requestMethod).setRequestEntity(requestEntity);
        } else if (dcp.equalsIgnoreCase("http_get")) {
            requestMethod = new GetMethod(securedService.toExternalForm());
            requestMethod.setQueryString(proxyRequest);
        } else {
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_NOT_POST_OR_GET", "WSS"));
        }
        // getDataRequest
        try {
            // make header parameters of the requestParameters.
            for (RequestParameter param : request.getRequestParameters()) {
                if (!param.getId().toLowerCase().trim().contains("mime-type"))// Contenttype
                    requestMethod.addRequestHeader(param.getId(), param.getParameter());
            }
            // Call the secured service
            client.executeMethod(requestMethod);
            headers = requestMethod.getResponseHeaders();
            footers = requestMethod.getResponseFooters();
            body = requestMethod.getResponseBodyAsStream();

            if (body == null)
                throw new DoServiceException(Messages.getMessage("WASS_ERROR_GOT_NO_RESPONSE", "WSS"));
        } catch (HttpException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_EXCEPTION_IN_RESPONSE", "WSS"));
        } catch (IOException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_IN_TRANSPORT", "WSS"));
        }
        try {
            // Replace the given urls with the facadeurls if it is a GetCapabilities request
            if (proxyRequest.trim().contains("GetCapabilities")) {
                Operation[] operations = null;
                OGCCapabilitiesDocument doc = null;
                /*
                 * For now just check these service, others may be "secured" in the future.
                 */
                if ("WFS".equals(securedServiceName)) {
                    doc = new WFSCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    WFSCapabilities cap = (WFSCapabilities) doc.parseCapabilities();
                    operations = cap.getOperationsMetadata().getOperations();
                    replaceFacadeURL(operations, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.wfs.XMLFactory.export(cap);
                } else if (("WMS").equals(securedServiceName)) {
                    doc = new WMSCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    doc = WMSCapabilitiesDocumentFactory.getWMSCapabilitiesDocument(doc.getRootElement());
                    WMSCapabilities cap = (WMSCapabilities) doc.parseCapabilities();
                    org.deegree.owscommon_new.Operation[] ops = cap.getOperationMetadata().getOperations()
                            .toArray(new org.deegree.owscommon_new.Operation[0]);
                    replaceFacadeURL(ops, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.wms.XMLFactory.export(cap);
                } else if (("WCS").equals(securedServiceName)) {
                    doc = new WCSCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    WCSCapabilities cap = (WCSCapabilities) doc.parseCapabilities();
                    operations = cap.getCapabilitiy().getOperations().getOperations();
                    replaceFacadeURL(operations, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.wcs.XMLFactory.export(cap);
                } else if (("CSW").equals(securedServiceName)) {
                    doc = new CatalogueCapabilitiesDocument();
                    doc.load(body, securedService.toExternalForm());
                    CatalogueCapabilities cap = (CatalogueCapabilities) doc.parseCapabilities();
                    operations = cap.getOperationsMetadata().getOperations();
                    replaceFacadeURL(operations, request.getFacadeURL());
                    doc = org.deegree.ogcwebservices.csw.XMLFactory_2_0_0.export(cap, null);
                }

                body = new ByteArrayInputStream(doc.getAsString().getBytes());
            }
        } catch (IOException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_READING_BODY", "WSS"));
        } catch (InvalidCapabilitiesException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_CAPABILITIES_RESPONSE", "WSS"));
        } catch (SAXException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_FACADE_URL", "WSS"));
        } catch (XMLParsingException e) {
            LOG.logError(e.getMessage(), e);
            throw new DoServiceException(Messages.getMessage("WASS_ERROR_READING_BODY", "WSS"));
        }
        return new DoServiceResponse(headers, body, footers);
    }

    return null;
}

From source file:org.deegree.portal.cataloguemanager.control.FindServicesListener.java

/**
 * @param cswAddress/*from  ww  w.j  ava  2s.  c o  m*/
 * @return
 */
@SuppressWarnings("unchecked")
private XMLFragment performQuery(GetRecords getRecords, String cswAddress) throws Exception {
    XMLFragment gr = XMLFactory.exportWithVersion(getRecords);
    LOG.logDebug("GetRecords: ", gr.getAsPrettyString());
    Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
    Map<String, String> map = new HashMap<String, String>();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                && !name.equalsIgnoreCase("user-agent")) {
            map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
        }
    }
    HttpMethod method = HttpUtils.performHttpPost(cswAddress, gr, 60000, null, null, map);
    XMLFragment xml = new XMLFragment();
    xml.load(method.getResponseBodyAsStream(), cswAddress);
    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        LOG.logDebug("GetRecords result: ", xml.getAsPrettyString());
    }
    return xml;
}

From source file:org.deegree.portal.cataloguemanager.control.FullMetadataSetListener.java

/**
 * @param cswAddress//from   w ww .j  a v  a2  s.c om
 * @return
 */
@SuppressWarnings("unchecked")
private XMLFragment performQuery(GetRecords getRecords, String cswAddress) throws Exception {
    XMLFragment gr = XMLFactory.exportWithVersion(getRecords);
    LOG.logDebug("GetRecords: ", gr.getAsPrettyString());
    Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
    Map<String, String> map = new HashMap<String, String>();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                && !name.equalsIgnoreCase("user-agent")) {
            map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
        }
    }
    HttpMethod method = HttpUtils.performHttpPost(cswAddress, gr, 60000, null, null, map);
    XMLFragment xml = new XMLFragment();
    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        String s = FileUtils.readTextFile(method.getResponseBodyAsStream()).toString();
        LOG.logDebug("CSW Address: ", cswAddress);
        LOG.logDebug("Header: ", map);
        LOG.logDebug("GetRecords result: ", s);
        xml.load(new StringReader(s), cswAddress);
    } else {
        xml.load(method.getResponseBodyAsStream(), cswAddress);
    }
    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        LOG.logDebug("GetRecords result: ", xml.getAsPrettyString());
    }
    return xml;
}

From source file:org.deegree.portal.cataloguemanager.control.LoadMetadataSetListener.java

@SuppressWarnings("unchecked")
@Override// ww  w  . j  a va 2  s  .  c om
public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException {

    CatalogueManagerConfiguration config = getCatalogueManagerConfiguration(event);
    Map<String, String> param = event.getParameter();
    LOG.logDebug("load metadataset request param: ", param);
    String charset = event.getCharacterEncoding();
    if (charset == null) {
        charset = Charset.defaultCharset().displayName();
    }

    String s = URLEncoder.encode(param.get(PARAM_ID), charset);
    URL url = new URL(config.getCatalogueURL() + '?' + GRBID + s);
    LOG.logDebug("load metadataset: ", url);
    try {
        Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
        Map<String, String> map = new HashMap<String, String>();
        while (en.hasMoreElements()) {
            String name = (String) en.nextElement();
            if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                    && !name.equalsIgnoreCase("user-agent")) {
                map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
            }
        }
        HttpMethod get = HttpUtils.performHttpGet(url.toExternalForm(), null, 60000, null, null, map);
        xml = new XMLFragment();
        xml.load(get.getResponseBodyAsStream(), url.toExternalForm());
        xml = new XMLFragment(XMLTools.getFirstChildElement(xml.getRootElement()));
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage());
        responseHandler.writeAndClose(true, eb);
        return;
    }
    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        LOG.logDebug(xml.getAsPrettyString());
    }

    event.getSession().setAttribute("MD_TEMPLATE", xml);

    MetadataBean metadata = new MetadataBean();

    if (param.get("ISTEMPLATE") == null || "false".equalsIgnoreCase(param.get("ISTEMPLATE"))) {
        String tmp = getValue(config.getXPath("datasetTitle"));
        if ("".equals(tmp)) {
            tmp = getValue(config.getXPath("seviceTitle"));
        }
        metadata.setDatasetTitle(tmp);
        metadata.setIdentifier(getValue(config.getXPath("identifier")));
        metadata.setAbstract_(getValue(config.getXPath("abstract_")));
    }
    String tmp = getValue(config.getXPath("begin"));
    if (tmp != null && tmp.trim().length() > 0) {
        Calendar cal = TimeTools.createCalendar(tmp);
        metadata.setBegin(toISO(cal));
    }
    metadata.setContactCity(getValue(config.getXPath("contactCity")));
    metadata.setContactCountry(getValue(config.getXPath("contactCountry")));
    metadata.setContactDeliveryPoint(getValue(config.getXPath("contactDeliveryPoint")));
    metadata.setContactEmailAddress(getValue(config.getXPath("contactEmailAddress")));
    metadata.setContactFacsimile(getValue(config.getXPath("contactFacsimile")));
    metadata.setContactIndividualName(getValue(config.getXPath("contactIndividualName")));
    metadata.setContactOrganisationName(getValue(config.getXPath("contactOrganisationName")));
    metadata.setContactPostalCode(getValue(config.getXPath("contactPostalCode")));
    metadata.setContactRole(getValue(config.getXPath("contactRole")));
    metadata.setContactVoice(getValue(config.getXPath("contactVoice")));
    tmp = getValue(config.getXPath("creation"));
    if (tmp != null && tmp.trim().length() > 0) {
        Calendar cal = TimeTools.createCalendar(tmp);
        metadata.setCreation(toISO(cal));
    }
    metadata.setCrs(getValue(config.getXPath("crs")));
    tmp = getValue(config.getXPath("end"));
    if (tmp != null && tmp.trim().length() > 0) {
        Calendar cal = TimeTools.createCalendar(tmp);
        metadata.setEnd(toISO(cal));
    }
    metadata.setGeogrDescription(getValue(config.getXPath("geogrDescription")));
    metadata.setHlevel(getValue(config.getXPath("hlevel")));

    metadata.setKeywords(getValues(config.getXPath("keywords")));
    metadata.setParentId(getValue(config.getXPath("parentId")));
    metadata.setPocCity(getValue(config.getXPath("pocCity")));
    metadata.setPocCountry(getValue(config.getXPath("pocCountry")));
    metadata.setPocDeliveryPoint(getValue(config.getXPath("pocDeliveryPoint")));
    metadata.setPocEmailAddress(getValue(config.getXPath("pocEmailAddress")));
    metadata.setPocFacsimile(getValue(config.getXPath("pocFacsimile")));
    metadata.setPocIndividualName(getValue(config.getXPath("pocIndividualName")));
    metadata.setPocOrganisationName(getValue(config.getXPath("pocOrganisationName")));
    metadata.setPocPostalCode(getValue(config.getXPath("pocPostalCode")));
    metadata.setPocRole(getValue(config.getXPath("pocRole")));
    metadata.setPocVoice(getValue(config.getXPath("pocVoice")));
    tmp = getValue(config.getXPath("publication"));
    if (tmp != null && tmp.trim().length() > 0) {
        Calendar cal = TimeTools.createCalendar(tmp);
        metadata.setPublication(toISO(cal));
    }
    tmp = getValue(config.getXPath("revision"));
    if (tmp != null && tmp.trim().length() > 0) {
        Calendar cal = TimeTools.createCalendar(tmp);
        metadata.setRevision(toISO(cal));
    }
    metadata.setScale(getValue(config.getXPath("scale")));
    metadata.setTopCat(getValue(config.getXPath("topCat")));

    tmp = getValue(config.getXPath("begin"));
    if (tmp.length() == 0) {
        tmp = getValue(config.getXPath("begin2"));
    }
    Calendar cal = TimeTools.createCalendar(tmp);
    metadata.setBegin(toISO(cal));

    tmp = getValue(config.getXPath("end"));
    if (tmp.length() == 0) {
        tmp = getValue(config.getXPath("end2"));
    }
    cal = TimeTools.createCalendar(tmp);
    metadata.setEnd(toISO(cal));
    metadata.setLineage(getValue(config.getXPath("lineage")));

    metadata.setTransferOnline(getValue(config.getXPath("transferOptOnline")));
    metadata.setTransferFormatName(getValue(config.getXPath("transferOptFormatName")));
    metadata.setTransferFormatVersion(getValue(config.getXPath("transferOptFormatVersion")));

    s = getValue(config.getXPath("accessConstraints"));
    if (s == null) {
        s = getValue(config.getXPath("srvAccessConstraints"));
    }
    metadata.setAccessConstraints(s);

    // result page uses UTF-8 encoding
    String charEnc = Charset.defaultCharset().displayName();
    responseHandler.setContentType("application/json; charset=" + charEnc);
    responseHandler.writeAndClose(true, metadata);
}

From source file:org.deegree.portal.cataloguemanager.control.LoadOWSCapabilitiesListener.java

public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException {
    String url = (String) event.getParameter().get("url");
    String version = (String) event.getParameter().get("version");
    String type = (String) event.getParameter().get("type");
    String req = "request=GetCapabilities&service=" + type;
    if (version != null && version.trim().length() > 0) {
        req += ("&version=" + version);
    }//from  ww w  . j  a va  2s  . c o  m
    LOG.logInfo("URL: ", url);
    LOG.logInfo("request: ", req);

    HttpMethod get = HttpUtils.performHttpGet(url, req, 60000, null, null, null);

    // check if correct content type
    String contentType = get.getResponseHeader("Content-Type").getValue();
    if (!contentType.contains("xml")) {
        String msg = "Error: Response Content is " + contentType + " not xml";
        LOG.logError(msg);
        ExceptionBean bean = new ExceptionBean(this.getClass().getName(), msg);
        responseHandler.writeAndClose(true, bean);
        return;
    }

    session = event.getSession();
    InputStream is = get.getResponseBodyAsStream();
    try {
        if (type.equals("WMS")) {
            handleWMS(is, responseHandler);
        } else if (type.equals("WFS")) {
            handleWFS(is, responseHandler);
        } else if (type.equals("WCS")) {
            handleWCS(is, responseHandler);
        } else if (type.equals("CSW")) {
            handleCSW(is, responseHandler);
        } else {
            is.close();
            String msg = "unknow service type requested: " + url;
            LOG.logError(msg);
            ExceptionBean bean = new ExceptionBean(this.getClass().getName(), msg);
            responseHandler.writeAndClose(true, bean);
            return;
        }
    } catch (Exception e) {
        LOG.logError(e);
        ExceptionBean bean = new ExceptionBean(this.getClass().getName(), e.getMessage());
        responseHandler.writeAndClose(true, bean);
    }

}

From source file:org.deegree.portal.standard.csw.control.FullMetadataSetListener.java

/**
 * @param cswAddress/*from  w  w w  . j  a va2  s  . c  o  m*/
 * @return
 */
@SuppressWarnings("unchecked")
private XMLFragment performQuery(String request) throws Exception {
    LOG.logDebug("GetRecordById: ", request);
    Enumeration<String> en = ((HttpServletRequest) getRequest()).getHeaderNames();
    Map<String, String> map = new HashMap<String, String>();
    while (en.hasMoreElements()) {
        String name = (String) en.nextElement();
        if (!name.equalsIgnoreCase("accept-encoding") && !name.equalsIgnoreCase("content-length")
                && !name.equalsIgnoreCase("user-agent")) {
            map.put(name, ((HttpServletRequest) getRequest()).getHeader(name));
        }
    }
    URL url = new URL(request);
    map = KVP2Map.toMap(url.getQuery());
    StringBuilder sb = new StringBuilder(url.toExternalForm().split("\\?")[0]);
    sb.append('?');
    Iterator<String> iter = map.keySet().iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        sb.append(key).append('=')
                .append(URLEncoder.encode(map.get(key), Charset.defaultCharset().displayName()));
        if (iter.hasNext()) {
            sb.append('&');
        }
    }
    HttpMethod method = HttpUtils.performHttpGet(sb.toString(), null, 60000, null, null, map);
    XMLFragment xml = new XMLFragment();
    xml.load(method.getResponseBodyAsStream(), request);
    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        LOG.logDebug("GetRecordById result: ", xml.getAsPrettyString());
    }
    return xml;
}

From source file:org.deegree.portal.standard.nominatim.control.SearchNominatimListener.java

public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException {

    String address = getInitParameter("address");
    String queryString = (String) event.getParameter().get("QUERYSTRING");
    String searchBox = null;//w  w w  . j ava  2s. c  om
    try {
        searchBox = getSearchBox();
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage());
        responseHandler.writeAndClose(true, eb);
        return;
    }

    String charEnc = getRequest().getCharacterEncoding();
    if (charEnc == null) {
        charEnc = Charset.defaultCharset().displayName();
    }
    queryString = "q=" + URLEncoder.encode(queryString, "UTF-8") + "&format=xml&limit=100&viewbox=" + searchBox;
    LOG.logInfo("Nominatim search query: ", address + "?" + queryString);

    HttpMethod method = HttpUtils.performHttpGet(address, queryString, 60000, null, null, null);
    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());
    }
    List<String[]> result = new ArrayList<String[]>(100);
    Map<String, String> bboxes = new HashMap<String, String>(100);
    try {
        List<Node> nodes = XMLTools.getNodes(xml.getRootElement(), "place",
                CommonNamespaces.getNamespaceContext());
        for (Node node : nodes) {
            String place = XMLTools.getNodeAsString(node, "@display_name",
                    CommonNamespaces.getNamespaceContext(), "");
            String osm_id = XMLTools.getNodeAsString(node, "@osm_id", CommonNamespaces.getNamespaceContext(),
                    "");
            result.add(new String[] { place, osm_id });

            String boundingbox = XMLTools.getNodeAsString(node, "@boundingbox",
                    CommonNamespaces.getNamespaceContext(), "");
            bboxes.put(osm_id, boundingbox);
        }
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage());
        responseHandler.writeAndClose(true, eb);
        return;
    }
    HttpSession session = ((HttpServletRequest) getRequest()).getSession(true);
    session.setAttribute("NominatimBBOXES", bboxes);

    // result page uses UTF-8 encoding
    responseHandler.setContentType("application/json; charset=" + charEnc);
    responseHandler.writeAndClose(false, result);
}

From source file:org.deegree.portal.standard.routing.control.CalculateRouteListener.java

private XMLFragment performQuery(ResponseHandler responseHandler, String address)
        throws HttpException, IOException, UnsupportedEncodingException {
    StringBuilder query = new StringBuilder(500);
    query.append("format=kml&layer=mapnik&instructions=1");
    query.append("&flat=").append(requestBean.getStartWGS84().y);
    query.append("&flon=").append(requestBean.getStartWGS84().x);
    query.append("&tlat=").append(requestBean.getEndWGS84().y);
    query.append("&tlon=").append(requestBean.getEndWGS84().x);
    query.append("&v=").append(requestBean.getTransportation());
    query.append("&fast=").append(requestBean.isFastest());

    LOG.logDebug("YOURS query: ", address + "?" + query);

    HttpMethod method = HttpUtils.performHttpGet(address, query.toString(), 60000, null, null, null);

    // get and parse the result that must be an XML document
    // YOURS routing service always returns result in UTF-8 encoding
    InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8");
    XMLFragment xml = new XMLFragment();
    try {//from   w  ww .  ja v  a2 s .  c o  m
        xml.load(isr, address);
    } catch (Exception e) {
        LOG.logError(e.getMessage(), e);
        throw new RuntimeException(e);
    } finally {
        isr.close();
    }

    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        LOG.logDebug(xml.getAsPrettyString());
    }
    return xml;
}