1 /*
2 * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License").
5 * You may not use this file except in compliance with the License.
6 * A copy of the License is located at
7 *
8 * http://aws.amazon.com/apache2.0
9 *
10 * or in the "license" file accompanying this file. This file is distributed
11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12 * express or implied. See the License for the specific language governing
13 * permissions and limitations under the License.
14 */
15 package com.amazonaws.services.sqs;
16
17 import java.net.URI;
18 import java.net.URISyntaxException;
19 import java.util.List;
20 import java.util.Map;
21
22 import com.amazonaws.AmazonClientException;
23 import com.amazonaws.Request;
24 import com.amazonaws.handlers.AbstractRequestHandler;
25
26 /**
27 * Custom request handler for SQS that processes the request before it gets routed to the client
28 * runtime layer.
29 * <p>
30 * SQS MessageQueue operations take a QueueUrl parameter that needs special handling to update the
31 * endpoint and resource path on the request before it's executed.
32 */
33 public class QueueUrlHandler extends AbstractRequestHandler {
34 private static final String QUEUE_URL_PARAMETER = "QueueUrl";
35
36 public void beforeRequest(Request<?> request) {
37
38 final Map<String, List<String>> requestParams = request.getParameters();
39 final List<String> queueURLParam = requestParams.get(QUEUE_URL_PARAMETER);
40 if (queueURLParam != null && !queueURLParam.isEmpty() ) {
41 List<String> queueURLParameter = requestParams.remove(QUEUE_URL_PARAMETER);
42 String queueUrl = queueURLParameter.iterator().next();
43
44 try {
45 URI uri = new URI(queueUrl);
46 request.setResourcePath(uri.getPath());
47
48 if (uri.getHost() != null) {
49 // If the URI has a host specified, set the request's endpoint to the queue URLs
50 // endpoint, so that queue URLs from different regions will send the request to
51 // the correct endpoint.
52 URI uriWithoutPath = new URI(uri.toString().replace(uri.getPath(), ""));
53 request.setEndpoint(uriWithoutPath);
54 }
55 } catch (URISyntaxException e) {
56 throw new AmazonClientException("Unable to parse SQS queue URL '" + queueUrl + "'", e);
57 }
58 }
59 }
60 }
61