Skip to content

Commit bf024b8

Browse files
committed
rolled in review comments
1 parent 0655f63 commit bf024b8

File tree

5 files changed

+212
-148
lines changed

5 files changed

+212
-148
lines changed

.doc_gen/metadata/location_metadata.yaml

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,32 @@ location_CalculateRoute:
133133
- location.java2.calc.distance.main
134134
services:
135135
location: {CalculateRoute}
136+
location_DeleteGeofenceCollection:
137+
languages:
138+
Java:
139+
versions:
140+
- sdk_version: 2
141+
github: javav2/example_code/location
142+
sdkguide:
143+
excerpts:
144+
- description:
145+
snippet_tags:
146+
- location.java2.delete.collection.main
147+
services:
148+
location: {DeleteGeofenceCollection}
149+
location_DeleteKey:
150+
languages:
151+
Java:
152+
versions:
153+
- sdk_version: 2
154+
github: javav2/example_code/location
155+
sdkguide:
156+
excerpts:
157+
- description:
158+
snippet_tags:
159+
- location.java2.delete.key.main
160+
services:
161+
location: {DeleteKey}
136162
location_DeleteMap:
137163
languages:
138164
Java:

javav2/example_code/location/src/main/java/com/example/location/HelloLocation.java

Lines changed: 35 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,27 @@
1616
import java.util.concurrent.CompletableFuture;
1717

