package com.esri.arcgis.model; import com.esri.arcgis.carto.*; import com.esri.arcgis.geodatabase.*; import com.esri.arcgis.datasourcesfile.*; import com.esri.arcgis.datasourcesraster.*; import com.esri.arcgis.geoanalyst.*; import com.esri.arcgis.geometry.*; import com.esri.arcgis.display.*; import com.esri.arcgis.spatialanalyst.*; import com.esri.arcgis.server.IServerObjectManager; import com.esri.arcgis.server.IServerContext; import com.esri.arcgis.server.IServerObject; import com.esri.arcgis.server.ServerConnection; import com.esri.arcgis.system.*; import java.io.*; import javax.servlet.*; import java.util.*; import javax.servlet.http.*; import com.esri.arcgis.geometry.IEnvelope; public class ptp_shape_servlet extends HttpServlet{ public static String error_out = ""; public static String aPath ="D:\\applications\\model_ags\\datatemp"; public static IServerContext sc = null; public static String gridName = "grd1"; public static String shapeName = "shape1"; public static String url_out = null; public static FeatureClass fClass = null; public static FeatureClass tClass = null; public static String error_desc = null; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Two Request Parameters"; String point1 = request.getParameter("point1"); String point2 = request.getParameter("point2"); String url_out_1 = computeCost(point1,point2); out.println(url_out_1); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * @param args */ public static String computeCost(String frompoint, String topoint) { try { return model_exec("ip", "domain", "user", "password", "mapobject", frompoint, topoint); } catch (Exception e1){ error_desc = getStackTrace(e1); } return ""; } public static String getStackTrace(Exception t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); t.printStackTrace(pw); pw.flush(); sw.flush(); return sw.toString(); } public static void main(String[] args) { // TODO Auto-generated method stub //"450000,-700001", "1000000,-1000000" // String out_model_url = null; url_out = model_exec("ip", "domain", "user", "password", "mapobject", args[0], args[1] ); // System.out.println(out_model_url); } private static IFeatureClass rasterToLine(Raster costPath) throws IOException { //Here we use the IRasterConvertHelper to convert the raster cost path //to a polyline feature class. IFeatureClass ifClass = null; try { IRasterConvertHelper iRastConvert = new RasterConvertHelper(sc.createObject(RasterConvertHelper.getClsid())); IRasterAnalysisEnvironment iRasEnv = new RasterAnalysis(sc.createObject(RasterAnalysis.getClsid())); iRasEnv.setCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue,costPath); iRasEnv.setExtent(esriRasterEnvSettingEnum.esriRasterEnvValue,costPath,null); ifClass = iRastConvert.toShapefile(costPath.getAsIGeoDataset(),esriGeometryType.esriGeometryPolyline,iRasEnv); } catch (IOException e) { System.out.println("Couldn't build the input point."); error_out = e.getMessage(); throw e; } return ifClass; } public static String model_exec(String host, String domain, String user, String password, String mapServerName, String fromPoint, String toPoint) { String url_from_server = null; try { new ServerInitializer().initializeServer(domain, user, password); ServerConnection connection = new ServerConnection(); connection.connect(host); IServerObjectManager som = connection.getServerObjectManager(); sc = som.createServerContext(mapServerName, "MapServer"); IServerObject serverObject = sc.getServerObject(); IMapServerObjects mapServer = new IMapServerObjectsProxy( serverObject); IMap map = mapServer.getMap(""); // IMapServer server = new MapServer(mapServer); //This first (and only) layer in the IMap is the cost surface grid ILayer firstLayer = map.getLayer(0); IRasterLayer rasterLayer = new IRasterLayerProxy(firstLayer); IRaster rasterObject = rasterLayer.getRaster(); //access the raster object of the cost surface grid Raster rasterO = new Raster(rasterObject); /* //Use this to analyze the raster statistics of the cost raster. * * IRasterBandCollection iRasterBandCollection = rasterO.getAsIRasterBandCollection(); System.out.println("number of bands: " + iRasterBandCollection.getCount()); IRasterBand iRasterBand = iRasterBandCollection.item(0); IRasterStatistics iRasterStatistics = iRasterBand.getStatistics(); System.out.println("Max Pixel: " + iRasterStatistics.getMaximum()); System.out.println("Min Pixel: " + iRasterStatistics.getMinimum()); System.out.println("Mean Pixel: " + iRasterStatistics.getMean()); System.out.println("StdDev Pixel: " + iRasterStatistics.getStandardDeviation()); System.out.println(fromPoint.substring(0,fromPoint.indexOf(",")) + " " + fromPoint.substring(fromPoint.indexOf(",") + 1) ); */ //call the build_point method to create the IPoint of the two text based points IPoint fromPt = build_point(fromPoint); IPoint toPt = build_point(toPoint); System.out.println("built points"); //Generate the featureworkspace as a shapefilefactory IWorkspaceFactory shapeWkspFactory = new ShapefileWorkspaceFactory(sc.createObject(ShapefileWorkspaceFactory.getClsid())); IFeatureWorkspace featureWksp = new IFeatureWorkspaceProxy(shapeWkspFactory.openFromFile(aPath, 0)); //Build geometrydef for the point featureclasses GeometryDef geometryDef = new GeometryDef(sc.createObject(GeometryDef.getClsid())); geometryDef.setGeometryType(esriGeometryType.esriGeometryPoint); geometryDef.setSpatialReferenceByRef(rasterO.getSpatialReference()); //Apply the geometrydef for the points to the shape field Field geometryShapeField = new Field(sc.createObject(Field.getClsid())); geometryShapeField.setName("Shape"); geometryShapeField.setType(esriFieldType.esriFieldTypeGeometry); geometryShapeField.setGeometryDefByRef(geometryDef); Fields fields = new Fields(sc.createObject(Fields.getClsid())); fields.addField(geometryShapeField); //Generate the frompoint and topoin IFeatureclasses based on the shape field above IFeatureClass ifClass = featureWksp.createFeatureClass(shapeName,fields,null,null,esriFeatureType.esriFTSimple,"Shape",null); IFeatureClass itClass = featureWksp.createFeatureClass(shapeName+"t",fields,null,null,esriFeatureType.esriFTSimple,"Shape",null); //add and store the two ipoints to the point feature classes IFeature iFeat = ifClass.createFeature(); iFeat.setShapeByRef(fromPt); iFeat.store(); IFeature itoFeat = itClass.createFeature(); itoFeat.setShapeByRef(toPt); itoFeat.store(); fClass = new FeatureClass(ifClass); tClass = new FeatureClass(itClass); //Set 50,000meter buffer around from and to points for the clip IEnvelope clipEnv = new Envelope(sc.createObject(Envelope.getClsid())); if (fromPt.getY() > toPt.getY()){ clipEnv.setYMax(fromPt.getY() + 50000); clipEnv.setYMin(toPt.getY() - 50000); } else { clipEnv.setYMax(toPt.getY() + 50000); clipEnv.setYMin(fromPt.getY() - 50000); } if (fromPt.getX() > toPt.getX()) { clipEnv.setXMax(fromPt.getX() + 50000); clipEnv.setXMin(toPt.getX() - 50000); } else { clipEnv.setXMax(toPt.getX() + 50000); clipEnv.setXMin(fromPt.getX() - 50000); } System.out.println("set new envelope"); //set the analysis extent of the cost surface to the above envelope rasterO.setAnalysisExtentByRef(clipEnv); // Create workspace factory // IWorkspaceFactory rasWkspFactory = new RasterWorkspaceFactory(sc.createObject(RasterWorkspaceFactory.getClsid())); //Set up the rasterdistanceop class RasterDistanceOp idistcost = new RasterDistanceOp(sc.createObject(RasterDistanceOp.getClsid())); System.out.println("create IDistanceOp out of pRasterDS"); //Set up the analysis environment properties IRasterAnalysisEnvironment pRasterEnv = new IRasterAnalysisEnvironmentProxy(idistcost); pRasterEnv.setCellSize(esriRasterEnvSettingEnum.esriRasterEnvMaxOf,rasterO); pRasterEnv.setExtent(esriRasterEnvSettingEnum.esriRasterEnvMinOf,rasterO,null); pRasterEnv.setOutSpatialReferenceByRef(rasterO.getSpatialReference()); //Integer maxDistance = new Integer(500000); //Raster newRaster = new Raster(idistcost.costDistance(fClass.getAsIGeoDataset(),rasterO.getAsIGeoDataset(),null,null)); //Generate costdistance raster using the cosdistancefull method based //on the fClass (from point). This will compute the distance for all //the cells in the source raster to this from point Raster newRaster = new Raster(idistcost.costDistanceFull(fClass.getAsIGeoDataset(),rasterO.getAsIGeoDataset(),true, true, false, null,null)); //if you want to save the grid, do it here (don't forget the IWorkspaceFactory //above).... //newRaster.saveAs(gridName,rasWkspFactory.openFromFile(aPath,0),"GRID"); //band 0 from above contains the distance out //band 1 from above contains the backlink Raster distanceOut = new Raster(newRaster.getBandByName(newRaster.getAsIRasterBandCollection().item(0).getBandname()).getRasterDataset().createDefaultRaster()); Raster backlinkOut = new Raster(newRaster.getBandByName(newRaster.getAsIRasterBandCollection().item(1).getBandname()).getRasterDataset().createDefaultRaster()); //generate raster costPath based: // on the from point, // the distance raster, // the backlink raster, // using the best single path // Raster costPath = new Raster(idistcost.costPath(tClass.getAsIGeoDataset(),distanceOut,backlinkOut,esriGeoAnalysisPathEnum.esriGeoAnalysisPathBestSingle)); //call rasterToLine function from above to convert the raster line to a polyline //I could not get the costPathAsPolyline method to work properly.... IFeatureClass costLineFC = rasterToLine(costPath); //There should be only one feature in this featureclass. //Return it as an ipolyline to get the length of the line. IPolyline ipLine = new IPolylineProxy(costLineFC.getFeature(0).getShape()); System.out.println(costLineFC.getShapeFieldName()); System.out.println(ipLine.getLength()); FeatureLayer ifLayer = new FeatureLayer(sc.createObject(FeatureLayer.getClsid())); ifLayer.setFeatureClassByRef(costLineFC); //generate the igeofeaturelayer from the featurelayer IGeoFeatureLayer igfLayer = ifLayer.getAsIGeoFeatureLayer(); //Uncomment this to save the grid to disk //costPath.saveAs(gridName,rasWkspFactory.openFromFile(aPath,0),"GRID"); /* * * //stats on the raster datasets System.out.println(newRaster.getExtent().getEnvelope().getXMin()); System.out.println(newRaster.getExtent().getEnvelope().getYMin()); System.out.println(newRaster.getExtent().getEnvelope().getXMax()); System.out.println(newRaster.getExtent().getEnvelope().getYMax()); System.out.println(newRaster.getExtent().getXMax()); iRasterBandCollection = costout.getAsIRasterBandCollection(); System.out.println("number of bands: " + iRasterBandCollection.getCount()); iRasterBand = iRasterBandCollection.item(0); iRasterStatistics = iRasterBand.getStatistics(); System.out.println("Max Pixel: " + iRasterStatistics.getMaximum()); System.out.println("Min Pixel: " + iRasterStatistics.getMinimum()); System.out.println("Mean Pixel: " + iRasterStatistics.getMean()); System.out.println("StdDev Pixel: " + iRasterStatistics.getStandardDeviation()); iRasterBandCollection = pathout.getAsIRasterBandCollection(); iRasterBand = iRasterBandCollection.item(0); iRasterStatistics = iRasterBand.getStatistics(); System.out.println("Max Pixel: " + iRasterStatistics.getMaximum()); System.out.println("Min Pixel: " + iRasterStatistics.getMinimum()); System.out.println("Mean Pixel: " + iRasterStatistics.getMean()); System.out.println("StdDev Pixel: " + iRasterStatistics.getStandardDeviation()); */ //We have finshed the geoprocessing. //Now we must generate an image of this new polyline. //Since I am using a non-pooled object, I can just modify the map object //export the image and finally release the map object back to the pool. //clear all layers from the map object map.clearLayers(); //At first I was going to render the raster layer... //but doing that only highlights one cell along the path. //At large area views it became hard to see the line so //I rewrote it to render the polyline. //I am going to leave this code in here for future use. /* IRasterLayer irLayer = new RasterLayer(sc.createObject(RasterLayer.getClsid())); irLayer.createFromRaster(costPath.getAsIRaster()); RasterClassifyColorRampRenderer pRen = new RasterClassifyColorRampRenderer(sc.createObject(RasterClassifyColorRampRenderer.getClsid())); IRasterRenderer pRasRen = new IRasterRendererProxy(pRen); pRasRen = irLayer.getRenderer(); pRen.setClassCount(2); pRasRen.update(); IAlgorithmicColorRamp pRamp = new IAlgorithmicColorRampProxy(sc.createObject(AlgorithmicColorRamp.getClsid())); pRamp.setSize(pRen.getClassCount()); boolean[] b10k = null; RgbColor rgbColor = new RgbColor(sc.createObject(RgbColor.getClsid())); rgbColor.setRed(255); rgbColor.setGreen(0); rgbColor.setBlue(0); pRamp.setFromColor(rgbColor.getAsIColor()); rgbColor.setRed(255); rgbColor.setGreen(0); rgbColor.setBlue(0); pRamp.setToColor(rgbColor.getAsIColor()); pRamp.createRamp(b10k); ColorSymbol pSym = new ColorSymbol(sc.createObject(ColorSymbol.getClsid())); for (int i = 0; i < pRen.getClassCount(); i++) { //p.println("pRamp size: " + pRamp.getSize() + "pRamp color 1: " + pRamp.getColor(i).getCMYK()); pSym.setColor(pRamp.getColor(i)); //p.println("set symbol"); pRen.setSymbol(i,pSym.getAsISymbol()); //p.println("set label"); pRen.setLabel(i,"Label" + i); //p.println("Label" + i); } pRasRen.update(); irLayer.setRendererByRef(pRen.getAsIRasterRenderer()); map.addLayer(irLayer); */ //set up linesymbol for polyline SimpleLineSymbol iSimpLineSym = new SimpleLineSymbol(sc.createObject(SimpleLineSymbol.getClsid())); SimpleRenderer simpleRenderer = new SimpleRenderer(sc.createObject(SimpleRenderer.getClsid())); //set up rgb color RgbColor rgbColor = new RgbColor(sc.createObject(RgbColor.getClsid())); rgbColor.setRed(255); rgbColor.setGreen(0); rgbColor.setBlue(0); //set linesymbol to the proper color and width iSimpLineSym.setColor(rgbColor); iSimpLineSym.setWidth(8.0); //set the symbol by referencing the simplelinesymbol for the simplerenderer simpleRenderer.setSymbolByRef(iSimpLineSym); //set igeofeaturelayer to the simplerenderer igfLayer.setRendererByRef(simpleRenderer); //add this new geofeaturelayer to the map //map.addLayer(ifLayer); map.addLayer(igfLayer); //set up map export properties IImageDescription imageDesc = null; IImageType imageType = null; IImageDisplay imageDisplay = null; IMapDescription mapDesc= null; IMapImage mapImage = null; //get mapdescription from the server mapDesc = server.getServerInfo(server.getDefaultMapName()).getDefaultMapDescription(); //set image type imageType = new IImageTypeProxy(sc.createObject(ImageType.getClsid())); imageType.setFormat(esriImageFormat.esriImagePNG); imageType.setReturnType(esriImageReturnType.esriImageReturnMimeData); //set display resolution and height and width imageDisplay = new IImageDisplayProxy(sc.createObject(ImageDisplay.getClsid())); imageDisplay.setDeviceResolution(96D); imageDisplay.setWidth(650); imageDisplay.setHeight(470); //apply type and display to the imagedescription imageDesc = new IImageDescriptionProxy(sc.createObject(ImageDescription.getClsid())); imageDesc.setDisplay(imageDisplay); imageDesc.setType(imageType); //set image return type and execute the exportmapimage method of server imageDesc.getType().setReturnType(esriImageReturnType.esriImageReturnURL); mapImage = server.exportMapImage(mapDesc, imageDesc); //set up parameters to generate the world file double ipixrealw = mapImage.getMapExtent().getWidth() / mapImage.getWidth(); double ulX = mapImage.getMapExtent().getUpperLeft().getX(); double ulY = mapImage.getMapExtent().getUpperLeft().getY(); System.out.println(ipixrealw); System.out.println(0.0); System.out.println(0.0); System.out.println(ipixrealw * -1); System.out.println(ulX); System.out.println(ulY); //Generate string for the servlet to send back to the caller. //The string contains the world file parameters, followed by the //image url, followed by the length of the line in meters /* url_from_server = ipixrealw + "," + 0.0 + "," + 0.0 + "," + ipixrealw * -1 + "," + ulX + "," + ulY + "," + mapImage.getURL() + "," + ipLine.getLength(); */ //+ costLineFC.getFeature(1); url_from_server = "" + "" + "" + "" + mapImage.getURL() + "" + "" + ipLine.getLength() + "" + "" + ""; System.out.println(url_from_server); //delete generated from and to point featureclass shapefiles fClass.delete(); tClass.delete(); //System.exit(1); } catch (Exception e) { try{ fClass.delete(); tClass.delete(); } catch (IOException e1){ System.out.println("Error deleting shapfiles"); e1.printStackTrace(); } System.out.println("We couldn't do the interpolation"); e.printStackTrace(); System.out.println("Threw an exception while trying to get feature count: " + e.getClass() + " :: " + e.getMessage()); error_out = e.getMessage(); error_desc = getStackTrace(e); } finally { try { sc.releaseContext(); } catch (Exception e) { } } return url_from_server; } private static IPoint build_point(String input1) throws IOException { IPoint bPoint = new Point(sc.createObject(Point.getClsid())); Double fromX = null; Double fromY = null; try { System.out.println("test1 " + input1); //fromPoint.substring(0,fromPoint.indexOf(",")) fromX = fromX.valueOf(input1.substring(0,input1.indexOf(","))); System.out.println("test2"); fromY = fromY.valueOf(input1.substring(input1.indexOf(",") + 1)); System.out.println(fromX); bPoint.putCoords(fromX.doubleValue(),fromY.doubleValue()); } catch (IOException e) { System.out.println("Couldn't build the input point."); error_out = e.getMessage(); throw e; } return bPoint; } }