forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPITest.java
More file actions
200 lines (179 loc) · 8.37 KB
/
APITest.java
File metadata and controls
200 lines (179 loc) · 8.37 KB
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// 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.cloud.api;
import com.cloud.utils.exception.CloudRuntimeException;
import com.google.gson.Gson;
import org.apache.cloudstack.api.response.SuccessResponse;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
/**
* Base class for API Test
*
*/
public abstract class APITest {
protected String rootUrl = "http://localhost:8080/client/api";
protected String sessionKey = null;
protected String cookieToSent = null;
/**
* Sending an api request through Http GET
* @param command command name
* @param params command query parameters in a HashMap
* @return http request response string
*/
protected String sendRequest(String command, HashMap<String, String> params) {
try {
// Construct query string
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("command=");
sBuilder.append(command);
if (params != null && params.size() > 0) {
Iterator<String> keys = params.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
sBuilder.append("&");
sBuilder.append(key);
sBuilder.append("=");
sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8"));
}
}
// Construct request url
String reqUrl = rootUrl + "?" + sBuilder.toString();
// Send Http GET request
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (!command.equals("login") && cookieToSent != null) {
// add the cookie to a request
conn.setRequestProperty("Cookie", cookieToSent);
}
conn.connect();
if (command.equals("login")) {
// if it is login call, store cookie
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookieToSent = cookieName + "=" + cookieValue;
}
}
}
// Get the response
StringBuilder response = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
try {
while ((line = rd.readLine()) != null) {
response.append(line);
}
} catch (EOFException ex) {
// ignore this exception
System.out.println("EOF exception due to java bug");
}
rd.close();
return response.toString();
} catch (Exception e) {
throw new CloudRuntimeException("Problem with sending api request", e);
}
}
protected String createMD5String(String password) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new CloudRuntimeException("Error", e);
}
md5.reset();
BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes()));
// make sure our MD5 hash value is 32 digits long...
StringBuffer sb = new StringBuffer();
String pwStr = pwInt.toString(16);
int padding = 32 - pwStr.length();
for (int i = 0; i < padding; i++) {
sb.append('0');
}
sb.append(pwStr);
return sb.toString();
}
protected Object fromSerializedString(String result, Class<?> repCls) {
try {
if (result != null && !result.isEmpty()) {
// get real content
int start;
int end;
if (repCls == LoginResponse.class || repCls == SuccessResponse.class) {
start = result.indexOf('{', result.indexOf('{') + 1); // find
// the
// second
// {
end = result.lastIndexOf('}', result.lastIndexOf('}') - 1); // find
// the
// second
// }
// backwards
} else {
// get real content
start = result.indexOf('{', result.indexOf('{', result.indexOf('{') + 1) + 1); // find
// the
// third
// {
end = result.lastIndexOf('}', result.lastIndexOf('}', result.lastIndexOf('}') - 1) - 1); // find
// the
// third
// }
// backwards
}
if (start < 0 || end < 0) {
throw new CloudRuntimeException("Response format is wrong: " + result);
}
String content = result.substring(start, end + 1);
Gson gson = ApiGsonHelper.getBuilder().create();
return gson.fromJson(content, repCls);
}
return null;
} catch (RuntimeException e) {
throw new CloudRuntimeException("Caught runtime exception when doing GSON deserialization on: " + result, e);
}
}
/**
* Login call
* @param username user name
* @param password password (plain password, we will do MD5 hash here for you)
* @return login response string
*/
protected void login(String username, String password) {
// send login request
HashMap<String, String> params = new HashMap<String, String>();
params.put("response", "json");
params.put("username", username);
params.put("password", password);
String result = this.sendRequest("login", params);
LoginResponse loginResp = (LoginResponse)fromSerializedString(result, LoginResponse.class);
sessionKey = loginResp.getSessionkey();
}
}