1818
// snippet-start:[location.java2.hello.main]
19+
/**
20+
* Before running this Java V2 code example, set up your development
21+
* environment, including your credentials.
22+
*
23+
* For more information, see the following documentation topic:
24+
*
25+
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
26+
*
27+
* In addition, you need to create a collection using the AWS Management
28+
* console. For information, see the following documentation.
29+
*
30+
* https://docs.aws.amazon.com/location/latest/developerguide/geofence-gs.html
31+
32+
*/
1933
public class HelloLocation {
2034

2135
private static LocationAsyncClient locationAsyncClient;
2236
private static final Logger logger = LoggerFactory.getLogger(HelloLocation.class);
2337

2438
// This Singleton pattern ensures that only one `LocationClient`
25-
// instance is used throughout the application.
39+
// instance.
2640
private static LocationAsyncClient getClient() {
2741
if (locationAsyncClient == null) {
2842
SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
@@ -50,31 +64,42 @@ public static void main(String[] args) {
5064
final String usage = """
5165
5266
Usage:
53-
<colletionName>
67+
<collectionName>
5468
5569
Where:
56-
colletionName - The Amazon location collection name.
70+
collectionName - The Amazon location collection name.
5771
""";
5872

5973
if (args.length != 1) {
6074
System.out.println(usage);
6175
System.exit(1);
6276
}
6377

64-
String colletionName = args[0];
65-
listGeofences(colletionName);
78+
String collectionName = args[0];
79+
listGeofences(collectionName);
6680
}
6781

82+
/**
83+
* Lists geofences from a specified geofence collection asynchronously.
84+
*
85+
* @param collectionName The name of the geofence collection to list geofences from.
86+
* @return A {@link CompletableFuture} representing the result of the asynchronous operation.
87+
* The future completes when all geofences have been processed and logged.
88+
*/
6889
public static CompletableFuture<Void> listGeofences(String collectionName) {
6990
ListGeofencesRequest geofencesRequest = ListGeofencesRequest.builder()
70-
.collectionName(collectionName)
71-
.build();
91+
.collectionName(collectionName)
92+
.build();
7293

7394
ListGeofencesPublisher paginator = getClient().listGeofencesPaginator(geofencesRequest);
7495
CompletableFuture<Void> future = paginator.subscribe(response -> {
75-
response.entries().forEach(geofence ->
76-
logger.info("Geofence ID: " + geofence.geofenceId())
77-
);
96+
if (response.entries().isEmpty()) {
97+
logger.info("No Geofences were found in the collection.");
98+
} else {
99+
response.entries().forEach(geofence ->
100+
logger.info("Geofence ID: " + geofence.geofenceId())
101+
);
102+
}
78103
});
79104
return future;
80105
}

javav2/example_code/location/src/main/java/com/example/location/scenario/LocationActions.java

Lines changed: 37 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
import software.amazon.awssdk.services.geoplaces.model.SearchNearbyRequest;
1717
import software.amazon.awssdk.services.geoplaces.model.SearchNearbyResponse;
1818
import software.amazon.awssdk.services.geoplaces.model.SearchTextRequest;
19-
import software.amazon.awssdk.services.geoplaces.model.SearchTextResponse;
2019
import software.amazon.awssdk.services.location.LocationAsyncClient;
2120
import software.amazon.awssdk.services.location.model.AccessDeniedException;
2221
import software.amazon.awssdk.services.location.model.ApiKeyRestrictions;
@@ -157,66 +156,58 @@ public CompletableFuture<SearchNearbyResponse> searchNearBy() {
157156
*
158157
* @param searchQuery the search query to be used for the place search (ex, coffee shop)
159158
*/
160-
public CompletableFuture<SearchTextResponse> searchText(String searchQuery) {
159+
public CompletableFuture<Void> searchText(String searchQuery) {
161160
double latitude = 37.7749; // San Francisco
162161
double longitude = -122.4194;
163162
List<Double> queryPosition = List.of(longitude, latitude);
164163

165164
SearchTextRequest request = SearchTextRequest.builder()
166-
.queryText(searchQuery)
167-
.biasPosition(queryPosition)
168-
.build();
165+
.queryText(searchQuery)
166+
.biasPosition(queryPosition)
167+
.build();
169168

170169
return getGeoPlacesClient().searchText(request)
171-
.whenComplete((response, exception) -> {
172-
if (exception != null) {
173-
Throwable cause = exception.getCause();
174-
if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
175-
throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
170+
.thenCompose(response -> {
171+
if (response.resultItems().isEmpty()) {
172+
logger.info("No places found.");
173+
return CompletableFuture.completedFuture(null);
176174
}
177-
throw new CompletionException("Error performing place search", exception);
178-
}
179175

180-
// Process the response and fetch detailed information about the place.
181-
response.resultItems().stream().findFirst().ifPresent(result -> {
182-
String placeId = result.placeId(); // Get Place ID
176+
// Get the first place ID
177+
String placeId = response.resultItems().get(0).placeId();
183178
logger.info("Found Place with id: " + placeId);
184179

185-
// Fetch detailed info using getPlace.
180+
// Fetch detailed info using getPlace
186181
GetPlaceRequest getPlaceRequest = GetPlaceRequest.builder()
187-
.placeId(placeId)
188-
.build();
189-
190-
getGeoPlacesClient().getPlace(getPlaceRequest)
191-
.whenComplete((placeResponse, placeException) -> {
192-
if (placeException != null) {
193-
Throwable cause = placeException.getCause();
194-
if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
195-
throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
182+
.placeId(placeId)
183+
.build();
184+
185+
return getGeoPlacesClient().getPlace(getPlaceRequest)
186+
.thenAccept(placeResponse -> {
187+
logger.info("Detailed Place Information:");
188+
logger.info("Name: " + placeResponse.placeType().name());
189+
logger.info("Address: " + placeResponse.address().label());
190+
191+
if (placeResponse.foodTypes() != null && !placeResponse.foodTypes().isEmpty()) {
192+
logger.info("Food Types:");
193+
placeResponse.foodTypes().forEach(foodType -> {
194+
logger.info(" - " + foodType);
195+
});
196+
} else {
197+
logger.info("No food types available.");
196198
}
197-
throw new CompletionException("Error fetching place details", placeException);
198-
}
199-
200-
// Print detailed place information.
201-
logger.info("Detailed Place Information:");
202-
logger.info("Name: " + placeResponse.placeType().name());
203-
logger.info("Address: " + placeResponse.address().label());
204-
205-
// Print each food type (if any).
206-
if (placeResponse.foodTypes() != null && !placeResponse.foodTypes().isEmpty()) {
207-
logger.info("Food Types:");
208-
placeResponse.foodTypes().forEach(foodType -> {
209-
logger.info(" - " + foodType);
210-
});
211-
} else {
212-
logger.info("No food types available.");
213-
}
214-
215-
logger.info("-------------------------");
216-
});
199+
logger.info("-------------------------");
200+
});
201+
})
202+
.exceptionally(exception -> {
203+
Throwable cause = exception.getCause();
204+
if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
205+
throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
206+
}
207+
throw new CompletionException("Error performing place search", exception);
217208
});
218-
});
219209
}
210+
220211
// snippet-end:[geoplaces.java2.search.text.main]
221212

222213
// snippet-start:[geoplaces.java2.geocode.main]

javav2/example_code/location/src/main/java/com/example/location/scenario/LocationScenario.java

Lines changed: 55 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@
1919
import java.util.concurrent.CompletionException;
2020

2121
// snippet-start:[location.java2.scenario.main]
22+
/*
23+
* Before running this Java V2 code example, set up your development
24+
* environment, including your credentials.
25+
*
26+
* For more information, see the following documentation topic:
27+
*
28+
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
29+
*
30+
*/
2231
public class LocationScenario {
2332

2433
public static final String DASHES = new String(new char[80]).replace("\0", "-");
@@ -43,18 +52,18 @@ public static void main(String[] args) {
4352
deviceId - The ID of the device (e.g., "iPhone-112356").
4453
""";
4554

46-
if (args.length != 7) {
47-
logger.info(usage);
48-
return;
49-
}
55+
//if (args.length != 7) {
56+
// logger.info(usage);
57+
// return;
58+
// }
5059

51-
String mapName = args[0];
52-
String keyName = args[1];
53-
String collectionName = args[2];
54-
String geoId = args[3];
55-
String trackerName = args[4];
56-
String calculatorName = args[5];
57-
String deviceId = args[6];
60+
String mapName = "AWSMap200" ; //args[0];
61+
String keyName = "AWSApiKey200" ; //args[1];
62+
String collectionName = "AWSLocationCollection200" ; //args[2];
63+
String geoId = "geoId200" ; //args[3];
64+
String trackerName = "geoTracker200" ; //args[4];
65+
String calculatorName = "AWSRouteCalc200" ; //args[5];
66+
String deviceId = "iPhone-112356" ; //args[6];
5867

5968
logger.info("""
6069
AWS Location Service is a fully managed service offered by Amazon Web Services (AWS) that
@@ -82,6 +91,8 @@ location names into geographic coordinates (latitude and longitude),\s
8291
try {
8392
runScenario(mapName, keyName, collectionName, geoId, trackerName, calculatorName, deviceId);
8493
} catch (RuntimeException e) {
94+
// Clean up AWS Resources.
95+
cleanUp(mapName, keyName, collectionName, trackerName, calculatorName);
8596
logger.info(e.getMessage());
8697
}
8798
}
@@ -145,9 +156,10 @@ restrict API keys to specific AWS Location operations (e.g., only
145156
In order to get the MAP URL, you need to get the API Key value.
146157
You can get the key value using the AWS Management Console under
147158
Location Services. This operation cannot be completed using the
148-
AWS SDK.
159+
AWS SDK. For more information about getting the key value, see
160+
https://docs.aws.amazon.com/location/latest/developerguide/using-apikeys.html.
149161
""");
150-
String mapUrl = "https://maps.geo.aws.amazon.com/maps/v0/maps/{MapName}/tiles/{z}/{x}/{y}?key={KeyValue}";
162+
String mapUrl = "https://maps.geo.aws.amazon.com/maps/v0/maps/"+mapName+"/tiles/{z}/{x}/{y}?key={KeyValue}";
151163
logger.info("Embed this URL in your Web app: " + mapUrl);
152164
logger.info("");
153165
waitForInputToContinue(scanner);
@@ -291,7 +303,7 @@ restrict API keys to specific AWS Location operations (e.g., only
291303
waitForInputToContinue(scanner);
292304
try {
293305
CalculateRouteResponse response = locationActions.calcDistanceAsync(calculatorName).join();
294-
logger.info("Successfully calculated route. The distance is {}", response.summary().distance());
306+
logger.info("Successfully calculated route. The distance in kilometers is {}", response.summary().distance());
295307
} catch (CompletionException ce) {
296308
Throwable cause = ce.getCause();
297309
if (cause instanceof ResourceNotFoundException) {
@@ -325,7 +337,7 @@ restrict API keys to specific AWS Location operations (e.g., only
325337
waitForInputToContinue(scanner);
326338

327339
logger.info("Now we are going to perform a nearby Search.");
328-
waitForInputToContinue(scanner);
340+
//waitForInputToContinue(scanner);
329341
locationActions.searchNearBy().join();
330342
waitForInputToContinue(scanner);
331343
} catch (CompletionException ce) {
@@ -343,21 +355,7 @@ restrict API keys to specific AWS Location operations (e.g., only
343355
logger.info("Would you like to delete the AWS Location Services resources? (y/n)");
344356
String delAns = scanner.nextLine().trim();
345357
if (delAns.equalsIgnoreCase("y")) {
346-
try {
347-
locationActions.deleteMap(mapName).join();
348-
locationActions.deleteKey(keyName).join();
349-
locationActions.deleteGeofenceCollectionAsync(collectionName).join();
350-
locationActions.deleteTracker(trackerName).join();
351-
locationActions.deleteRouteCalculator(calculatorName).join();
352-
} catch (CompletionException ce) {
353-
Throwable cause = ce.getCause();
354-
if (cause instanceof ResourceNotFoundException) {
355-
logger.info("The resource was not found: {}", cause.getMessage(), cause);
356-
} else {
357-
logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
358-
}
359-
return;
360-
}
358+
cleanUp(mapName, keyName, collectionName, trackerName, calculatorName);
361359
} else {
362360
logger.info("The AWS resources will not be deleted.");
363361
}
@@ -369,6 +367,33 @@ restrict API keys to specific AWS Location operations (e.g., only
369367
logger.info(DASHES);
370368
}
371369

370+
/**
371+
* Cleans up resources by deleting the specified map, key, geofence collection, tracker, and route calculator.
372+
*
373+
* @param mapName The name of the map to delete.
374+
* @param keyName The name of the key to delete.
375+
* @param collectionName The name of the geofence collection to delete.
376+
* @param trackerName The name of the tracker to delete.
377+
* @param calculatorName The name of the route calculator to delete.
378+
*/
379+
private static void cleanUp(String mapName, String keyName, String collectionName, String trackerName, String calculatorName) {
380+
try {
381+
locationActions.deleteMap(mapName).join();
382+
locationActions.deleteKey(keyName).join();
383+
locationActions.deleteGeofenceCollectionAsync(collectionName).join();
384+
locationActions.deleteTracker(trackerName).join();
385+
locationActions.deleteRouteCalculator(calculatorName).join();
386+
} catch (CompletionException ce) {
387+
Throwable cause = ce.getCause();
388+
if (cause instanceof ResourceNotFoundException) {
389+
logger.info("The resource was not found: {}", cause.getMessage(), cause);
390+
} else {
391+
logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
392+
}
393+
return;
394+
}
395+
}
396+
372397
private static void waitForInputToContinue(Scanner scanner) {
373398
while (true) {
374399
logger.info("");

0 commit comments

Comments
 (0)