1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.jclouds.openstack.functions;
20
21 import static com.google.common.base.Preconditions.checkNotNull;
22 import static org.jclouds.http.HttpUtils.releasePayload;
23 import static org.jclouds.openstack.reference.AuthHeaders.AUTH_TOKEN;
24 import static org.jclouds.openstack.reference.AuthHeaders.URL_SUFFIX;
25
26 import java.net.URI;
27 import java.util.Map.Entry;
28
29 import javax.annotation.Resource;
30 import javax.inject.Inject;
31 import javax.inject.Provider;
32 import javax.ws.rs.core.UriBuilder;
33
34 import org.jclouds.http.HttpRequest;
35 import org.jclouds.http.HttpResponse;
36 import org.jclouds.logging.Logger;
37 import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse;
38 import org.jclouds.rest.InvocationContext;
39
40 import com.google.common.annotations.VisibleForTesting;
41 import com.google.common.base.Function;
42 import com.google.common.collect.ImmutableMap;
43 import com.google.common.collect.ImmutableMap.Builder;
44
45
46
47
48
49
50 public class ParseAuthenticationResponseFromHeaders implements Function<HttpResponse, AuthenticationResponse>,
51 InvocationContext<ParseAuthenticationResponseFromHeaders> {
52
53 @Resource
54 protected Logger logger = Logger.NULL;
55
56 private final Provider<UriBuilder> uriBuilderProvider;
57 private String hostToReplace;
58
59 @Inject
60 public ParseAuthenticationResponseFromHeaders(Provider<UriBuilder> uriBuilderProvider) {
61 this.uriBuilderProvider = uriBuilderProvider;
62 }
63
64
65
66
67 public AuthenticationResponse apply(HttpResponse from) {
68 releasePayload(from);
69 Builder<String, URI> builder = ImmutableMap.<String, URI> builder();
70 for (Entry<String, String> entry : from.getHeaders().entries()) {
71 if (entry.getKey().endsWith(URL_SUFFIX))
72 builder.put(entry.getKey(), getURI(entry.getValue()));
73 }
74 AuthenticationResponse response = new AuthenticationResponse(checkNotNull(from.getFirstHeaderOrNull(AUTH_TOKEN),
75 AUTH_TOKEN), builder.build());
76 logger.debug("will connect to: ", response);
77 return response;
78 }
79
80
81 protected URI getURI(String headerValue) {
82 if (headerValue == null)
83 return null;
84 URI toReturn = URI.create(headerValue);
85 if (!"127.0.0.1".equals(toReturn.getHost()))
86 return toReturn;
87 return uriBuilderProvider.get().uri(toReturn).host(hostToReplace).build();
88 }
89
90 @Override
91 public ParseAuthenticationResponseFromHeaders setContext(HttpRequest request) {
92 return setHostToReplace(request.getEndpoint().getHost());
93 }
94
95 @VisibleForTesting
96 ParseAuthenticationResponseFromHeaders setHostToReplace(String hostToReplace) {
97 this.hostToReplace = hostToReplace;
98 return this;
99 }
100 }