arcgissamples\geoprocessing\customtool\CreateBuffer.java—ArcObjects 10.4 Help for Java | ArcGIS for Desktop
Custom Java geoprocessing tool - Create Buffer
arcgissamples\geoprocessing\customtool\CreateBuffer.java
/* Copyright 2015 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 at <your ArcGIS install location>/DeveloperKit10.4/userestrictions.txt.
* 
*/
package arcgissamples.geoprocessing.customtool;

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

import com.esri.arcgis.geodatabase.DEFeatureClass;
import com.esri.arcgis.geodatabase.DEFeatureClassType;
import com.esri.arcgis.geodatabase.IGPMessages;
import com.esri.arcgis.geodatabase.IGPValue;
import com.esri.arcgis.geodatabase.esriGPMessageSeverity;
import com.esri.arcgis.geoprocessing.BaseGeoprocessingTool;
import com.esri.arcgis.geoprocessing.GPCompositeDataType;
import com.esri.arcgis.geoprocessing.GPFeatureLayer;
import com.esri.arcgis.geoprocessing.GPFeatureLayerType;
import com.esri.arcgis.geoprocessing.GPFeatureRecordSetLayerType;
import com.esri.arcgis.geoprocessing.GPLayerType;
import com.esri.arcgis.geoprocessing.GPLinearUnit;
import com.esri.arcgis.geoprocessing.GPLinearUnitType;
import com.esri.arcgis.geoprocessing.GPParameter;
import com.esri.arcgis.geoprocessing.GeoProcessor;
import com.esri.arcgis.geoprocessing.IGPEnvironmentManager;
import com.esri.arcgis.geoprocessing.IGPParameter;
import com.esri.arcgis.geoprocessing.esriGPParameterDirection;
import com.esri.arcgis.geoprocessing.esriGPParameterType;
import com.esri.arcgis.interop.AutomationException;
import com.esri.arcgis.system.Array;
import com.esri.arcgis.system.IArray;
import com.esri.arcgis.system.IName;
import com.esri.arcgis.system.ITrackCancel;
import com.esri.arcgis.system.VarArray;

public class CreateBuffer extends BaseGeoprocessingTool {
  
  private static final long serialVersionUID = 1L;
  private String toolName = "JavaCreateBuffer";
  private String displayName = "Java Create Buffer Tool";
  private String metadataFileName = toolName + ".xml";
  private static String sw = null;
  private GeoProcessor gp = null;

