Compute the slope of a raster dataset
arcgissamples\scenario\RasterDatasetSlope.java
/* Copyright 2010 ESRI
* 
* All rights reserved under the copyright laws of the United States
* and applicable international laws, treaties, and conventions.
* 
* You may freely redistribute and use this sample code, with or
* without modification, provided you include the original copyright
* notice and use restrictions.
* 
* See the use restrictions.
* 
*/
package arcgissamples.scenario;

import java.io.File;
import java.io.IOException;

import com.esri.arcgis.datasourcesraster.Raster;
import com.esri.arcgis.datasourcesraster.RasterWorkspace;
import com.esri.arcgis.datasourcesraster.RasterWorkspaceFactory;
import com.esri.arcgis.geoanalyst.RasterSurfaceOp;
import com.esri.arcgis.geoanalyst.esriGeoAnalysisSlopeEnum;
import com.esri.arcgis.geodatabase.IGeoDataset;
import com.esri.arcgis.geodatabase.IGeoDatasetProxy;
import com.esri.arcgis.geodatabase.Workspace;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseExtensionCode;
import com.esri.arcgis.system.esriLicenseProductCode;
import com.esri.arcgis.system.esriLicenseStatus;

public class RasterDatasetSlope {
  public RasterDatasetSlope(){
    
  }
  
  /**
   * Main Method - The console application entry point.
   * 
   * @param args String[] Command line argument
   */
  public static void main(String[] args) {
    System.out.println("Starting RasterDatasetSlope - An ArcObjects SDK Developer Sample");
    
    try{
      //Initialize engine console application
      EngineInitializer.initializeEngine();
      
      //Initialize ArcGIS license
      AoInitialize aoInit = new AoInitialize();
      initializeArcGISLicenses(aoInit);
      
      //Get DEVKITHOME Home
      String devKitHome = System.getenv("AGSDEVKITJAVA");
      
      //Data access setup
      String demPath = devKitHome + "java" + File.separator + "samples" + File.separator 
                    + "data" + File.separator + "raster";
      String demName = "dem1";
      
      //Data output setup
      String outPath = getOutputDir() + File.separator + "createslope";
      String outName = "slope";
      String outFormat = "GRID";

      File outDataFile = new File(outPath, outName);
      if (outDataFile.exists()) {
        System.out.println("Output datafile already exists: " + outDataFile.getAbsolutePath());
        System.out.println("Delete it (plus .shx and .dbf files) and rerun");
        System.exit(-1);
      }
      
      System.out.println("Calculating Slope ...");
      RasterDatasetSlope rasterDatasetSlope = new RasterDatasetSlope();
      Raster raster = rasterDatasetSlope.buildSlope(demPath, demName, outPath);
      
      System.out.println("Saving Workspace ...");
      rasterDatasetSlope.saveToDisk(raster, outPath, outName, outFormat);
      
      System.out.println("Output raster data created in " + outDataFile.getParent());    
      
      //Ensure any ESRI libraries are unloaded in the correct order
      aoInit.shutdown();
    }catch(Exception e){
      System.out.println("Error: " + e.getMessage());
      e.printStackTrace();
      System.exit(-1);
    }
  }
  
  /**
   * Checks to see if an ArcGIS Engine Runtime license is available.
   * If so, then the ArcGIS License is initialized.  In addition, this
   * sample uses the spatial analyst extension and is checked out.
   * 
   * @param aoInit The AoInitialize object instantiated in the main method.
   */
  static void initializeArcGISLicenses(AoInitialize aoInit) {
    try {
      AoInitialize ao = new AoInitialize();
      
      if (ao.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeEngine) 
          == esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
      else if (ao.isProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeArcView) 
          == esriLicenseStatus.esriLicenseAvailable)
        ao.initialize(esriLicenseProductCode.esriLicenseProductCodeArcView);
      
      ao.checkOutExtension(esriLicenseExtensionCode.esriLicenseExtensionCodeSpatialAnalyst);
    } catch (Exception e) {e.printStackTrace();}
  }

  /**
   * saveOnDisk - persist raster to disk
   */
  private void saveToDisk(Raster raster, String wkspPath, String outName, String outFormat) throws IOException{
    RasterWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactory();
    Workspace workspace = new Workspace(rasterWorkspaceFactory.openFromFile(wkspPath, 0));
    raster.saveAs(outName, workspace, outFormat);
  }

  /**
   *  buildSlope - builds slope on a dem dataset and saves to disk
   *
   * @param   srcPath - path to DEM dataset on disk
   * @param   srcName - DEM name
   * @return  Raster
   */
  @SuppressWarnings("all")
  public Raster buildSlope(String srcPath, String srcName, String outPath) throws IOException {
    // If the output directory does not exist, create it.
    File outPathDir = new File(outPath);
    if (!outPathDir.exists()) {
      outPathDir.mkdir();
    }

    // Get access to the source raster data
    RasterWorkspaceFactory rasterWorkspaceFactory = new RasterWorkspaceFactory();
    Workspace srcWorkspace = new Workspace(rasterWorkspaceFactory.openFromFile(srcPath, 0));
    RasterWorkspace srcRasterWorkspace = new RasterWorkspace(srcWorkspace);
    IGeoDataset srcRasterDataset = new IGeoDatasetProxy(srcRasterWorkspace.openRasterDataset(srcName));

    // Create an output workspace
    Workspace outWorkspace = new Workspace(rasterWorkspaceFactory.openFromFile(outPath, 0));

    // Create a RasterSurfaceOp operator and set its workspace to be the output workspace
    RasterSurfaceOp rasterSurfaceOp = new RasterSurfaceOp();
    rasterSurfaceOp.setOutWorkspaceByRef(outWorkspace);

    // Calculate and create the slope data for of the source raster dataset,
    // put the data in the output workspace, and return the raster
    return new Raster(rasterSurfaceOp.slope(srcRasterDataset, esriGeoAnalysisSlopeEnum.esriGeoAnalysisSlopeDegrees, null));
  }

  /**
   * Convenience method to generate an output directory based on the operating
   * system that the sample is being executed on. 
   * 
   * @return A path to the new directory is return
   */
  private static String getOutputDir() {
    String userDir;
    
    //Get the operating systems user profile or home location depending
    //on which operating system this sample is executed on.
    if(System.getProperty("os.name").toLowerCase().indexOf("win") > -1){
      userDir = System.getenv("UserProfile");
    }else{
      userDir = System.getenv("HOME");
    }
      
    String outputDir = userDir + File.separator + "arcgis_sample_output";
    
    System.out.println("Creating output directory - " + outputDir);
    
    new File(outputDir).mkdir();
    
    return outputDir;
  }
}