1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.amber.oauth2.client;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.io.PrintWriter;
28 import java.net.HttpURLConnection;
29 import java.net.URL;
30 import java.net.URLConnection;
31 import java.util.Map;
32
33 import org.apache.amber.oauth2.client.request.OAuthClientRequest;
34 import org.apache.amber.oauth2.client.response.OAuthClientResponse;
35 import org.apache.amber.oauth2.client.response.OAuthClientResponseFactory;
36 import org.apache.amber.oauth2.common.OAuth;
37 import org.apache.amber.oauth2.common.exception.OAuthProblemException;
38 import org.apache.amber.oauth2.common.exception.OAuthSystemException;
39 import org.apache.amber.oauth2.common.utils.OAuthUtils;
40
41
42
43
44
45
46
47
48
49 public class URLConnectionClient implements HttpClient {
50
51 public URLConnectionClient() {
52 }
53
54 public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
55 String requestMethod, Class<T> responseClass)
56 throws OAuthSystemException, OAuthProblemException {
57
58 String responseBody = null;
59 URLConnection c = null;
60 int responseCode = 0;
61 try {
62 URL url = new URL(request.getLocationUri());
63
64 c = url.openConnection();
65 responseCode = -1;
66 if (c instanceof HttpURLConnection) {
67 HttpURLConnection httpURLConnection = (HttpURLConnection)c;
68
69 if (headers != null && !headers.isEmpty()) {
70 for (Map.Entry<String, String> header : headers.entrySet()) {
71 httpURLConnection.addRequestProperty(header.getKey(), header.getValue());
72 }
73 }
74
75 if (request.getHeaders() != null) {
76 for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
77 httpURLConnection.addRequestProperty(header.getKey(), header.getValue());
78 }
79 }
80
81 if (!OAuthUtils.isEmpty(requestMethod)) {
82 httpURLConnection.setRequestMethod(requestMethod);
83 if (requestMethod.equals(OAuth.HttpMethod.POST)) {
84 httpURLConnection.setDoOutput(true);
85 OutputStream ost = httpURLConnection.getOutputStream();
86 PrintWriter pw = new PrintWriter(ost);
87 pw.print(request.getBody());
88 pw.flush();
89 pw.close();
90 }
91 } else {
92 httpURLConnection.setRequestMethod(OAuth.HttpMethod.GET);
93 }
94
95 httpURLConnection.connect();
96
97 InputStream inputStream;
98 responseCode = httpURLConnection.getResponseCode();
99 if (responseCode == 400) {
100 inputStream = httpURLConnection.getErrorStream();
101 } else {
102 inputStream = httpURLConnection.getInputStream();
103 }
104
105 responseBody = OAuthUtils.saveStreamAsString(inputStream);
106 }
107 } catch (IOException e) {
108 throw new OAuthSystemException(e);
109 }
110
111 return OAuthClientResponseFactory
112 .createCustomResponse(responseBody, c.getContentType(), responseCode, responseClass);
113 }
114
115 @Override
116 public void shutdown() {
117
118 }
119
120 }