1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 package org.arvados.sdk;
7 import com.google.api.client.http.javanet.*;
8 import com.google.api.client.http.ByteArrayContent;
9 import com.google.api.client.http.GenericUrl;
10 import com.google.api.client.http.HttpBackOffIOExceptionHandler;
11 import com.google.api.client.http.HttpContent;
12 import com.google.api.client.http.HttpRequest;
13 import com.google.api.client.http.HttpRequestFactory;
14 import com.google.api.client.http.HttpTransport;
15 import com.google.api.client.http.UriTemplate;
16 import com.google.api.client.json.JsonFactory;
17 import com.google.api.client.json.jackson2.JacksonFactory;
18 import com.google.api.client.util.ExponentialBackOff;
19 import com.google.api.client.util.Maps;
20 import com.google.api.services.discovery.Discovery;
21 import com.google.api.services.discovery.model.JsonSchema;
22 import com.google.api.services.discovery.model.RestDescription;
23 import com.google.api.services.discovery.model.RestMethod;
24 import com.google.api.services.discovery.model.RestMethod.Request;
25 import com.google.api.services.discovery.model.RestResource;
27 import java.math.BigDecimal;
28 import java.math.BigInteger;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.List;
36 import org.apache.log4j.Logger;
37 import org.json.simple.JSONArray;
38 import org.json.simple.JSONObject;
41 * This class provides a java SDK interface to Arvados API server.
43 * Please refer to http://doc.arvados.org/api/ to learn about the
44 * various resources and methods exposed by the API server.
48 public class Arvados {
49 // HttpTransport and JsonFactory are thread-safe. So, use global instances.
50 private HttpTransport httpTransport;
51 private final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
53 private String arvadosApiToken;
54 private String arvadosApiHost;
55 private boolean arvadosApiHostInsecure;
57 private String arvadosRootUrl;
59 private static final Logger logger = Logger.getLogger(Arvados.class);
61 // Get it once and reuse on the call requests
62 RestDescription restDescription = null;
63 String apiName = null;
64 String apiVersion = null;
66 public Arvados (String apiName, String apiVersion) throws Exception {
67 this (apiName, apiVersion, null, null, null);
70 public Arvados (String apiName, String apiVersion, String token,
71 String host, String hostInsecure) throws Exception {
72 this.apiName = apiName;
73 this.apiVersion = apiVersion;
75 // Read needed environmental variables if they are not passed
77 arvadosApiToken = token;
79 arvadosApiToken = System.getenv().get("ARVADOS_API_TOKEN");
80 if (arvadosApiToken == null) {
81 throw new Exception("Missing environment variable: ARVADOS_API_TOKEN");
86 arvadosApiHost = host;
88 arvadosApiHost = System.getenv().get("ARVADOS_API_HOST");
89 if (arvadosApiHost == null) {
90 throw new Exception("Missing environment variable: ARVADOS_API_HOST");
93 arvadosRootUrl = "https://" + arvadosApiHost;
94 arvadosRootUrl += (arvadosApiHost.endsWith("/")) ? "" : "/";
96 if (hostInsecure != null) {
97 arvadosApiHostInsecure = Boolean.valueOf(hostInsecure);
99 arvadosApiHostInsecure =
100 "true".equals(System.getenv().get("ARVADOS_API_HOST_INSECURE")) ? true : false;
103 // Create HTTP_TRANSPORT object
104 NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
105 if (arvadosApiHostInsecure) {
106 builder.doNotValidateCertificate();
108 httpTransport = builder.build();
110 // initialize rest description
111 restDescription = loadArvadosApi();
115 * Make a call to API server with the provide call information.
116 * @param resourceName
122 public Map call(String resourceName, String methodName,
123 Map<String, Object> paramsMap) throws Exception {
124 RestMethod method = getMatchingMethod(resourceName, methodName);
126 HashMap<String, Object> parameters = loadParameters(paramsMap, method);
128 GenericUrl url = new GenericUrl(UriTemplate.expand(
129 arvadosRootUrl + restDescription.getBasePath() + method.getPath(),
133 // construct the request
134 HttpRequestFactory requestFactory;
135 requestFactory = httpTransport.createRequestFactory();
137 // possibly required content
138 HttpContent content = null;
140 if (!method.getHttpMethod().equals("GET") &&
141 !method.getHttpMethod().equals("DELETE")) {
142 String objectName = resourceName.substring(0, resourceName.length()-1);
143 Object requestBody = paramsMap.get(objectName);
144 if (requestBody == null) {
145 error("POST method requires content object " + objectName);
148 content = new ByteArrayContent("application/json",((String)requestBody).getBytes());
151 HttpRequest request =
152 requestFactory.buildRequest(method.getHttpMethod(), url, content);
154 // Set read timeout to 120 seconds (up from default of 20 seconds)
155 request.setReadTimeout(120 * 1000);
157 // Add retry behavior
158 request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff()));
161 List<String> authHeader = new ArrayList<String>();
162 authHeader.add("OAuth2 " + arvadosApiToken);
163 request.getHeaders().put("Authorization", authHeader);
164 String response = request.execute().parseAsString();
166 Map responseMap = jsonFactory.createJsonParser(response).parse(HashMap.class);
168 logger.debug(responseMap);
171 } catch (Exception e) {
178 * Get all supported resources by the API
181 public Set<String> getAvailableResourses() {
182 return (restDescription.getResources().keySet());
186 * Get all supported method names for the given resource
187 * @param resourceName
191 public Set<String> getAvailableMethodsForResourse(String resourceName)
193 Map<String, RestMethod> methodMap = getMatchingMethodMap (resourceName);
194 return (methodMap.keySet());
198 * Get the parameters for the method in the resource sought.
199 * @param resourceName
204 public Map<String,List<String>> getAvailableParametersForMethod(String resourceName, String methodName)
206 RestMethod method = getMatchingMethod(resourceName, methodName);
207 Map<String, List<String>> parameters = new HashMap<String, List<String>>();
208 List<String> requiredParameters = new ArrayList<String>();
209 List<String> optionalParameters = new ArrayList<String>();
210 parameters.put ("required", requiredParameters);
211 parameters.put("optional", optionalParameters);
214 // get any request parameters
215 Request request = method.getRequest();
216 if (request != null) {
217 Object required = request.get("required");
218 Object requestProperties = request.get("properties");
219 if (requestProperties != null) {
220 if (requestProperties instanceof Map) {
221 Map properties = (Map)requestProperties;
222 Set<String> propertyKeys = properties.keySet();
223 for (String property : propertyKeys) {
224 if (Boolean.TRUE.equals(required)) {
225 requiredParameters.add(property);
227 optionalParameters.add(property);
234 // get other listed parameters
235 Map<String,JsonSchema> methodParameters = method.getParameters();
236 for (Map.Entry<String, JsonSchema> entry : methodParameters.entrySet()) {
237 if (Boolean.TRUE.equals(entry.getValue().getRequired())) {
238 requiredParameters.add(entry.getKey());
240 optionalParameters.add(entry.getKey());
243 } catch (Exception e){
250 private HashMap<String, Object> loadParameters(Map<String, Object> paramsMap,
251 RestMethod method) throws Exception {
252 HashMap<String, Object> parameters = Maps.newHashMap();
254 // required parameters
255 if (method.getParameterOrder() != null) {
256 for (String parameterName : method.getParameterOrder()) {
257 JsonSchema parameter = method.getParameters().get(parameterName);
258 if (Boolean.TRUE.equals(parameter.getRequired())) {
259 Object parameterValue = paramsMap.get(parameterName);
260 if (parameterValue == null) {
261 error("missing required parameter: " + parameter);
263 putParameter(null, parameters, parameterName, parameter, parameterValue);
269 for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
270 String parameterName = entry.getKey();
271 Object parameterValue = entry.getValue();
273 if (parameterName.equals("contentType")) {
274 if (method.getHttpMethod().equals("GET") || method.getHttpMethod().equals("DELETE")) {
275 error("HTTP content type cannot be specified for this method: " + parameterName);
278 JsonSchema parameter = null;
279 if (restDescription.getParameters() != null) {
280 parameter = restDescription.getParameters().get(parameterName);
282 if (parameter == null && method.getParameters() != null) {
283 parameter = method.getParameters().get(parameterName);
285 putParameter(parameterName, parameters, parameterName, parameter, parameterValue);
292 private RestMethod getMatchingMethod(String resourceName, String methodName)
294 Map<String, RestMethod> methodMap = getMatchingMethodMap(resourceName);
296 if (methodName == null) {
297 error("missing method name");
301 methodMap == null ? null : methodMap.get(methodName);
302 if (method == null) {
303 error("method not found: ");
309 private Map<String, RestMethod> getMatchingMethodMap(String resourceName)
311 if (resourceName == null) {
312 error("missing resource name");
315 Map<String, RestMethod> methodMap = null;
316 Map<String, RestResource> resources = restDescription.getResources();
317 RestResource resource = resources.get(resourceName);
318 if (resource == null) {
319 error("resource not found");
321 methodMap = resource.getMethods();
326 * Not thread-safe. So, create for each request.
332 private RestDescription loadArvadosApi()
337 Discovery.Builder discoveryBuilder =
338 new Discovery.Builder(httpTransport, jsonFactory, null);
340 discoveryBuilder.setRootUrl(arvadosRootUrl);
341 discoveryBuilder.setApplicationName(apiName);
343 discovery = discoveryBuilder.build();
345 return discovery.apis().getRest(apiName, apiVersion).execute();
346 } catch (Exception e) {
353 * Convert the input parameter into its equivalent json string.
354 * Add this json string value to the parameters map to be sent to server.
357 * @param parameterName
359 * @param parameterValue
362 private void putParameter(String argName, Map<String, Object> parameters,
363 String parameterName, JsonSchema parameter, Object parameterValue)
365 Object value = parameterValue;
366 if (parameter != null) {
367 if ("boolean".equals(parameter.getType())) {
368 value = Boolean.valueOf(parameterValue.toString());
369 } else if ("number".equals(parameter.getType())) {
370 value = new BigDecimal(parameterValue.toString());
371 } else if ("integer".equals(parameter.getType())) {
372 value = new BigInteger(parameterValue.toString());
373 } else if ("float".equals(parameter.getType())) {
374 value = new BigDecimal(parameterValue.toString());
375 } else if ("Java.util.Calendar".equals(parameter.getType())) {
376 value = new BigDecimal(parameterValue.toString());
377 } else if (("array".equals(parameter.getType())) ||
378 ("Array".equals(parameter.getType()))) {
379 if (parameterValue.getClass().isArray()){
380 value = getJsonValueFromArrayType(parameterValue);
381 } else if (List.class.isAssignableFrom(parameterValue.getClass())) {
382 value = getJsonValueFromListType(parameterValue);
384 } else if (("Hash".equals(parameter.getType())) ||
385 ("hash".equals(parameter.getType()))) {
386 value = getJsonValueFromMapType(parameterValue);
388 if (parameterValue.getClass().isArray()){
389 value = getJsonValueFromArrayType(parameterValue);
390 } else if (List.class.isAssignableFrom(parameterValue.getClass())) {
391 value = getJsonValueFromListType(parameterValue);
392 } else if (Map.class.isAssignableFrom(parameterValue.getClass())) {
393 value = getJsonValueFromMapType(parameterValue);
398 parameters.put(parameterName, value);
402 * Convert the given input array into json string before sending to server.
403 * @param parameterValue
406 private String getJsonValueFromArrayType (Object parameterValue) {
407 String arrayStr = Arrays.deepToString((Object[])parameterValue);
409 // we can expect either an array of array objects or an array of objects
410 if (arrayStr.startsWith("[[") && arrayStr.endsWith("]]")) {
411 Object[][] array = new Object[1][];
412 arrayStr = arrayStr.substring(2, arrayStr.length()-2);
413 String jsonStr = getJsonStringForArrayStr(arrayStr);
414 String value = "[" + jsonStr + "]";
417 arrayStr = arrayStr.substring(1, arrayStr.length()-1);
418 return (getJsonStringForArrayStr(arrayStr));
422 private String getJsonStringForArrayStr(String arrayStr) {
423 Object[] array = arrayStr.split(",");
424 Object[] trimmedArray = new Object[array.length];
425 for (int i=0; i<array.length; i++){
426 trimmedArray[i] = array[i].toString().trim();
428 String value = JSONArray.toJSONString(Arrays.asList(trimmedArray));
433 * Convert the given input List into json string before sending to server.
434 * @param parameterValue
437 private String getJsonValueFromListType (Object parameterValue) {
438 List paramList = (List)parameterValue;
439 Object[] array = new Object[paramList.size()];
440 Arrays.deepToString(paramList.toArray(array));
441 return (getJsonValueFromArrayType(array));
445 * Convert the given input map into json string before sending to server.
446 * @param parameterValue
449 private String getJsonValueFromMapType (Object parameterValue) {
450 JSONObject json = new JSONObject((Map)parameterValue);
451 return json.toString();
454 private static void error(String detail) throws Exception {
455 String errorDetail = "ERROR: " + detail;
457 logger.debug(errorDetail);
458 throw new Exception(errorDetail);
461 public static void main(String[] args){
462 System.out.println("Welcome to Arvados Java SDK.");
463 System.out.println("Please refer to http://doc.arvados.org/sdk/java/index.html to get started with the the SDK.");