  public CreateBuffer() {
    try {
      /*
       * Initialize Geoprocessor. The Geoprocessor object represents the
       * Geoprocessing Framework and will be used to execute the system GP tool.
       */
      gp = new GeoProcessor();
      gp.setOverwriteOutput(true);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Returns name of the tool This name appears when executing the tool at the
   * command line or in scripting. This name should be unique to each toolbox
   * and must not contain spaces.
   */
  public String getName() throws IOException, AutomationException {
    return toolName;
  }

  /**
   * Returns Display Name of the tool, as seen in ArcToolbox.
   */
  public String getDisplayName() throws IOException, AutomationException {
    return displayName;
  }

  /**
   * Returns the full name of the tool
   */
  public IName getFullName() throws IOException, AutomationException {
    return (IName) new CBFunctionFactory().getFunctionName(toolName);
  }

  /**
   * Returns an array of paramInfo This is the location where the parameters to
   * the Function Tool are defined. This property returns an IArray of parameter
   * objects (IGPParameter). These objects define the characteristics of the
   * input and output parameters.
   */
  public IArray getParameterInfo() throws IOException, AutomationException {
    IArray parameters = new Array();

    GPCompositeDataType compositeType = new GPCompositeDataType();
    compositeType.addDataType(new GPFeatureLayerType());
    compositeType.addDataType(new GPLayerType());
    compositeType.addDataType(new GPFeatureRecordSetLayerType());

    GPParameter parameter1 = new GPParameter();
    parameter1.setName("in_features");
    parameter1.setDirection(esriGPParameterDirection.esriGPParameterDirectionInput);
    parameter1.setDisplayName("Input Features");
    parameter1.setParameterType(esriGPParameterType.esriGPParameterTypeRequired);
    parameter1.setDataTypeByRef(compositeType);
    parameter1.setValueByRef(new GPFeatureLayer());
    parameters.add(parameter1);

    GPParameter parameter2 = new GPParameter();
    parameter2.setName("in_distance");
    parameter2.setDirection(esriGPParameterDirection.esriGPParameterDirectionInput);
    parameter2.setDisplayName("Buffer Distance");
    parameter2.setParameterType(esriGPParameterType.esriGPParameterTypeRequired);
    parameter2.setDataTypeByRef(new GPLinearUnitType());
    parameter2.setValueByRef(new GPLinearUnit());
    parameters.add(parameter2);

    GPParameter parameter4 = new GPParameter();
    parameter4.setName("out_featureclass");
    parameter4.setDirection(esriGPParameterDirection.esriGPParameterDirectionOutput);
    parameter4.setDisplayName("Output Feature Class");
    parameter4.setParameterType(esriGPParameterType.esriGPParameterTypeRequired);
    parameter4.setDataTypeByRef(new DEFeatureClassType());
    parameter4.setValueByRef(new DEFeatureClass());
    parameters.add(parameter4);

    return parameters;
  }

  /**
   * Called each time the user changes a parameter in the tool dialog or Command
   * Line. This updates the output data of the tool, which extremely useful for
   * building models. After returning from UpdateParameters(), the GP framework
   * calls its internal validation routine to check that a given set of
   * parameter values are of the appropriate number, DataType, and value.
   */
  public void updateParameters(IArray paramvalues, IGPEnvironmentManager envMgr) {
    try {
      // Retrieve the Input Feature Set parameter
      IGPParameter inputFeatureSetParameter = (IGPParameter) paramvalues.getElement(0);
      IGPValue inputFeatureSetValue = gpUtilities.unpackGPValue(inputFeatureSetParameter);
      String inputFS = inputFeatureSetValue.getAsText();
      
      // Retrieve Output Feature Class Parameter
      IGPParameter parameter4 = (IGPParameter) paramvalues.getElement(2);
      IGPValue parameter4Value = gpUtilities.unpackGPValue(parameter4);
      String outputString = parameter4Value.getAsText();

      //force assign a value to output parameter only if its not already specified 
      String outputFC = "", fileName = "";
      if(outputString == null || outputString.isEmpty()){
        // retrieve the environment value for scratch workspace
        sw = gp.getEnvironmentValue("scratchWorkspace").toString();
        if(sw != null && !sw.isEmpty() && inputFS != null){
          fileName = new File(inputFS).getName();
          if (fileName.contains(".")) {
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
          }
          
          File swFile = new File(sw);
          if(swFile.isDirectory() && !swFile.getName().endsWith(".gdb") && 
              !swFile.getName().endsWith(".mdb")){
            outputFC = fileName + "_buffer.shp";
          }
          else{
            outputFC = fileName + "_buffer";
          }
        }
        
        parameter4Value.setAsText(sw + File.separator + outputFC);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Called after returning from the internal validation routine. You can
   * examine the messages created from internal validation and change them if
   * desired.
   */
  public void updateMessages(IArray paramvalues, IGPEnvironmentManager envMgr, IGPMessages gpMessages) {
    try {
      if (gpMessages.getMaxSeverity() == esriGPMessageSeverity.esriGPMessageSeverityError) {
        for (int i = 0; i < gpMessages.getCount(); i++) {
          System.out.println(gpMessages.getMessage(i).getDescription());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Executes the tool
   */
  public void execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages messages)
    throws IOException, AutomationException {
    // Retrieve Input feature class parameter
    IGPParameter parameter1 = (IGPParameter) paramvalues.getElement(0);
    IGPValue parameter1Value = gpUtilities.unpackGPValue(parameter1);
    messages.addMessage("\nSpecified parameter1 value: " + parameter1Value.getAsText());

    // Retrieve Distance parameter
    IGPParameter parameter2 = (IGPParameter) paramvalues.getElement(1);
    IGPValue parameter2Value = gpUtilities.unpackGPValue(parameter2);
    messages.addMessage("\nSpecified parameter2 value: " + parameter2Value.getAsText());

    // Retrieve Output Parameter
    IGPParameter outputParameter = (IGPParameter) paramvalues.getElement(2);
    IGPValue outputValue = gpUtilities.unpackGPValue(outputParameter);
    if (gpUtilities.exists(outputValue)) {
      messages.addMessage("\nOutput already exists. Overwriting it...");
      gpUtilities.delete(outputValue);
    }
    String output = outputValue.getAsText();

    // Use the System GP tool to create a buffer
    VarArray array = new VarArray();
    array.add(parameter1Value.getAsText());// input features
    array.add(output);// output
    array.add(parameter2Value.getAsText());// distance
    array.add("FULL");
    array.add("ROUND");
    array.add("NONE");
    array.add("#");

    // execute buffer tool using geoprocessor
    gp.execute("Buffer_analysis", array, trackcancel);

    messages.addMessage("Output: " + output);
  }

  /**
   * Returns metadata file
   */
  public String getMetadataFile() throws IOException, AutomationException {
    return metadataFileName;
  }

  /**
   * Returns status of license
   */
  public boolean isLicensed() throws IOException, AutomationException {
    // no license checking is being done in this sample.
    return true;
  }
}