This repository was archived by the owner on Mar 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSemantics3Request.java
More file actions
274 lines (249 loc) · 9.08 KB
/
Semantics3Request.java
File metadata and controls
274 lines (249 loc) · 9.08 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package com.semantics3.api;
import com.semantics3.errors.Semantics3Exception;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.HashMap;
public class Semantics3Request{
final static private String API_DOMAIN = "api.semantics3.com";
final static private String API_BASE = "https://" + API_DOMAIN + "/v1/";
private String apiKey;
private String apiSecret;
private String endpoint;
private String endpointURL;
private OAuthConsumer consumer;
private HashMap<String,JSONObject> query = new HashMap<String, JSONObject>();
private JSONObject queryResult;
private StringBuffer urlBuilder;
private ConnectionProperties connectionProperties;
public Semantics3Request(String apiKey, String apiSecret, String endpoint, ConnectionProperties connectionProperties) {
if (apiKey == null) {
throw new Semantics3Exception(
"API Credentials Missing",
"You did not supply an apiKey. Please sign up at https://semantics3.com/ to obtain your api_key."
);
}
if (apiSecret == null) {
throw new Semantics3Exception(
"API Credentials Missing",
"You did not supply an apiSecret. Please sign up at https://semantics3.com/ to obtain your api_key."
);
}
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.consumer = new DefaultOAuthConsumer(apiKey, apiSecret);
consumer.setTokenWithSecret("", "");
this.endpoint = endpoint;
this.connectionProperties = connectionProperties;
}
public Semantics3Request(String apiKey, String apiSecret, ConnectionProperties connectionProperties) {
this(apiKey, apiSecret, null, connectionProperties);
}
public Semantics3Request(String apiKey, String apiSecret, String endpoint) {
this(apiKey, apiSecret, endpoint, new ConnectionProperties());
}
public Semantics3Request(String apiKey, String apiSecret) {
this(apiKey, apiSecret, null, new ConnectionProperties());
}
protected JSONObject fetch(String endpoint, String params) throws
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException, URISyntaxException {
String req = new StringBuffer()
.append(API_BASE)
.append(endpoint)
.append("?q=")
.append(URLEncoder.encode(params, "UTF-8"))
.toString();
HttpURLConnection request = new ConnectionBuilder().buildConnection(req, this.connectionProperties);
consumer.sign(request);
request.connect();
try {
JSONObject json = new JSONObject(new JSONTokener(request.getInputStream()));
if (!json.has("code")){
json.put("code", "OK");
}
return json;
}
catch (SocketTimeoutException e) {
throw e;
}
catch (IOException e) {
InputStream error = ((HttpURLConnection) request).getErrorStream();
JSONObject json = new JSONObject(new JSONTokener(error));
if (!json.has("code")) {
json.put("code", "Error");
}
else {
Object value = json.get("code");
json.put("code", value.toString());
}
return json;
}
}
protected JSONObject fetch(String endpoint, String method, HashMap<String, Object> params) throws
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException, URISyntaxException {
String req = new StringBuffer()
.append(API_BASE)
.append(endpoint)
.toString();
HttpURLConnection request = new ConnectionBuilder().buildConnection(req, this.connectionProperties);
if(method == "POST") {
request.setDoInput(true);
request.setDoOutput(true);
request.setRequestMethod(method);
request.setRequestProperty("Content-Type", "application/json");
request.setRequestProperty("Accept", "application/json");
consumer.sign(request);
JSONObject jsonParams = new JSONObject(params);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(request.getOutputStream());
outputStreamWriter.write(jsonParams.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
}
else {
request.setRequestMethod(method);
consumer.sign(request);
}
request.connect();
try {
JSONObject json = new JSONObject(new JSONTokener(request.getInputStream()));
if (!json.has("code")){
json.put("code", "OK");
}
return json;
}
catch (SocketTimeoutException e) {
throw e;
}
catch (IOException e) {
InputStream error = ((HttpURLConnection) request).getErrorStream();
JSONObject json = new JSONObject(new JSONTokener(error));
if (!json.has("code")) {
json.put("code", "Error");
}
else {
Object value = json.get("code");
json.put("code", value.toString());
}
return json;
}
}
public Semantics3Request add(String endpoint, Object... fields) {
JSONObject endpointQuery;
if ((endpointQuery = query.get(endpoint)) == null) {
endpointQuery = new JSONObject();
query.put(endpoint,endpointQuery);
}
JSONObject sq = endpointQuery;
for (int i=0;i<fields.length-2;i++) {
JSONObject tmp = sq;
if(sq.has((String)fields[i])){
try {
sq = sq.getJSONObject((String)fields[i]);
} catch(Exception e) {
throw new Semantics3Exception(
"Invalid constraint",
"Cannot add this constraint, '" + fields[i] +"' is already a value."
);
}
} else {
sq = new JSONObject();
tmp.put((String)fields[i], sq);
}
}
sq.put((String)fields[fields.length-2], fields[fields.length-1]);
return this;
}
public void remove(String endpoint, String... fields) {
_remove(this.query.get(endpoint),0,fields);
}
private void _remove(JSONObject subquery,int i, String[] fields) {
if (i == fields.length-1) {
subquery.remove(fields[i]);
} else {
JSONObject child = (JSONObject) subquery.get(fields[i]);
_remove(child,i+1,fields);
if (child.length() == 0) {
subquery.remove(fields[i]);
}
}
}
public Semantics3Request field(Object...fields) {
return add(this.endpoint,fields);
}
protected void runQuery() throws
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException, URISyntaxException {
runQuery(this.endpoint);
}
protected void runQuery(String endpoint) throws
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException, URISyntaxException {
JSONObject q = this.query.get(endpoint);
if (q==null) {
throw new Semantics3Exception(
"No query built",
"You need to first create a query using the add() method."
);
}
this.queryResult = fetch(endpoint,q.toString());
if (!this.queryResult.getString("code").equals("OK")) {
throw new Semantics3Exception(
this.queryResult.getString("code"),
String.format("Error Code: %s %s", this.queryResult.getString("code"),this.queryResult.getString("message"))
);
}
}
public JSONObject runQuery(String endpoint, String method, HashMap<String, Object> params) throws
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException, URISyntaxException {
if(method == "GET"){
JSONObject jsonObject = new JSONObject(params);
this.query.put(endpoint, jsonObject);
this.runQuery(endpoint);
}
else {
this.queryResult = fetch(endpoint, method, params);
}
if (!this.queryResult.getString("code").equals("OK")) {
throw new Semantics3Exception(
this.queryResult.getString("code"),
this.queryResult.getString("message")
);
}
return this.queryResult;
}
public JSONObject get() throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, URISyntaxException {
return get(this.endpoint);
}
public JSONObject get(String endpoint) throws
OAuthMessageSignerException,
OAuthExpectationFailedException,
OAuthCommunicationException,
IOException, URISyntaxException {
this.runQuery(endpoint);
return this.queryResult;
}
}