Create and add features whose attribute values satisfy a predefined set of contingencies.
Use case
Contingent values are a data design feature that allow you to make values in one field dependent on values in another field. Your choice for a value on one field further constrains the domain values that can be placed on another field. In this way, contingent values enforce data integrity by applying additional constraints to reduce the number of valid field inputs.
For example, a field crew working in a sensitive habitat area may be required to stay a certain distance away from occupied bird nests, but the size of that exclusion area differs depending on the bird's level of protection according to presiding laws. Surveyors can add points of bird nests in the work area, and their selection of the size of the exclusion area will be contingent on the values in other attribute fields.
How to use the sample
Click on the map to add a feature symbolizing a bird's nest. Then choose values describing the nest's status, protection, and buffer size. Notice how different values are available depending on the values of preceding fields. Once the contingent values are validated, click "Save" to add the feature to the map. To delete the feature as you are in progress, click "Delete".
How it works
Create and load the Geodatabase from the mobile geodatabase location on file.
Load the GeodatabaseFeatureTable from the geodatabase.
Create a new FeatureLayer from the geodatabase feature table and add it to the map.
Create a new ArcGISFeature using geodatabaseFeatureTable.createFeature()
Load the ContingentValuesDefinition from the feature table.
Get the required geodatabase feature table field by name using .getField(String fieldName).
Then get the CodedValueDomain of the field with field.getDomain().
Get the coded value domain's CodedValues with codedValueDomain.getCodedValues().
After selecting a value from the initial coded values for the first field, retrieve the remaining valid contingent values for each field as you select the values for the attributes.
i. Get the ContingentValueResults by using geodatabaseFeatureTable.getContingentValues(Feature feature, String field) with the feature and the target field by name.
ii. Get an array of valid ContingentValues from contingentValuesResult.getContingentValuesByFieldGroup().get(String fieldGroupName) with the name of the relevant field group.
iii. Iterate through the array of valid contingent values to create an array of ContingentCodedValue names or the minimum and maximum values of a ContingentRangeValue depending on the type of ContingentValue returned.
Validate the feature's contingent values by using validateContingencyConstraints(Feature feature) with the current feature. If the resulting array is empty, the selected values are valid.
The mobile geodatabase contains birds nests in the Fillmore area, defined with contingent values. Each feature contains information about its status, protection, and buffer size.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/*
* Copyright 2022 Esri.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/package com.esri.samples.add_features_with_contingent_values;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.geometry.Point2D;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.data.ArcGISFeature;
import com.esri.arcgisruntime.data.CodedValue;
import com.esri.arcgisruntime.data.CodedValueDomain;
import com.esri.arcgisruntime.data.ContingencyConstraintViolation;
import com.esri.arcgisruntime.data.ContingentCodedValue;
import com.esri.arcgisruntime.data.ContingentRangeValue;
import com.esri.arcgisruntime.data.ContingentValue;
import com.esri.arcgisruntime.data.ContingentValuesDefinition;
import com.esri.arcgisruntime.data.ContingentValuesResult;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.Geodatabase;
import com.esri.arcgisruntime.data.GeodatabaseFeatureTable;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.layers.ArcGISVectorTiledLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.ColorUtil;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
publicclassAddFeaturesWithContingentValuesController{
@FXMLprivate MapView mapView;
@FXMLprivate ComboBox<CodedValue> statusComboBox;
@FXMLprivate ComboBox<CodedValue> protectionComboBox;
@FXMLprivate Label label;
@FXMLprivate Slider bufferSlider;
@FXMLprivate VBox attributeControlsVBox;
@FXMLprivate Label addFeatureLabel;
@FXMLprivate Label attributesLabel;
private ArcGISFeature newFeature;
private ContingentValuesDefinition contingentValuesDefinition;
private FeatureLayer featureLayer;
private Graphic graphic;
private Geodatabase geodatabase;
private GeodatabaseFeatureTable geodatabaseFeatureTable;
private GraphicsOverlay graphicsOverlay;
privatefinal SimpleBooleanProperty isEditingFeatureProperty = new SimpleBooleanProperty(false);
/**
* Called after FXML loads. Sets up map.
*/publicvoidinitialize(){
try {
// authentication with an API key or named user is required to access basemaps and other location services String yourAPIKey = System.getProperty("apiKey");
ArcGISRuntimeEnvironment.setApiKey(yourAPIKey);
// display the name of the coded values in the attribute combo boxes protectionComboBox.setButtonCell(new CodedValueListCell());
protectionComboBox.setCellFactory(c -> new CodedValueListCell());
statusComboBox.setButtonCell(new CodedValueListCell());
statusComboBox.setCellFactory(c -> new CodedValueListCell());
// control updates to the UI isEditingFeatureProperty.addListener(((observable, oldValue, newValue) -> {
if (newValue) {
addFeatureLabel.setVisible(false);
attributesLabel.setVisible(true);
attributeControlsVBox.setDisable(false);
} else {
addFeatureLabel.setVisible(true);
attributesLabel.setVisible(false);
attributeControlsVBox.setDisable(true);
}
}));
// create a new vector tile package from a vector tile package pathvar vectorTiledLayer = new ArcGISVectorTiledLayer(new File(System.getProperty("data.dir"), "./samples-data" +
"/FillmoreTopographicMap.vtpk").getAbsolutePath());
// create a new basemap with the vector tiled layer and create a new map from itvar basemap = new Basemap(vectorTiledLayer);
ArcGISMap map = new ArcGISMap(basemap);
// set the map to the map view mapView.setMap(map);
// create a graphics overlay to display the nest buffer exclusion area graphicsOverlay = new GraphicsOverlay();
var bufferSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.FORWARD_DIAGONAL,
ColorUtil.colorToArgb(Color.RED), new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID,
ColorUtil.colorToArgb(Color.BLACK), 2));
graphicsOverlay.setRenderer(new SimpleRenderer(bufferSymbol));
// create a new simple marker symbol to mark where new feature is being added on the mapvar symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, ColorUtil.colorToArgb(Color.BLACK), 11);
// add the graphics overlay to the mapview mapView.getGraphicsOverlays().add(graphicsOverlay);
geodatabase = new Geodatabase(new File(System.getProperty("data.dir"),
"./samples-data/ContingentValuesBirdNests.geodatabase").getAbsolutePath());
// wait for the geodatabase to finish loading and check it has loaded geodatabase.addDoneLoadingListener(() -> {
if (geodatabase.getLoadStatus() == LoadStatus.LOADED) {
// get the BirdNests geodatabase feature table, and wait for it to load geodatabaseFeatureTable = geodatabase.getGeodatabaseFeatureTable("BirdNests");
geodatabaseFeatureTable.addDoneLoadingListener(() -> {
if (geodatabaseFeatureTable.getLoadStatus() == LoadStatus.LOADED) {
// create a new feature that matches the schema of the geodatabase feature table newFeature = (ArcGISFeature) geodatabaseFeatureTable.createFeature();
featureLayer = new FeatureLayer(geodatabaseFeatureTable);
map.getOperationalLayers().add(featureLayer);
// when the feature layer has loaded, set the viewpoint on the map to its full extent, and add buffers to// the features featureLayer.addDoneLoadingListener(() -> {
if (featureLayer.getLoadStatus() == LoadStatus.LOADED) {
mapView.setViewpointGeometryAsync(featureLayer.getFullExtent(), 50);
// queries the features in the feature table and applies a buffer to them// set up query parameters for generating buffer graphic queryAndBufferFeatures();
getAndLoadContingentDefinitionAndSetStatusAttribute();
mapView.setDisable(false);
}
});
} elseif (geodatabase.getLoadStatus() == LoadStatus.FAILED_TO_LOAD) {
new Alert(Alert.AlertType.ERROR, "Geodatabase failed to load").show();
}
});
// load the geodatabase feature table geodatabaseFeatureTable.loadAsync();
}
});
// load the geodatabase geodatabase.loadAsync();
// set up mouse clicked listener mapView.setOnMouseClicked(event -> {
if (event.isStillSincePress() && event.getButton() == MouseButton.PRIMARY) {
isEditingFeatureProperty.set(true);
// if the newFeature object is null, create a new feature and set its attributes from the already populated UIif (newFeature == null) {
newFeature = (ArcGISFeature) geodatabaseFeatureTable.createFeature();
newFeature.getAttributes().put("Status", statusComboBox.getSelectionModel().getSelectedItem().getCode());
newFeature.getAttributes().put("Protection",
protectionComboBox.getSelectionModel().getSelectedItem().getCode());
newFeature.getAttributes().put("BufferSize", (int) bufferSlider.getValue());
}
// create a point from where the user clicked Point2D point = new Point2D(event.getX(), event.getY());
Point mapPoint = mapView.screenToLocation(point);
// get the normalized geometry for the clicked location and use it as the feature's geometry Point normalizedMapPoint = (Point) GeometryEngine.normalizeCentralMeridian(mapPoint);
newFeature.setGeometry(normalizedMapPoint);
// check if the graphics overlay already contains the graphic, and if not, add it to the graphics overlayif (!graphicsOverlay.getGraphics().contains(graphic)) {
graphic = new Graphic();
graphicsOverlay.getGraphics().add(graphic);
graphic.setSymbol(symbol);
graphic.setGeometry(newFeature.getGeometry());
graphic.setSelected(true);
} else {
// otherwise, update the geometry of the graphic as the user clicks the map graphic.setGeometry(newFeature.getGeometry());
}
}
});
} catch (Exception e) {
// on any error, display the stack trace e.printStackTrace();
}
}
/**
* Gets and loads the contingent values definition from the geodatabase feature table, checks it contains field groups, and gets
* the coded value domains from the "Status" field.
*/privatevoidgetAndLoadContingentDefinitionAndSetStatusAttribute(){
// get and load the table's contingent values definition. this must be loaded after the table has loaded contingentValuesDefinition = geodatabaseFeatureTable.getContingentValuesDefinition();
contingentValuesDefinition.addDoneLoadingListener(() -> {
// check the contingent values definition has field groups (if the list is empty, there are no// contingent values defined for this tableif (contingentValuesDefinition.getLoadStatus() == LoadStatus.LOADED && !contingentValuesDefinition.getFieldGroups().isEmpty()) {
// get the coded value domains for the "Status" field name CodedValueDomain statusCodedValueDomain =
(CodedValueDomain) geodatabaseFeatureTable.getField("Status").getDomain();
// add each returned coded value as an item to the status combo boxfor (CodedValue codedValue : statusCodedValueDomain.getCodedValues()) {
// requires some mapping of object code back to string statusComboBox.getItems().add(codedValue);
}
// once the combo box has been populated with coded values, select the first oneif (statusComboBox.getItems().size() == statusCodedValueDomain.getCodedValues().size()) {
statusComboBox.getSelectionModel().selectFirst();
}
// check the contingent values are valid contingentValuesAreValid();
}
});
contingentValuesDefinition.loadAsync();
}
/**
* Handles interaction with the status combo box. Gets the coded value chosen from the combo box and sets it as
* the feature's "Status" attribute.
*/@FXMLprivatevoidhandleStatusComboBox(){
// add "Status" attribute to the new feature: this will allow the related contingent value in the// "Protected" field to be detected newFeature.getAttributes().put("Status", statusComboBox.getSelectionModel().getSelectedItem().getCode());
// get contingent values for the protection field ContingentValuesResult protectionContingentValues = geodatabaseFeatureTable.getContingentValues(newFeature,
"Protection");
// get contingent values by field group for the protection field group List<ContingentValue> protectionFieldGroupValues =
protectionContingentValues.getContingentValuesByFieldGroup().get("ProtectionFieldGroup");
List<CodedValue> contingentCodedValues = FXCollections.observableArrayList();
protectionFieldGroupValues.forEach(contingentValue -> {
var contingentCodedValue = (ContingentCodedValue) contingentValue; // cast to required contingent value type contingentCodedValues.add(contingentCodedValue.getCodedValue());
});
// add contingent coded values to the protection attribute combobox protectionComboBox.setItems(FXCollections.observableArrayList(contingentCodedValues));
// once the combo box has populated, select the first coded valueif (protectionComboBox.getItems().size() == protectionFieldGroupValues.size()) {
protectionComboBox.getSelectionModel().selectFirst();
}
}
/**
* Handles interaction with the protection combo box. Gets the coded value chosen from the combo box and sets it as
* the feature's "Protection" attribute. Also sets the min and max value of the bufferSlider based on the contingent
* range value of the returned contingent range value.
*/@FXMLprivatevoidhandleProtectionComboBox(){
if (protectionComboBox.getSelectionModel().getSelectedItem() != null) {
// put the value chosen from the protection combobox as the attribute for the new feature newFeature.getAttributes().put("Protection", protectionComboBox.getSelectionModel().getSelectedItem().getCode());
// get contingent values for the buffer size field ContingentValuesResult bufferContingentValues = geodatabaseFeatureTable.getContingentValues(newFeature,
"BufferSize");
// get contingent range values for the buffer size field group ContingentRangeValue bufferRangeValue =
(ContingentRangeValue) bufferContingentValues.getContingentValuesByFieldGroup()
.get("BufferSizeFieldGroup").get(0); // cast to required contingent value type// get the minimum and maximum value from the buffer contingent range valuesvar minValue = (Integer) bufferRangeValue.getMinValue();
var maxValue = (Integer) bufferRangeValue.getMaxValue();
// set the min and max value of the buffer slider depending on the returned value of the contingent range value bufferSlider.setMin(minValue);
bufferSlider.setMax(maxValue);
bufferSlider.setValue(minValue);
// set the "BufferSize" attribute to that of the value of the slider newFeature.getAttributes().put("BufferSize", (int) bufferSlider.getValue());
// update label to show buffer size value label.setText("Exclusion Area Buffer Size: " + (Math.round(bufferSlider.getValue())));
}
}
/**
* Handles interaction with the buffer slider. Gets the buffer slider value and sets is as the feature's "BufferSize"
* attribute.
*/@FXMLprivatevoidhandleBufferSlider(){
// set the initial attribute and the text to the min of the contingent range value newFeature.getAttributes().put("BufferSize", (int) Math.round(bufferSlider.getValue()));
label.setText("Exclusion Area Buffer Size: " + (Math.round(bufferSlider.getValue())));
}
/**
* Queries features in the geodatabase feature table, and creates a buffer for each feature based on its "BufferSize"
* attribute.
*/privatevoidqueryAndBufferFeatures(){
// create new query parameters and set its where clausevar queryParameters = new QueryParameters();
queryParameters.setWhereClause("BufferSize > 0");
// get all the features that have buffer size greater than zerovar results = geodatabaseFeatureTable.queryFeaturesAsync(queryParameters);
results.addDoneListener(() -> {
try {
// clear the existing buffer graphics graphicsOverlay.getGraphics().clear();
// get the features from the resultvar featureQueryResult = results.get();
for (Feature feature : featureQueryResult) {
// get the feature's buffer size attribute and create a new buffer geometry from it Integer bufferDistance = (Integer) feature.getAttributes().get("BufferSize");
Geometry buffer = GeometryEngine.buffer(feature.getGeometry(), bufferDistance);
Graphic bufferGraphic = new Graphic(buffer);
graphicsOverlay.getGraphics().add(bufferGraphic);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
});
}
/**
* Validate contingency constraints of the new feature. If there are constraints, an error dialog will display.
*/privatebooleancontingentValuesAreValid(){
List<ContingencyConstraintViolation> contingencyConstraintViolations = geodatabaseFeatureTable
.validateContingencyConstraints(newFeature);
int numberOfViolations = contingencyConstraintViolations.size();
// if the number of contingency constraint violations is zero, the attribute map satisfies all contingenciesif (numberOfViolations == 0) {
returntrue;
} else {
List<String> fieldGroupsNames = new ArrayList<>();
contingencyConstraintViolations.forEach(contingencyConstraintViolation -> {
fieldGroupsNames.add(contingencyConstraintViolation.getFieldGroup().getName());
});
String errorType = contingencyConstraintViolations.get(0).getType().toString();
new Alert(Alert.AlertType.ERROR,
errorType + "! " + numberOfViolations + " violations found in: " + Arrays.toString(fieldGroupsNames.toArray())).show();
returnfalse;
}
}
/**
* Handles interaction with the save button. Checks that the contingent values set to the feature are valid and
* adds the feature to the geodatabase feature table.
*/@FXMLprivatevoidhandleSaveButton(){
if (contingentValuesAreValid()) {
// add the feature to the table geodatabaseFeatureTable.addFeatureAsync(newFeature).addDoneListener(() -> {
// query and buffer features again now that a new feature has been added to the table queryAndBufferFeatures();
// now the new feature has been added set it to null to continue adding new features newFeature = null;
// reset the UI until the user clicks to add a point isEditingFeatureProperty.set(false);
graphic.setSelected(false);
});
}
}
/**
* Handles interaction with the Delete button. Deletes the created feature from the geodatabase feature table.
*/@FXMLprivatevoiddeleteFeature(){
// delete the feature from the geodatabase feature tablevar delete = geodatabaseFeatureTable.deleteFeatureAsync(newFeature);
// now the new feature has been deleted set it to null to continue adding new features, and remove the graphic delete.addDoneListener(() -> {
newFeature = null;
graphicsOverlay.getGraphics().remove(graphic);
});
// reset the UI until the user clicks to add a point isEditingFeatureProperty.set(false);
graphic.setSelected(false);
}
/**
* Stops and releases all resources used in application.
*/voidterminate(){
if (mapView != null) {
mapView.dispose();
geodatabase.close();
}
}
}