/** * Performs the passed OGCWebServiceRequest by accessing service from the pool and passing the * request to it * * @param request the incoming web service request * @param httpResponse the outgoing web serivce response * @throws ServiceException * @throws OGCWebServiceException */ public void perform(OGCWebServiceRequest request, HttpServletResponse httpResponse) throws ServiceException, OGCWebServiceException { LOG.entering(); LOG.logDebug(StringTools.concat(200, "Performing request: ", request.toString())); OGCWebService service = WPVServiceFactory.createInstance(); try { Object response = service.doService(request); if (response instanceof WPVSCapabilities) { sendGetCapabilitiesResponse(httpResponse, (WPVSCapabilities) response); } else if (response instanceof GetViewResponse) { sendGetViewResponse(httpResponse, (GetViewResponse) response); } else { String s = (response == null ? "null response object" : response.getClass().getName()); // this is not really nice...because excepts get cought later on below throw new OGCWebServiceException( getClass().getName(), StringTools.concat(200, "Unknown response class: '", s, "'.")); } } catch (OGCWebServiceException e) { LOG.logError("Error performing WPVFS request.", e); if (request instanceof GetView && ((GetView) request).getExceptionFormat().equals("INIMAGE")) { sendExceptionImage(httpResponse, e, (GetView) request); } else { sendException(httpResponse, e); } } LOG.exiting(); }
/** * zooms the current map by a factor and recenters it to the point the user has clicked to. * * @throws PortalException * @throws ContextException */ void zoom() throws PortalException, ContextException { ViewContext vc = getCurrentViewContext(portlet.getID()); MapModelAccess mma = new DefaultMapModelAccess(vc); String tmp = parameter.get(PARAM_FACTOR); if (tmp == null) { throw new PortalException("FACTOR must be set for zoom operation!"); } double factor = Double.parseDouble(tmp); tmp = parameter.get(PARAM_CLICKPOINT); if (tmp != null) { // zoom by pixel coordinates double coords[] = StringTools.toArrayDouble(tmp, ","); java.awt.Point point = new java.awt.Point((int) coords[0], (int) coords[1]); vc = mma.zoom(point, factor); } else { // zoom by map coordinates tmp = parameter.get(PARAM_MAPPOINT); if (tmp == null) { throw new PortalException( "at least a CLICKPOINT or a MAPPOINT must be defined for zoom operation!"); } double coords[] = StringTools.toArrayDouble(tmp, ","); Point point = GeometryFactory.createPoint(coords[0], coords[1], null); vc = mma.zoom(point, factor); } setCurrentMapContext(vc, portlet.getID()); }
private void initServices(ServletContext context) throws ServletException { // get list of OGC services String serviceList = this.getRequiredInitParameter(SERVICE); String[] serviceNames = StringTools.toArray(serviceList, ",", false); ServiceLookup lookup = ServiceLookup.getInstance(); for (int i = 0; i < serviceNames.length; i++) { LOG.logInfo( StringTools.concat(100, "---- Initializing ", serviceNames[i].toUpperCase(), " ----")); try { String className = this.getRequiredInitParameter(serviceNames[i] + HANDLER_CLASS); Class<?> handlerClzz = Class.forName(className); // initialize each service factory String s = this.getRequiredInitParameter(serviceNames[i] + HANDLER_CONF); URL serviceConfigurationURL = WebappResourceResolver.resolveFileLocation(s, context, LOG); // set configuration LOG.logInfo( StringTools.concat( 300, "Reading configuration for ", serviceNames[i].toUpperCase(), " from URL: '", serviceConfigurationURL, "'.")); String factoryClassName = SERVICE_FACTORIES_MAPPINGS.get(handlerClzz); Class<?> factory = Class.forName(factoryClassName); Method method = factory.getMethod("setConfiguration", new Class[] {URL.class}); method.invoke(factory, new Object[] {serviceConfigurationURL}); // The csw-ebrim profile adds an alternative service name, it too is registred with the CSW // handler. if ("CSW".equals(serviceNames[i].toUpperCase())) { lookup.addService(OGCRequestFactory.CSW_SERVICE_NAME_EBRIM.toUpperCase(), handlerClzz); } // put handler to available service list lookup.addService(serviceNames[i].toUpperCase(), handlerClzz); LOG.logInfo( StringTools.concat(300, serviceNames[i].toUpperCase(), " successfully initialized.")); } catch (ServletException e) { LOG.logError(e.getMessage(), e); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); LOG.logError(this.produceMessage(ERR_MSG, new Object[] {serviceNames[i]}), e); } catch (Exception e) { LOG.logError("Can't initialize OGC service:" + serviceNames[i], e); } } }
/** * moves the layer passed through by the HTTP request down for one position * * @throws PortalException */ void moveDown() throws PortalException { ViewContext vc = getCurrentViewContext(portlet.getID()); String tmp = parameter.get(PARAM_LAYER); String[] s = StringTools.toArray(tmp, "|", false); LOG.logDebug( StringTools.concat(150, "moving layer: ", s[0], " map model: ", portlet.getID(), " down")); MapModelAccess mma = new DefaultMapModelAccess(vc); try { vc = mma.swapLayers(new QualifiedName(null, s[0], null), new URL(s[1]), "OGC:WMS", false); } catch (MalformedURLException e) { throw new PortalException("no valid URL", e); } setCurrentMapContext(vc, portlet.getID()); }
/** * @param request * @param response @TODO refactor and optimize code for initializing handler */ public void doService(HttpServletRequest request, HttpServletResponse response) { if (response.isCommitted()) { LOG.logWarning("The response object is already committed!"); } long startTime = System.currentTimeMillis(); address = request.getRequestURL().toString(); String service = null; try { OGCWebServiceRequest ogcRequest = OGCRequestFactory.create(request); LOG.logInfo( StringTools.concat( 500, "Handling request '", ogcRequest.getId(), "' from '", request.getRemoteAddr(), "' to service: '", ogcRequest.getServiceName(), "'")); // get service from request service = ogcRequest.getServiceName().toUpperCase(); // get handler instance ServiceDispatcher handler = ServiceLookup.getInstance().getHandler(service, request.getRemoteAddr()); // dispatch request to specific handler handler.perform(ogcRequest, response); } catch (OGCWebServiceException e) { LOG.logError(e.getMessage(), e); sendException(response, e, request, service); } catch (ServiceException e) { if (e.getNestedException() instanceof OGCWebServiceException) { sendException(response, (OGCWebServiceException) e.getNestedException(), request, service); } else { sendException( response, new OGCWebServiceException(this.getClass().getName(), e.getMessage()), request, service); } LOG.logError(e.getMessage(), e); } catch (Exception e) { sendException( response, new OGCWebServiceException(this.getClass().getName(), e.getMessage()), request, service); LOG.logError(e.getMessage(), e); } if (LOG.isDebug()) { LOG.logDebug( "OGCServletController: request performed in " + Long.toString(System.currentTimeMillis() - startTime) + " milliseconds."); } }
/* * (non-Javadoc) * * @see org.deegree.security.AbstractAuthentication#authenticate(java.util.Map) */ public User authenticate(Map<String, String> params) throws WrongCredentialsException { String tmp = initParams.get(INIT_PARAM_PATTERN); List<String> patterns = StringTools.toList(tmp, ",;", true); String ipAddress = params.get(AUTH_PARAM_IPADDRESS); if (ipAddress != null) { for (String p : patterns) { if (ipAddress.matches(p)) { User usr = null; try { SecurityAccessManager sam = SecurityAccessManager.getInstance(); // use matching pattern as username and password usr = sam.getUserByName(p); usr.authenticate(null); } catch (Exception e) { LOG.logError(e.getMessage()); String msg = Messages.getMessage("OWSPROXY_USER_AUTH_ERROR", ipAddress); throw new WrongCredentialsException(msg); } return usr; } } throw new WrongCredentialsException( Messages.getMessage("OWSPROXY_USER_AUTH_ERROR", ipAddress)); } return null; }
/** * returns the service section of the configuration/capabilities. vendorspecific capabilities are * not supported yet * * @param namespaceURI * @return the service section of the configuration/capabilities. vendorspecific capabilities are * not supported yet * @throws InvalidCapabilitiesException */ public Capability getCapabilitySection(URI namespaceURI) throws InvalidCapabilitiesException { try { Node root = this.getRootElement(); Element element = XMLTools.getRequiredChildElement("Capability", namespaceURI, root); Element elem = XMLTools.getRequiredChildElement("Request", namespaceURI, element); OperationsMetadata request = parseOperations(elem, namespaceURI); elem = XMLTools.getRequiredChildElement("Exception", namespaceURI, element); ExceptionFormat eFormat = getExceptionFormat(elem, namespaceURI); // vendorspecific capabilities are not supported yet // elem = XMLTools.getRequiredChildByName( // "VendorSpecificCapabilities", WCSNS, element); String version = element.getAttribute("version"); if (version == null || version.equals("")) { version = this.parseVersion(); } String updateSequence = element.getAttribute("updateSequence"); if (updateSequence == null || updateSequence.equals("")) { updateSequence = this.getRootElement().getAttribute("updateSequence"); } return new Capability(version, updateSequence, request, eFormat, null); } catch (XMLParsingException e) { String s = e.getMessage(); throw new InvalidCapabilitiesException( "Error while parsing the Capability " + "Section of the capabilities\n" + s + StringTools.stackTraceToString(e)); } }
/** * Creates a <code>DCPType</code> object from the passed <code>DCPType</code> element. * <p> * NOTE: Currently the <code>OnlineResources</code> included in the <code>DCPType</code> are * just stored as simple <code>URLs</code> (not as <code>OnLineResource</code> instances)! * <p> * NOTE: In an <code>OGCStandardCapabilitiesDocument</code> the <code>XLinks</code> (the * <code>URLs</code>) are stored in separate elements (<code>OnlineResource</code>), in * an <code>OGCCommonCapabilitiesDocument</code> they are the * <code>Get<code>/<code>Post</code> elements themselves. * * @param element * @param namespaceURI * @return created <code>DCPType</code> * @throws XMLParsingException * @see org.deegree.owscommon.OWSCommonCapabilities */ protected DCPType getDCPType(Element element, URI namespaceURI) throws XMLParsingException { try { Element elem = XMLTools.getRequiredChildElement("HTTP", namespaceURI, element); ElementList el = XMLTools.getChildElements("Get", namespaceURI, elem); URL[] get = new URL[el.getLength()]; for (int i = 0; i < get.length; i++) { Element ell = XMLTools.getRequiredChildElement("OnlineResource", namespaceURI, el.item(i)); String s = XMLTools.getRequiredAttrValue("href", XLNNS, ell); get[i] = new URL(s); } el = XMLTools.getChildElements("Post", namespaceURI, elem); URL[] post = new URL[el.getLength()]; for (int i = 0; i < post.length; i++) { Element ell = XMLTools.getRequiredChildElement("OnlineResource", namespaceURI, el.item(i)); String s = XMLTools.getRequiredAttrValue("href", XLNNS, ell); post[i] = new URL(s); } Protocol protocol = new HTTP(get, post); return new DCPType(protocol); } catch (MalformedURLException e) { throw new XMLParsingException( "Couldn't parse DCPType onlineresoure URL about\n" + StringTools.stackTraceToString(e)); } }
/** * reads a deegree WCS configuration file and performs a DescribeCoverage request Steps: * * <ul> * <li>read configuration file * <li>read a DescribeCoverage request object * <li>perform the request * </ul> */ public void _testDescribeCoverage() { try { WCSConfiguration configuration = WCSConfiguration.create(Configuration.getWCSConfigurationURL()); WCService service = new WCService(configuration); Map<String, String> map = new HashMap<String, String>(); map.put("SERVICE", "WCS"); map.put("REQUEST", "DescribeCoverage"); map.put("VERSION", "1.0.0"); map.put("COVERAGE", "europe"); // StringBuffer sb = new StringBuffer(); // sb.append(Configuration.PROTOCOL + "://" + Configuration.HOST).append(':').append( // Configuration.PORT).append('/').append(Configuration.WCS_WEB_CONTEXT).append( // '/').append(Configuration.WCS_SERVLET).append("?service=WCS&").append( // "request=DescribeCoverage&version=1.0.0&coverage=europe"); DescribeCoverage desc = DescribeCoverage.create(map); CoverageDescription o = (CoverageDescription) service.doService(desc); LOG.logInfo(Arrays.toString(o.getCoverageOfferings())); } catch (Exception e) { fail(StringTools.stackTraceToString(e)); } }
/** * creates a <tt>MetadataLink</tt> object from the passed element. * * @param element * @return created <tt>MetadataLink</tt> * @throws XMLParsingException */ @Override protected MetadataLink parseMetadataLink(Element element) throws XMLParsingException { if (element == null) return null; try { URL reference = new URL(XMLTools.getAttrValue(element, "xlink:href")); String title = XMLTools.getAttrValue(element, "xlink:title"); URI about = new URI(XMLTools.getAttrValue(element, null, "about", null)); String tmp = XMLTools.getAttrValue(element, null, "metadataType", null); MetadataType metadataType = new MetadataType(tmp); return new MetadataLink(reference, title, about, metadataType); } catch (MalformedURLException e) { throw new XMLParsingException( "Couldn't parse metadataLink reference\n" + StringTools.stackTraceToString(e)); } catch (URISyntaxException e) { throw new XMLParsingException( "Couldn't parse metadataLink about\n" + StringTools.stackTraceToString(e)); } }
/** * sets all request attributes required by a map from the passed ViewContext * * @param vc */ private void setMapWindowAttributes() { String tmp = getInitParam(INIT_PANBUTTONS); ArrayList<String> pB = new ArrayList<String>(20); if (tmp != null) { String[] panButtons = StringTools.toArray(tmp, ",;", true); List<String> list = Arrays.asList(panButtons); pB.addAll(list); } setAttributes(pB); }
/** * performs the creation of a <tt>ImageGridCoverage</tt> from the source assigned to this reader. * * @param parameters * @throws IOException */ private GridCoverage performECW(GeneralParameterValueIm[] parameters) throws IOException { BufferedImage bi = null; CoverageOffering co = null; Object[] o = null; ECWReader ecwFile = null; try { String s = ((File) source).getName(); ecwFile = new ECWReader(s); // get the requested dimension in pixels int reqWidth = 0; int reqHeight = 0; for (int i = 0; i < parameters.length; i++) { OperationParameterIm op = (OperationParameterIm) parameters[i].getDescriptor(); String name = op.getName(); if (name.equalsIgnoreCase("WIDTH")) { Object vo = op.getDefaultValue(); reqWidth = ((Integer) vo).intValue(); } else if (name.equalsIgnoreCase("HEIGHT")) { Object vo = op.getDefaultValue(); reqHeight = ((Integer) vo).intValue(); } } // calculate image region of interest o = getECWImageRegion(reqWidth, reqHeight); Envelope envl = (Envelope) o[1]; Rectangle rect = (Rectangle) o[0]; bi = ecwFile.getBufferedImage(envl, rect.width, rect.height); // create a coverage description that matches the sub image (coverage) // for this a new LonLatEnvelope must be set co = (CoverageOffering) description.clone(); co.setLonLatEnvelope((LonLatEnvelope) o[2]); } catch (Exception e) { e.printStackTrace(); throw new IOException(StringTools.stackTraceToString(e)); } finally { // free the ECW cache memory if (ecwFile != null) { ecwFile.close(); } } return new ImageGridCoverage(co, (Envelope) o[1], bi); }
/** * @param name * @param select * @throws UnknownCRSException */ Table(String name, String select, List<Pair<String, String>> geometryColumns) throws UnknownCRSException { this.name = name; this.select = select.trim(); String[] tmp = StringTools.toArray(select, " ", false); for (String value : tmp) { if (value.startsWith("$")) { variables.add(value); } } for (Pair<String, String> pair : geometryColumns) { CoordinateSystem crs = CRSFactory.create(pair.second); Pair<String, CoordinateSystem> p = new Pair<String, CoordinateSystem>(pair.first, crs); this.geometryColumns.add(p); } }
/** return the LonLatEnvelope of the entire image in "EPSG:4326" */ private Envelope getLLEAsEnvelope() { String code = getNativeSRSCode(); LonLatEnvelope lle = description.getLonLatEnvelope(); Envelope tmp = GeometryFactory.createEnvelope( lle.getMin().getX(), lle.getMin().getY(), lle.getMax().getX(), lle.getMax().getY(), null); try { if (!code.equals("EPSG:4326")) { GeoTransformer trans = new GeoTransformer(code); tmp = trans.transform(tmp, "EPSG:4326"); } } catch (Exception e) { LOGGER.logError(StringTools.stackTraceToString(e)); } return tmp; }
/** * reads a deegree WCS configuration file and performs a GetCoverage request Steps: * * <ul> * <li>read configuration file * <li>read a GetCoverage request object * <li>perform the request * </ul> */ public void _testGetCoverage1() { try { WCSConfiguration configuration = WCSConfiguration.create(Configuration.getWCSConfigurationURL()); WCService service = new WCService(configuration); StringBuffer sb = new StringBuffer(); sb.append(Configuration.PROTOCOL + "://" + Configuration.HOST) .append(':') .append(Configuration.PORT) .append(Configuration.WCS_WEB_CONTEXT) .append('/') .append(Configuration.WCS_SERVLET); String req = "<?xml version='1.0' encoding='UTF-8'?><GetCoverage " + "xmlns='http://www.opengis.net/wcs' xmlns:gml='http://www.opengis.net/gml' " + "service='WCS' version='1.0.0'><sourceCoverage>Mapneatline</sourceCoverage>" + "<domainSubset><spatialSubset><gml:Envelope srsName='EPSG:4326'>" + "<gml:pos dimension='2'>-1,-1</gml:pos><gml:pos dimension='2'>1,1" + "</gml:pos></gml:Envelope><gml:Grid dimension='2'><gml:limits>" + "<gml:GridEnvelope><gml:low>0 0</gml:low><gml:high>300 300</gml:high>" + "</gml:GridEnvelope></gml:limits><gml:axisName>x</gml:axisName>" + "<gml:axisName>y</gml:axisName></gml:Grid></spatialSubset></domainSubset>" + "<output><crs>EPSG:4326</crs><format>jpeg</format></output></GetCoverage>"; StringReader reader = new StringReader(req); Document doc = XMLTools.parse(reader); GetCoverage desc = (GetCoverage) OGCRequestFactory.createFromXML(doc); ResultCoverage o = (ResultCoverage) service.doService(desc); BufferedImage bi = ((AbstractGridCoverage) o.getCoverage()).getAsImage(500, 500); FileOutputStream fos = new FileOutputStream(Configuration.getWCSBaseDir().getPath() + "/kannweg1.tif"); ImageUtils.saveImage(bi, fos, "tif", 1); fos.close(); } catch (Exception e) { fail(StringTools.stackTraceToString(e)); } }
/** * Creates a <code>DCPType</code> object from the passed <code>DCP</code> element. * <p> * NOTE: Currently the <code>OnlineResources</code> included in the <code>DCPType</code> are * just stored as simple <code>URLs</code> (not as <code>OnLineResource</code> instances)! * <p> * NOTE: In an <code>OGCStandardCapabilitiesDocument</code> the <code>XLinks</code> (the * <code>URLs</code>) are stored in separate elements (<code>OnlineResource</code>), in * an <code>OGCCommonCapabilitiesDocument</code> they are the * <code>Get<code>/<code>Post</code> elements themselves. * * @param element * * @return created <code>DCPType</code> * @throws XMLParsingException * * @see org.deegree.ogcwebservices.getcapabilities.OGCStandardCapabilities */ @Override protected DCPType getDCP(Element element) throws XMLParsingException { LOG.entering(); DCPType dcpType = null; try { Element elem = (Element) XMLTools.getRequiredNode(element, "HTTP", nsContext); List nl = XMLTools.getNodes(elem, "Get", nsContext); URL[] get = new URL[nl.size()]; for (int i = 0; i < get.length; i++) { String s = XMLTools.getNodeAsString((Node) nl.get(i), "./@xlink:href", nsContext, null); if (s == null) { s = XMLTools.getRequiredNodeAsString( (Node) nl.get(i), "./OnlineResource/@xlink:href", nsContext); } get[i] = new URL(s); } nl = XMLTools.getNodes(elem, "Post", nsContext); URL[] post = new URL[nl.size()]; for (int i = 0; i < post.length; i++) { String s = XMLTools.getNodeAsString((Node) nl.get(i), "./@xlink:href", nsContext, null); if (s == null) { s = XMLTools.getRequiredNodeAsString( (Node) nl.get(i), "./OnlineResource/@xlink:href", nsContext); } post[i] = new URL(s); } Protocol protocol = new HTTP(get, post); dcpType = new DCPType(protocol); } catch (MalformedURLException e) { throw new XMLParsingException( "Couldn't parse DCPType onlineresource URL about: " + StringTools.stackTraceToString(e)); } LOG.exiting(); return dcpType; }
/** * reads a deegree WCS configuration file and performs a GetCapbilities request Steps: * * <ul> * <li>read configuration file * <li>read a GetCapabilites request object * <li>perform the request * </ul> */ public void testGetCapabilities() { try { WCSConfiguration configuration = WCSConfiguration.create(Configuration.getWCSConfigurationURL()); WCService service = new WCService(configuration); // StringBuffer sb = new StringBuffer(); // sb.append( "http://127.0.0.1/deegreewcs/wcs?service=WCS&" ); // sb.append( "request=GetCapabilities&version=1.0.0" ); Map<String, String> map = new HashMap<String, String>(); map.put("REQUEST", "GetCapabilities"); map.put("VERSION", "1.0.0"); map.put("SERVICE", "WCS"); WCSGetCapabilities getCapa = (WCSGetCapabilities) WCSGetCapabilities.create(map); // (WCSGetCapabilities) OGCRequestFactory.createFromKVP(sb.toString()); Object o = service.doService(getCapa); XMLFragment xml = XMLFactory.export((WCSConfiguration) o); // xml.write( System.out ); LOG.logInfo(xml.getAsPrettyString()); } catch (Exception e) { fail(StringTools.stackTraceToString(e)); } }
/** * validates if the requested layer is valid against the policy/condition. If the passed user <> * null this is checked against the user- and rights-management system/repository * * @param condition * @param layer * @throws InvalidParameterValueException */ private void validateLayer(Condition condition, String layer, String style) throws InvalidParameterValueException { OperationParameter op = condition.getOperationParameter(LAYER); // version is valid because no restrictions are made if (op.isAny()) { return; } List<String> v = op.getValues(); // seperate layers from assigned styles Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < v.size(); i++) { String[] tmp = StringTools.toArray(v.get(i), "|", false); map.put(tmp[0], tmp[1]); } String vs = map.get(layer); if (vs == null) { if (!op.isUserCoupled()) { throw new InvalidParameterValueException(INVALIDLAYER + layer); } userCoupled = true; } else if (!style.equalsIgnoreCase("default") && vs.indexOf("$any$") < 0 && vs.indexOf(style) < 0) { if (!op.isUserCoupled()) { // a style is valid for a layer if it's the default style // or the layer accepts any style or a style is explicit defined // to be valid throw new InvalidParameterValueException(INVALIDSTYLE + layer + ':' + style); } userCoupled = true; } }
/** * reads a deegree WCS configuration file and performs a GetCoverage request Steps: * * <ul> * <li>read configuration file * <li>read a GetCoverage request object * <li>perform the request * </ul> */ public void _testGetCoverage3() { try { WCSConfiguration configuration = WCSConfiguration.create(Configuration.getWCSConfigurationURL()); WCService service = new WCService(configuration); Map<String, String> map = new HashMap<String, String>(); map.put("SERVICE", "WCS"); map.put("REQUEST", "GetCoverage"); map.put("VERSION", "1.0.0"); map.put("COVERAGE", "europe"); map.put("CRS", "EPSG:4326"); map.put("BBOX", "-5,40,20,60"); map.put("WIDTH", "800"); map.put("HEIGHT", "800"); map.put("FORMAT", "jpeg"); // StringBuffer sb = new StringBuffer(); // sb.append(Configuration.PROTOCOL + "://" + Configuration.HOST) // .append(':').append(Configuration.PORT).append('/') // .append(Configuration.WCS_WEB_CONTEXT).append('/') // .append(Configuration.WCS_SERVLET).append("?service=WCS&") // .append("request=GetCoverage&version=1.0.0&coverage=europe&") // .append( "crs=EPSG:4326&BBOX=-5,40,20,60&Width=800&height=800&") // .append("format=jpeg"); GetCoverage desc = GetCoverage.create(map); ResultCoverage o = (ResultCoverage) service.doService(desc); BufferedImage bi = ((AbstractGridCoverage) o.getCoverage()).getAsImage(800, 800); FileOutputStream fos = new FileOutputStream(Configuration.getWCSBaseDir().getPath() + "/kannweg3.tif"); ImageUtils.saveImage(bi, fos, "tif", 1); fos.close(); } catch (Exception e) { fail(StringTools.stackTraceToString(e)); } }
/** * reads a deegree WCS configuration file and performs a GetCoverage request. same as * testGetCoverage1() but uses nameIndexed data source Steps: * * <ul> * <li>read configuration file * <li>read a GetCoverage request object * <li>perform the request * </ul> */ public void _testGetCoverage2() { try { WCSConfiguration configuration = WCSConfiguration.create(Configuration.getWCSConfigurationURL()); WCService service = new WCService(configuration); Map<String, String> map = new HashMap<String, String>(); map.put("SERVICE", "WCS"); map.put("REQUEST", "GetCoverage"); map.put("VERSION", "1.0.0"); map.put("COVERAGE", "dem"); map.put("CRS", "EPSG:4326"); map.put("BBOX", "-122.6261,37.4531,-122.0777,38.0"); map.put("WIDTH", "828"); map.put("HEIGHT", "823"); map.put("FORMAT", "GeoTiff"); // StringBuffer sb = new StringBuffer(); // sb.append(Configuration.PROTOCOL + "://" + Configuration.HOST).append(':').append( // Configuration.PORT).append('/').append(Configuration.WCS_WEB_CONTEXT).append( // '/').append(Configuration.WCS_SERVLET).append("?service=WCS&").append( // "request=GetCoverage&version=1.0.0&coverage=dem&").append( // "crs=EPSG:4326&BBOX=-122.6261,37.4531,-122.0777,38.0&Width=828&height=823&") // .append("format=GeoTiff"); GetCoverage desc = GetCoverage.create(map); ResultCoverage o = (ResultCoverage) service.doService(desc); BufferedImage bi = ((AbstractGridCoverage) o.getCoverage()).getAsImage(828, 823); LOG.logInfo(o.toString()); FileOutputStream fos = new FileOutputStream(new URL(Configuration.getWCSBaseDir(), "/kannweg2.tif").getFile()); ImageUtils.saveImage(bi, fos, "tif", 1); fos.close(); } catch (Exception e) { fail(StringTools.stackTraceToString(e)); } }
/** * sets the name of the the layers that are activated for feature info requests in the uses WMC */ void setCurrentFILayer() { String tmp = parameter.get(PARAM_CURRENTFILAYER); String[] fiLayer = StringTools.toArray(tmp, ",", false); if (fiLayer != null) { List<String> list = Arrays.asList(fiLayer); list = new ArrayList<String>(list); ViewContext vc = getCurrentViewContext(portlet.getID()); LayerList layerList = vc.getLayerList(); Layer[] layers = layerList.getLayers(); for (int i = 0; i < layers.length; i++) { try { if (list.contains(layers[i].getName())) { layers[i].getExtension().setSelectedForQuery(true); } else { layers[i].getExtension().setSelectedForQuery(false); } } catch (Exception e) { // TODO: handle exception LOG.logError(e.getMessage(), e); } } } }
/** * appends the selected layers of a WMS to the passed <code>ViewContext</code> * * @param context * @throws ContextException * @throws MalformedURLException * @throws PortalException * @throws InvalidCapabilitiesException */ private void appendWMS(RPCWebEvent rpc, ViewContext context) throws MalformedURLException, ContextException, PortalException, InvalidCapabilitiesException { RPCStruct struct = (RPCStruct) rpc.getRPCMethodCall().getParameters()[0].getValue(); URL url = new URL((String) struct.getMember("WMSURL").getValue()); String name = (String) struct.getMember("WMSNAME").getValue(); String version = (String) struct.getMember("WMSVERSION").getValue(); String layers = (String) struct.getMember("LAYERS").getValue(); String formatName = (String) struct.getMember("FORMAT").getValue(); boolean useAuthentification = false; if (struct.getMember("useAuthentification") != null) { String tmp = (String) struct.getMember("useAuthentification").getValue(); useAuthentification = "true".equalsIgnoreCase(tmp); } List<String> list = StringTools.toList(layers, ";", true); WMSCapabilitiesDocument capa = null; try { StringBuffer sb = new StringBuffer(500); if ("1.0.0".equals(version)) { sb.append(url.toExternalForm()).append("?request=capabilities&service=WMS"); } else { sb.append(url.toExternalForm()).append("?request=GetCapabilities&service=WMS"); } if (useAuthentification) { HttpSession session = ((HttpServletRequest) getRequest()).getSession(); String user = ((org.apache.jetspeed.om.security.BaseJetspeedUser) session.getAttribute("turbine.user")) .getUserName(); String password = ((org.apache.jetspeed.om.security.BaseJetspeedUser) session.getAttribute("turbine.user")) .getPassword(); if (!"anon".equals(user)) { sb.append("&user="******"&password="******"GetCapabilites for added WMS", sb.toString()); capa = WMSCapabilitiesDocumentFactory.getWMSCapabilitiesDocument(new URL(sb.toString())); } catch (Exception e) { LOG.logError(e.getMessage(), e); String msg = null; if ("1.0.0".equals(version)) { msg = StringTools.concat( 500, "could not load WMS capabilities from: ", new URL(url.toExternalForm() + "?request=capabilities&service=WMS"), "; reason: ", e.getMessage()); } else { msg = StringTools.concat( 500, "could not load WMS capabilities from: ", new URL(url.toExternalForm() + "?request=GetCapabilities&service=WMS"), "; reason: ", e.getMessage()); } throw new PortalException(msg); } WMSCapabilities capabilities = (WMSCapabilities) capa.parseCapabilities(); String rootTitle = capabilities.getLayer().getTitle(); // ---------------------------------------------------------------------------- // stuff required by layerlist tree view Node root = context.getGeneral().getExtension().getLayerTreeRoot(); // check if Node width this title already exists Node[] nodes = root.getNodes(); int newNodeId = -1; for (int j = 0; j < nodes.length; j++) { if (nodes[j].getTitle().equals(rootTitle)) { newNodeId = nodes[j].getId(); break; } } if (newNodeId == -1) { newNodeId = root.getMaxNodeId() + 1; Node newNode = new Node(newNodeId, root, rootTitle, true, false); Node[] newNodes = new Node[nodes.length + 1]; newNodes[0] = newNode; for (int j = 0; j < nodes.length; j++) { newNodes[j + 1] = nodes[j]; } root.setNodes(newNodes); } // ---------------------------------------------------------------------------- for (int i = 0; i < list.size(); i++) { String[] lay = StringTools.toArray(list.get(i), "|", false); Server server = new Server(name, version, "OGC:WMS", url, capabilities); String srs = context.getGeneral().getBoundingBox()[0].getCoordinateSystem().getPrefixedName(); Format format = new Format(formatName, true); FormatList fl = new FormatList(new Format[] {format}); // read available styles from WMS capabilities and add them // to the WMC layer org.deegree.ogcwebservices.wms.capabilities.Layer wmslay = capabilities.getLayer(lay[0]); org.deegree.ogcwebservices.wms.capabilities.Style[] wmsstyles = wmslay.getStyles(); Style[] styles = null; if (wmsstyles == null || wmsstyles.length == 0) { // a wms capabilities layer may offeres one or more styles for // a layer but it don't have to. But WMC must have at least one // style for each layer; So we set a default style in the case // a wms does not declares one styles = new Style[1]; styles[0] = new Style("", "default", "", null, true); } else { styles = new Style[wmsstyles.length]; for (int j = 0; j < styles.length; j++) { boolean isDefault = wmsstyles[j].getName().toLowerCase().indexOf("default") > -1 || wmsstyles[j].getName().trim().length() == 0; ImageURL legendURL = null; LegendURL[] lUrl = wmsstyles[j].getLegendURL(); if (lUrl != null && lUrl.length > 0) { legendURL = new ImageURL( lUrl[0].getWidth(), lUrl[0].getHeight(), lUrl[0].getFormat(), lUrl[0].getOnlineResource()); } styles[j] = new Style( wmsstyles[j].getName(), wmsstyles[j].getTitle(), wmsstyles[j].getAbstract(), legendURL, isDefault); } } StyleList styleList = new StyleList(styles); BaseURL mdUrl = null; MetadataURL[] mdUrls = wmslay.getMetadataURL(); if (mdUrls != null && mdUrls.length == 1 && mdUrls[0] != null) { mdUrl = mdUrls[0]; } int authentication = LayerExtension.NONE; if (useAuthentification) { authentication = LayerExtension.USERPASSWORD; } LayerExtension lex = new LayerExtension( null, false, wmslay.getScaleHint().getMin(), wmslay.getScaleHint().getMax(), false, authentication, newNodeId, false, null); Layer newLay = new Layer( server, lay[0], lay[1], null, new String[] {srs}, null, mdUrl, fl, styleList, wmslay.isQueryable(), false, lex); if (context .getLayerList() .getLayer(newLay.getName(), server.getOnlineResource().toExternalForm()) == null) { context.getLayerList().addLayerToTop(newLay); } } try { XMLFragment xml = XMLFactory.export(context); System.out.println(xml.getAsPrettyString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Exports a <code>GetRecords</code> instance to a <code>GetRecordsDocument</code>. * * @param request * @return DOM representation of the <code>GetRecords</code> * @throws XMLException if some elements could not be appended * @throws OGCWebServiceException if an error occurred while creating the xml-representation of * the GetRecords bean. */ public static GetRecordsDocument export(GetRecords request) throws XMLException, OGCWebServiceException { GetRecordsDocument getRecordsDocument = null; getRecordsDocument = new GetRecordsDocument(); try { getRecordsDocument.createEmptyDocument(); } catch (Exception e) { throw new XMLException(e.getMessage()); } Element rootElement = getRecordsDocument.getRootElement(); Document doc = rootElement.getOwnerDocument(); // 'version'-attribute rootElement.setAttribute("version", request.getVersion()); // 'resultType'-attribute rootElement.setAttribute("resultType", request.getResultTypeAsString()); // 'outputFormat'-attribute rootElement.setAttribute("outputFormat", request.getOutputFormat()); // 'outputSchema'-attribute rootElement.setAttribute("outputSchema", request.getOutputSchema()); // 'startPosition'-attribute rootElement.setAttribute("startPosition", "" + request.getStartPosition()); // 'maxRecords'-attribute rootElement.setAttribute("maxRecords", "" + request.getMaxRecords()); // '<csw:DistributedSearch>'-element if (request.getHopCount() != -1) { Element distributedSearchElement = doc.createElementNS(CSWNS.toString(), "csw:DistributedSearch"); // 'hopCount'-attribute distributedSearchElement.setAttribute("hopCount", "" + request.getHopCount()); rootElement.appendChild(distributedSearchElement); } // '<csw:ResponseHandler>'-elements (optional) URI responseHandler = request.getResponseHandler(); if (responseHandler != null) { Element responseHandlerElement = doc.createElementNS(CSWNS.toString(), "csw:ResponseHandler"); responseHandlerElement.appendChild(doc.createTextNode(responseHandler.toASCIIString())); rootElement.appendChild(responseHandlerElement); } // '<csw:Query>'-elements (required) Query query = request.getQuery(); if (query != null) { LOG.logDebug("Adding the csw:Query element to the csw:GetRecords document"); Element queryElement = doc.createElementNS(CSWNS.toString(), "csw:Query"); // 'typeName'-attribute // Testing for the list of typenames. List<QualifiedName> typeNames = query.getTypeNamesAsList(); Map<String, QualifiedName> aliases = new HashMap<String, QualifiedName>(query.getDeclaredTypeNameVariables()); if (typeNames.size() > 0) { appendTypeNamesAttribute(rootElement, queryElement, typeNames, aliases); } else { String s = StringTools.arrayToString(query.getTypeNames(), ','); queryElement.setAttribute("typeNames", s); } // '<csw:ElementSetName>'-element (optional) if (query.getElementSetName() != null) { Element elementSetNameElement = doc.createElementNS(CSWNS.toString(), "csw:ElementSetName"); List<QualifiedName> elementSetNameTypeNamesList = query.getElementSetNameTypeNamesList(); if (query.getElementSetNameVariables() != null && query.getElementSetNameVariables().size() > 0) { throw new OGCWebServiceException( "The elementSetName element in a csw:GetRecords request may not refrerence variables (aka. aliases), aborting request"); } if (elementSetNameTypeNamesList.size() > 0) { appendTypeNamesAttribute( rootElement, elementSetNameElement, elementSetNameTypeNamesList, null); } elementSetNameElement.appendChild(doc.createTextNode(query.getElementSetName())); queryElement.appendChild(elementSetNameElement); } // '<csw:ElementName>'-elements (optional) if (query.getElementNamesAsPropertyPaths() != null) { List<PropertyPath> elementNames = query.getElementNamesAsPropertyPaths(); for (int j = 0; j < elementNames.size(); j++) { Element elementNameElement = doc.createElementNS(CSWNS.toString(), "csw:ElementName"); elementNameElement.appendChild(doc.createTextNode(elementNames.get(j).getAsString())); queryElement.appendChild(elementNameElement); } } // '<csw:Constraint>'-element (optional) if (query.getContraint() != null) { Element constraintElement = doc.createElementNS(CSWNS.toString(), "csw:Constraint"); constraintElement.setAttribute("version", "1.1.0"); org.deegree.model.filterencoding.XMLFactory.appendFilter( constraintElement, query.getContraint()); queryElement.appendChild(constraintElement); } // '<ogc:SortBy>'-element (optional) SortProperty[] sortProperties = query.getSortProperties(); if (sortProperties != null && sortProperties.length != 0) { Element sortByElement = doc.createElementNS(OGCNS.toString(), "ogc:SortBy"); // '<ogc:SortProperty>'-elements for (int j = 0; j < sortProperties.length; j++) { Element sortPropertiesElement = doc.createElementNS(OGCNS.toString(), "ogc:SortProperty"); // '<ogc:PropertyName>'-element (required) Element propertyNameElement = doc.createElementNS(OGCNS.toString(), "ogc:PropertyName"); appendPropertyPath(propertyNameElement, sortProperties[j].getSortProperty()); // '<ogc:SortOrder>'-element (optional) Element sortOrderElement = doc.createElementNS(OGCNS.toString(), "ogc:SortOrder"); Node tn = doc.createTextNode(sortProperties[j].getSortOrder() ? "ASC" : "DESC"); sortOrderElement.appendChild(tn); sortPropertiesElement.appendChild(propertyNameElement); sortPropertiesElement.appendChild(sortOrderElement); sortByElement.appendChild(sortPropertiesElement); } queryElement.appendChild(sortByElement); } rootElement.appendChild(queryElement); } return getRecordsDocument; }
/** @param arg0 */ public UnauthorizedException(Throwable arg0) { super(StringTools.stackTraceToString(arg0)); }
/** * @param message * @param arg1 */ public UnauthorizedException(String message, Throwable arg1) { super(message, arg1); this.message = message + StringTools.stackTraceToString(arg1); }
/** * Creates a class representation of the <code>deegreeParams</code>- section. * * @return * @throws InvalidConfigurationException */ public CatalogueDeegreeParams getDeegreeParams() throws InvalidConfigurationException { CatalogueDeegreeParams deegreeParams = null; try { Node root = this.getRootElement(); Element element = XMLTools.getRequiredChildElement("deegreeParams", DEEGREECSW, root); // 'deegreecsw:DefaultOnlineResource'-element (mandatory) OnlineResource defaultOnlineResource = parseOnLineResource( XMLTools.getRequiredChildElement("DefaultOnlineResource", DEEGREECSW, element)); // 'deegreecsw:CacheSize'-element (optional, default: 100) int cacheSize = XMLTools.getNodeAsInt(element, "./deegreecsw:CacheSize", nsContext, 100); // 'deegreecsw:RequestTimeLimit'-element (optional, default: 2) int requestTimeLimit = XMLTools.getNodeAsInt(element, "./deegreecsw:RequestTimeLimit", nsContext, 2); // 'deegreecsw:Encoding'-element (optional, default: UTF-8) String characterSet = XMLTools.getStringValue("Encoding", DEEGREECSW, element, "UTF-8"); // default output schema used by a catalogue String defaultOutputSchema = XMLTools.getStringValue("DefaultOutputSchema", DEEGREECSW, element, "OGCCORE"); // 'deegreecsw:WFSResource'-element (mandatory) SimpleLink wfsResource = parseSimpleLink(XMLTools.getRequiredChildElement("WFSResource", DEEGREECSW, element)); // 'deegreecsw:CatalogAddresses'-element (optional) Element catalogAddressesElement = XMLTools.getChildElement("CatalogAddresses", DEEGREECSW, element); OnlineResource[] catalogAddresses = new OnlineResource[0]; if (catalogAddressesElement != null) { // 'deegreecsw:CatalogAddresses'-element (optional) ElementList el = XMLTools.getChildElements("CatalogAddress", DEEGREECSW, catalogAddressesElement); catalogAddresses = new OnlineResource[el.getLength()]; for (int i = 0; i < catalogAddresses.length; i++) { catalogAddresses[i] = parseOnLineResource(el.item(i)); } } OnlineResource transInXslt = null; Element elem = (Element) XMLTools.getNode(element, "deegreecsw:TransactionInputXSLT", nsc); if (elem != null) { transInXslt = parseOnLineResource(elem); } OnlineResource transOutXslt = null; elem = (Element) XMLTools.getNode(element, "deegreecsw:TransactionOutputXSLT", nsc); if (elem != null) { transOutXslt = parseOnLineResource(elem); } if ((transInXslt != null && transOutXslt == null) || (transInXslt == null && transOutXslt != null)) { throw new InvalidConfigurationException( "if CSW-deegreeParam " + "'TransactionInputXSLT' is defined 'TransactionOutputXSLT' must " + "be defined too and vice versa!"); } // 'deegreecsw:HarvestRepository'-element (optional) Element harvestRepositoryElement = XMLTools.getChildElement("HarvestRepository", DEEGREECSW, element); JDBCConnection harvestRepository = null; if (harvestRepositoryElement != null) { // 'deegreecsw:Connection'-element (optional) Element connectionElement = XMLTools.getChildElement("Connection", DEEGREECSW, harvestRepositoryElement); if (connectionElement != null) { harvestRepository = new JDBCConnection( XMLTools.getRequiredStringValue("Driver", DEEGREECSW, connectionElement), XMLTools.getRequiredStringValue("Logon", DEEGREECSW, connectionElement), XMLTools.getRequiredStringValue("User", DEEGREECSW, connectionElement), XMLTools.getRequiredStringValue("Password", DEEGREECSW, connectionElement), null, null, null); } } deegreeParams = new CatalogueDeegreeParams( defaultOnlineResource, cacheSize, requestTimeLimit, characterSet, wfsResource, catalogAddresses, harvestRepository, defaultOutputSchema, transInXslt, transOutXslt); } catch (XMLParsingException e) { throw new InvalidConfigurationException( "Error parsing the deegreeParams " + "section of the CSW configuration: \n" + e.getMessage() + StringTools.stackTraceToString(e)); } return deegreeParams; }
/** * Appends the XML representation of the given <code>Query</code> to an element. * * @param query */ private static void appendQuery(Element root, Query query) throws IOException, XMLParsingException { Element queryElem = XMLTools.appendElement(root, WFS, "wfs:Query"); if (query.getHandle() != null) { queryElem.setAttribute("handle", query.getHandle()); } if (query.getFeatureVersion() != null) { queryElem.setAttribute("featureVersion", query.getFeatureVersion()); } QualifiedName[] qn = query.getTypeNames(); String[] na = new String[qn.length]; for (int i = 0; i < na.length; i++) { na[i] = qn[i].getAsString(); queryElem.setAttribute("xmlns:" + qn[i].getPrefix(), qn[i].getNamespace().toASCIIString()); } String tn = StringTools.arrayToString(na, ','); queryElem.setAttribute("typeName", tn); PropertyPath[] propertyNames = query.getPropertyNames(); for (int i = 0; i < propertyNames.length; i++) { Element propertyNameElement = XMLTools.appendElement(queryElem, WFS, "wfs:PropertyName"); appendPropertyPath(propertyNameElement, propertyNames[i]); } Function[] fn = query.getFunctions(); // copy function definitions into query node if (fn != null) { for (int i = 0; i < fn.length; i++) { StringReader sr = new StringReader(fn[i].toXML().toString()); Document doc; try { doc = XMLTools.parse(sr); } catch (SAXException e) { throw new XMLParsingException("could not parse filter function", e); } XMLTools.copyNode(doc.getDocumentElement(), queryElem); } } // copy filter into query node if (query.getFilter() != null) { StringReader sr = new StringReader(query.getFilter().toXML().toString()); Document doc; try { doc = XMLTools.parse(sr); } catch (SAXException e) { throw new XMLParsingException("could not parse filter", e); } Element elem = XMLTools.appendElement(queryElem, OGCNS, "ogc:Filter"); XMLTools.copyNode(doc.getDocumentElement(), elem); } SortProperty[] sp = query.getSortProperties(); if (sp != null) { Element sortBy = XMLTools.appendElement(queryElem, OGCNS, "ogc:SortBy"); for (int i = 0; i < sp.length; i++) { Element sortProp = XMLTools.appendElement(sortBy, OGCNS, "ogc:SortProperty"); XMLTools.appendElement( sortProp, OGCNS, "ogc:PropertyName", sp[i].getSortProperty().getAsString()); if (!sp[i].getSortOrder()) { XMLTools.appendElement(sortBy, OGCNS, "ogc:SortOrder", "DESC"); } } } }
/* * (non-Javadoc) * * @see org.deegree.igeo.modules.remotecontrol.RequestHandler#perform(java.util.Map, * org.deegree.igeo.ApplicationContainer) */ public String perform(Map<String, String> paramater, ApplicationContainer<?> appContainer) throws ModuleException { String tmp = paramater.get("OBJECTIDS"); if (tmp == null || tmp.length() == 0) { throw new ModuleException(Messages.get("$DG10091")); } List<String> objIds = StringTools.toList(tmp, ",;", true); tmp = paramater.get("LAYER"); if (tmp == null) { throw new ModuleException(Messages.get("$DG10092")); } MapModel mapModel = appContainer.getMapModel(null); LocalMapModelVisitor mv = new LocalMapModelVisitor(tmp); try { mapModel.walkLayerTree(mv); } catch (Exception e) { LOG.logError(e.getMessage(), e); throw new ModuleException(e.getMessage()); } Layer layer = mv.getResult(); if (layer == null) { throw new ModuleException(Messages.get("$DG10093", tmp)); } layer.setVisible(true); // first select features in layer List<Identifier> ids = new ArrayList<Identifier>(); for (String id : objIds) { ids.add(new Identifier(id)); } SelectFeatureCommand cmd = new SelectFeatureCommand(layer, ids, false); try { appContainer.getCommandProcessor().executeSychronously(cmd, true); } catch (Exception e) { LOG.logError(e.getMessage(), e); throw new ModuleException(e.getMessage()); } // get selected features as FeatureCollection and so their common bounding box FeatureCollection fc = layer.getSelectedFeatures(); if (fc.size() == 0) { throw new ModuleException(Messages.get("$DG10094", paramater.get("OBJECTIDS"))); } Envelope env = null; try { env = fc.getBoundedBy(); if (env.getWidth() < 0.0001) { // feature collection just contains one point; set fix bbox width/height // 25 map units env = env.getBuffer(25); } } catch (GeometryException e) { LOG.logError(e.getMessage(), e); throw new ModuleException(e.getMessage()); } // zoom to common bounding box of selected features ZoomCommand zcmd = new ZoomCommand(mapModel); zcmd.setZoomBox( env, mapModel.getTargetDevice().getPixelWidth(), mapModel.getTargetDevice().getPixelHeight()); if ("TRUE".equalsIgnoreCase(paramater.get("sync"))) { try { appContainer.getCommandProcessor().executeSychronously(zcmd, true); } catch (Exception e) { LOG.logError(e.getMessage(), e); throw new ModuleException(e.getMessage()); } } else { appContainer.getCommandProcessor().executeASychronously(zcmd); } return "feature selected"; }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.logDebug("Starting to process request"); String addr = request.getRemoteAddr(); LOG.logDebug("request.remoteAddr: ", addr); OutputStream os = response.getOutputStream(); String docPath = downloadDir; ServletContext sc = getServletContext(); if (sc != null) { if (sc.getAttribute(Constants.DOWNLOADDIR) != null) { docPath = (String) sc.getAttribute(Constants.DOWNLOADDIR); } } File fileDir; try { fileDir = new File(new URL(docPath).getFile()); } catch (MalformedURLException e) { LOG.logDebug("Download dir did not start with 'file', trying just as file now.", e); fileDir = new File(docPath); } LOG.logDebug("download directory (fileDir): ", fileDir.toString()); response.setContentType(contentType); RandomAccessFile raf = null; // TODO make sure the path exists, otherwise return an error. try { if (ipAddress == null || ipAddress.equals(addr)) { String fileName = request.getParameter("file").trim(); LOG.logDebug("zip file name= ", fileName); String filename = StringTools.concat(100, "attachment;filename=\"", fileName, "\""); response.addHeader("Content-Disposition", filename); // response.setHeader( "Content-Disposition", filename ); // read each file from the local file system File f = new File(fileDir, fileName); raf = new RandomAccessFile(f, "r"); // LOG.logDebug( "raf.name: " + f.toString() ); long size = raf.length(); byte[] b = new byte[(int) size]; // reads the file to the byte array raf.read(b); // write current byte array (file) to the output stream os.write(b); LOG.logDebug("File is written successfully"); } else { os.write(Messages.getString("DownloadServlet.ERR_ACC_DENY").getBytes("UTF-8")); } } catch (Exception e) { LOG.logDebug("catching error: ", e); String message = org.deegree.i18n.Messages.get("IGEO_STD_CNTXT_WRONG_PATH", fileDir.toString()); os.write(message.getBytes("UTF-8")); os.write(e.toString().getBytes("UTF-8")); } finally { try { raf.close(); os.close(); } catch (Exception e) { LOG.logError(e.getMessage(), e); } } }