All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.genesys2.client.oauth.GenesysClient Maven / Gradle / Ivy

/**
 * Copyright 2014 Global Crop Diversity Trust
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with 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 org.genesys2.client.oauth;

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.genesys2.client.oauth.api.GenesysApi;
import org.genesys2.client.oauth.api.accession.AccessionJson;
import org.scribe.builder.ServiceBuilder;
import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.exceptions.OAuthException;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Genesys API client using Scribe.
 */
public class GenesysClient {

	/** The Constant _log. */
	private static final Logger _log = LogManager.getLogger(GenesysClient.class);

	/** The Constant EMPTY_TOKEN. */
	public static final Token EMPTY_TOKEN = null;

	/** The Constant SCOPE. */
	private static final String SCOPE = "read,write";

	/** The mapper. */
	private static ObjectMapper objectMapper = new ObjectMapper();

	/** The service. */
	private OAuthService service;

	/** The access token. */
	private Token accessToken;

	/** The refresh token. */
	private Token refreshToken;

	/** The genesys api. */
	private GenesysApi genesysApi;

	/** The api key. */
	private String apiKey;

	/** The api secret. */
	private String apiSecret;

	static {
		objectMapper = new ObjectMapper();
		objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
		objectMapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
		objectMapper.setSerializationInclusion(Include.NON_NULL);
	}

	/**
	 * Instantiates a new genesys client.
	 */
	public GenesysClient() {
	}

	/**
	 * Sets the base url.
	 *
	 * @param baseUrl
	 *            the base url
	 * @return the genesys client
	 */
	public GenesysClient setBaseUrl(String baseUrl) {
		genesysApi.setBaseUrl(baseUrl);
		return this;
	}

	/**
	 * Sets the genesys api.
	 *
	 * @param genesysApi
	 *            the new genesys api
	 */
	public void setGenesysApi(GenesysApi genesysApi) {
		this.genesysApi = genesysApi;
	}

	/**
	 * Gets the genesys api.
	 *
	 * @return the genesys api
	 */
	public GenesysApi getGenesysApi() {
		return genesysApi;
	}

	/**
	 * Load client configuration from {@link Properties}.
	 *
	 * @param properties
	 *            the properties
	 */
	public void loadProperties(Properties properties) {

		final String baseUrl = properties.getProperty("base.url");
		genesysApi.setBaseUrl(baseUrl);

		final String httpAuth = properties.getProperty("http.auth");

		if (StringUtils.isNotBlank(httpAuth) && httpAuth.contains(":")) {
			_log.warn("Using HTTP AUTH " + httpAuth);
			Authenticator.setDefault(new Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(httpAuth.split(":", 2)[0], httpAuth.split(":", 2)[1]
							.toCharArray());
				}
			});
		}

		setAccessToken(properties.getProperty("access.token"));
		setRefreshToken(properties.getProperty("refresh.token"));

		// CropHub auth service
		connect(properties.getProperty("client.key"), properties.getProperty("client.secret"),
				properties.getProperty("client.callback"));
	}

	/**
	 * Connect.
	 *
	 * @param clientId
	 *            the client id
	 * @param clientSecret
	 *            the client secret
	 * @param callback
	 *            the callback
	 */
	public void connect(String clientId, String clientSecret, String callback) {
		this.apiKey = clientId;
		this.apiSecret = clientSecret;
		this.service = new ServiceBuilder().provider(this.genesysApi).apiKey(clientId).apiSecret(clientSecret)
				.callback(callback).scope(SCOPE).build();
	}

	/**
	 * Sets the access token.
	 *
	 * @param tokenKey
	 *            the token key
	 * @return the genesys client
	 */
	public GenesysClient setAccessToken(String tokenKey) {
		accessToken = new Token(tokenKey, "");
		return this;
	}

	/**
	 * Sets the refresh token.
	 *
	 * @param tokenKey
	 *            the token key
	 * @return the genesys client
	 */
	public GenesysClient setRefreshToken(String tokenKey) {
		refreshToken = new Token(tokenKey, "");
		return this;
	}

	/**
	 * Query.
	 *
	 * @param url
	 *            the url
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String query(String url) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query(Verb.GET, url, null, null);
	}

	/**
	 * Query.
	 *
	 * @param method
	 *            the method
	 * @param url
	 *            the url
	 * @param queryString
	 *            the query string
	 * @param postBody
	 *            the post body
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String query(Verb method, String url, Map queryString, String postBody)
			throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {

		if (accessToken == null) {
			refreshAccessToken();
		}

		for (int i = 0; i < 2; i++) {
			OAuthRequest request = new OAuthRequest(method, getApiUrl(url));

			if (queryString != null && queryString.size() > 0) {
				for (String key : queryString.keySet()) {
					request.addQuerystringParameter(key, queryString.get(key));
				}
			}

			if (_log.isDebugEnabled()) {
				_log.debug(method + " " + request.getCompleteUrl());
			}

			if (postBody != null) {
				// System.err.println("Adding data: " + data);
				request.addPayload(postBody);
				request.addHeader("Content-Type", "application/json;charset=utf-8");
			}

			service.signRequest(accessToken, request);
			request.setConnectionKeepAlive(true);
			request.setConnectTimeout(10, TimeUnit.SECONDS);
			request.setReadTimeout(30, TimeUnit.SECONDS);
			request.setCharset("UTF-8");
			Response response = null;

			try {
				response = request.send();
			} catch (OAuthConnectionException e) {
				throw e;
			}

			String responseBody = response.getBody();
			if (response.isSuccessful()) {
				return responseBody + "\n";
			} else {
				if (response.getCode() == 401) {
					_log.warn("Response error: " + response.getCode());
					System.err.println(responseBody);
					if (i == 0) {
						refreshAccessToken();
					} else {
						throw new OAuthAuthenticationException("Unauthorized");
					}
				} else {
					_log.error(method + " " + request.getCompleteUrl());
					_log.error(postBody);
					_log.error("HTTP response code: " + response.getCode());
					_log.error("Response: " + responseBody);
					if (responseBody.contains("Deadlock found when trying to get lock; try restarting transaction")
							|| responseBody
									.contains("nested exception is org.hibernate.exception.LockAcquisitionException: could not execute statement")) {
						throw new PleaseRetryException(responseBody);
					} else
						throw new GenesysApiException("Unexpected error: " + responseBody);
				}
			}
		}
		return null;
	}

	/**
	 * Gets the api url.
	 *
	 * @param url
	 *            the url
	 * @return the api url
	 */
	private String getApiUrl(String url) {
		return genesysApi.getBaseUrl().concat("/api/v0").concat(url);
	}

	/**
	 * Refresh accessToken with refreshToken.
	 *
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 */
	public void refreshAccessToken() throws OAuthAuthenticationException {
		if (this.refreshToken != null) {
			_log.info("Using Refresh Token to get new access token");
			try {
				accessToken = genesysApi.getAccessToken(this.apiKey, this.apiSecret, this.refreshToken);
				_log.info("Got new Access Token!");
			} catch (OAuthException e) {
				_log.info("Refresh token didn't work: " + e.getMessage());
				throw new OAuthAuthenticationException("Refresh token not valid, please re-authenticate");
			}
		} else {
			throw new OAuthAuthenticationException("No refresh token, please re-authenticate");
		}
	}

	/**
	 * Accession exists.
	 *
	 * @param instCode
	 *            the inst code
	 * @param acceNumb
	 *            the acce numb
	 * @param genus
	 *            the genus
	 * @return the string
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String accessionExists(String instCode, String acceNumb, String genus) throws GenesysApiException {

		try {
			HashMap queryString = new HashMap();
			queryString.put("acceNumb", acceNumb);

			return query(Verb.GET, new URI(null, null, "/acn/exists/" + instCode + "/" + genus, null).toString(),
					queryString, null);
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * Make aid3.
	 *
	 * @param instCode
	 *            the inst code
	 * @param genus
	 *            the genus
	 * @param acceNumb
	 *            the acce numb
	 * @return the object node
	 */
	public static ObjectNode makeAid3(String instCode, String genus, String acceNumb) {
		ObjectNode json = objectMapper.createObjectNode();
		json.put("instCode", instCode);
		json.put("acceNumb", acceNumb);
		json.put("genus", genus);
		return json;
	}

	/**
	 * Update MLS status of accessions
	 *
	 * @param instCode
	 *            the inst code
	 * @param accns
	 *            the accns
	 * @return the string
	 * @throws GenesysApiException
	 *             the genesys api exception
	 * @throws JsonProcessingException
	 * @throws PleaseRetryException
	 * 
	 * @deprecated Please use {@link #updateAccessions(String, Collection)} with
	 *             only the instCode, acceNumb, (genus, ) and mlsStat provided.
	 */
	@Deprecated
	public String updateMLS(String instCode, Collection accns) throws GenesysApiException,
			PleaseRetryException, JsonProcessingException {

		if (accns == null || accns.size() == 0) {
			return null;
		}

		_log.debug("Sending: " + accns);
		return query(Verb.PUT, "/acn/" + instCode + "/update", null, objectMapper.writeValueAsString(accns));
	}

	/**
	 * Update accession information with new values provided in the JSON string.
	 * In case of {@link PleaseRetryException}, this method will attempt to
	 * re-send the data 5 times before giving up.
	 * 
	 * @param instCode
	 *            the WIEWS institute code
	 * @param jsonAccessionList
	 *            the JSON array of accessions
	 * @return "OK"
	 * @throws GenesysApiException
	 *             when data is not valid
	 * @throws InterruptedException
	 *             when thread was interrupted during sleep between retries
	 * 
	 */
	public String updateAccessions(String instCode, String jsonAccessionList) throws GenesysApiException,
			InterruptedException {
		for (int retry = 0; retry < 5; retry++) {
			try {
				return query(Verb.PUT, "/acn/" + instCode + "/upsert", null, jsonAccessionList);
			} catch (PleaseRetryException e) {
				long sleepTime = (long) (Math.pow(2, retry) * 100 + Math.pow(2, retry) * 2500 * Math.random());
				_log.warn("Retrying PUT after " + sleepTime + " ms.");
				Thread.sleep(sleepTime);
			}
		}
		throw new RuntimeException("All retries failed");
	}

	public String updateAccessions(String instCode, Collection accns) throws GenesysApiException,
			InterruptedException, JsonProcessingException {

		if (accns == null || accns.size() == 0) {
			return null;
		}

		return updateAccessions(instCode, objectMapper.writeValueAsString(accns));
	}

	/**
	 * Update organization members.
	 *
	 * @param organizationSlug
	 *            the organization slug
	 * @param institutes
	 *            the institutes
	 * @return the string
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String updateOrganizationMembers(String organizationSlug, ArrayNode institutes) throws GenesysApiException {
		_log.debug("Sending: " + institutes);
		try {
			return query(Verb.PUT, "/org/" + organizationSlug + "/set-institutes", null, institutes.toString());
		} catch (PleaseRetryException e) {
			_log.warn("Retrying PUT after some time...");
			try {
				Thread.sleep((long) (1000 * Math.random()));
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			return query(Verb.PUT, "/org/" + organizationSlug + "/set-institutes", null, institutes.toString());
		}
	}

	/**
	 * Update accession names.
	 *
	 * @param instCode
	 *            the inst code
	 * @param batch
	 *            the batch
	 * @return the string
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String updateAccessionNames(String instCode, Collection batch) throws GenesysApiException {
		_log.debug("Sending: " + batch);
		try {
			return query(Verb.PUT, "/acn/" + instCode + "/names", null, batch.toString());
		} catch (PleaseRetryException e) {
			_log.warn("Retrying PUT after some time...");
			try {
				Thread.sleep((long) (1000 * Math.random()));
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			_log.warn("Retrying PUT");
			return query(Verb.PUT, "/acn/" + instCode + "/names", null, batch.toString());
		}
	}

	/**
	 * Delete accessions.
	 *
	 * @param instCode
	 *            the inst code
	 * @param array
	 *            the array
	 * @return the string
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteAccessions(String instCode, ArrayNode array) throws GenesysApiException {
		return query(Verb.POST, "/acn/" + instCode + "/delete-named", null, array.toString());
	}

	/**
	 * Delete accession.
	 *
	 * @param instCode
	 *            the inst code
	 * @param ids
	 *            the ids
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteAccession(String instCode, ArrayNode ids) throws OAuthAuthenticationException,
			PleaseRetryException, GenesysApiException {
		return query(Verb.POST, "/acn/" + instCode + "/delete", null, ids.toString());
	}

	/**
	 * Gets the authorization url.
	 *
	 * @param accessToken
	 *            the access token
	 * @return the authorization url
	 */
	public String getAuthorizationUrl(Token accessToken) {
		return this.service.getAuthorizationUrl(accessToken);
	}

	/**
	 * Obtain access and refresh tokens with verifier code.
	 *
	 * @param verifierCode
	 *            the verifier code
	 */
	public void authenticate(String verifierCode) {
		Verifier verifier = new Verifier(verifierCode);
		accessToken = service.getAccessToken(GenesysClient.EMPTY_TOKEN, verifier);

		_log.info("ACCESS TOKEN: " + accessToken.getToken() + " sec=" + accessToken.getSecret() + " raw="
				+ accessToken.getRawResponse());

		refreshToken = genesysApi.getRefreshToken(accessToken);
		_log.info("REFRESH TOKEN: " + refreshToken.getToken() + " sec=" + refreshToken.getSecret() + " raw="
				+ refreshToken.getRawResponse());
	}

	/**
	 * Gets the access token.
	 *
	 * @return the access token
	 */
	public Token getAccessToken() {
		return accessToken;
	}

	/**
	 * Gets the refresh token.
	 *
	 * @return the refresh token
	 */
	public Token getRefreshToken() {
		return refreshToken;
	}

	/**
	 * Me.
	 *
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String me() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query("/me");
	}

	/**
	 * Gets the crop.
	 *
	 * @param shortName
	 *            the short name
	 * @return the crop
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getCrop(String shortName) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		if (!shortName.matches("^\\w+$")) {
			throw new GenesysApiException("Crop shortname can only contain characters");
		}
		return query("/crops/" + shortName);
	}

	/**
	 * List parameters.
	 *
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listParameters() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query("/kpi/parameter/list");
	}

	/**
	 * Put parameter.
	 *
	 * @param node
	 *            the node
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String putParameter(ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/kpi/parameter", null, node.toString());
	}

	/**
	 * Gets the parameter.
	 *
	 * @param name
	 *            the name
	 * @return the parameter
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getParameter(String name) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query("/kpi/parameter/" + name);
	}

	/**
	 * List dimensions.
	 *
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listDimensions() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query("/kpi/dimension/list");
	}

	/**
	 * Gets the dimension.
	 *
	 * @param id
	 *            the id
	 * @return the dimension
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getDimension(long id) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query("/kpi/dimension/" + id);
	}

	/**
	 * Put dimension.
	 *
	 * @param node
	 *            the node
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String putDimension(ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/kpi/dimension", null, node.toString());
	}

	/**
	 * List executions.
	 *
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listExecutions() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query("/kpi/execution/list");
	}

	/**
	 * Gets the execution.
	 *
	 * @param name
	 *            the name
	 * @return the execution
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getExecution(String name) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query("/kpi/execution/" + name);
	}

	/**
	 * Put execution.
	 *
	 * @param node
	 *            the node
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String putExecution(ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/kpi/execution", null, node.toString());
	}

	/**
	 * Kpi execute.
	 *
	 * @param name
	 *            the name
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String kpiExecute(String name) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/kpi/execution/" + name + "/execute", null, null);
	}

	/**
	 * Delete dimension.
	 *
	 * @param id
	 *            the id
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteDimension(long id) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.DELETE, "/kpi/dimension/" + id, null, null);
	}

	/**
	 * Delete execution.
	 *
	 * @param name
	 *            the name
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteExecution(String name) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.DELETE, "/kpi/execution/" + name, null, null);
	}

	/**
	 * Delete parameter.
	 *
	 * @param name
	 *            the name
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteParameter(String name) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.DELETE, "/kpi/parameter/" + name, null, null);
	}

	/**
	 * List crops.
	 *
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listCrops() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query("/crops");
	}

	/**
	 * Put crop.
	 *
	 * @param node
	 *            the node
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String putCrop(ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/crops", null, node.toString());
	}

	/**
	 * Delete crop.
	 *
	 * @param shortName
	 *            the short name
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteCrop(String shortName) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.DELETE, "/crops/" + shortName, null, null);
	}

	/**
	 * Gets the crop rules.
	 *
	 * @param shortName
	 *            the short name
	 * @return the crop rules
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getCropRules(String shortName) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query("/crops/" + shortName + "/rules");
	}

	/**
	 * Put crop rules.
	 *
	 * @param shortName
	 *            the short name
	 * @param currentCropRules
	 *            the current crop rules
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String putCropRules(String shortName, ArrayNode currentCropRules) throws OAuthAuthenticationException,
			PleaseRetryException, GenesysApiException {
		return query(Verb.PUT, "/crops/" + shortName + "/rules", null, currentCropRules.toString());
	}

	/**
	 * Rebuild crop taxa.
	 *
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String rebuildCropTaxa() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		return query(Verb.POST, "/crops/rebuild", null, null);
	}

	/**
	 * Rebuild crop taxa.
	 *
	 * @param shortName
	 *            the short name
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String rebuildCropTaxa(String shortName) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/crops/" + shortName + "/rebuild", null, null);
	}

	/**
	 * List organizations.
	 *
	 * @param page
	 *            the page
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listOrganizations(int page) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		Map qs = new HashMap();
		qs.put("page", String.valueOf(page));
		return query(Verb.GET, "/org", qs, null);
	}

	/**
	 * Gets the organization.
	 *
	 * @param slug
	 *            the slug
	 * @return the organization
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getOrganization(String slug) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query("/org/" + slug);
	}

	/**
	 * Update organization.
	 *
	 * @param org
	 *            the org
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String updateOrganization(ObjectNode org) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.POST, "/org", null, org.toString());
	}

	/**
	 * Delete organization.
	 *
	 * @param slug
	 *            the slug
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String deleteOrganization(String slug) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query(Verb.DELETE, "/org/" + slug, null, null);
	}

	/**
	 * Gets the organization members.
	 *
	 * @param slug
	 *            the slug
	 * @return the organization members
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getOrganizationMembers(String slug) throws OAuthAuthenticationException, PleaseRetryException,
			GenesysApiException {
		return query("/org/" + slug + "/institutes");
	}

	/**
	 * Put organization members.
	 *
	 * @param slug
	 *            the slug
	 * @param currentMembers
	 *            the current members
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String putOrganizationMembers(String slug, ArrayNode currentMembers) throws OAuthAuthenticationException,
			PleaseRetryException, GenesysApiException {
		return query(Verb.PUT, "/org/" + slug + "/set-institutes", null, currentMembers.toString());
	}

	/**
	 * Gets the organization blurp.
	 *
	 * @param slug
	 *            the slug
	 * @param language
	 *            the language
	 * @return the organization blurp
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String getOrganizationBlurp(String slug, String language) throws OAuthAuthenticationException,
			PleaseRetryException, GenesysApiException {
		return query("/org/" + slug + "/blurp/" + language);
	}

	/**
	 * Update organization blurp.
	 *
	 * @param slug
	 *            the slug
	 * @param blurp
	 *            the blurp
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String updateOrganizationBlurp(String slug, ObjectNode blurp) throws OAuthAuthenticationException,
			PleaseRetryException, GenesysApiException {
		return query(Verb.PUT, "/org/" + slug + "/blurp", null, blurp.toString());
	}

	/**
	 * List observations.
	 *
	 * @param executionName
	 *            the execution name
	 * @param dimensionFilter
	 *            the dimension filter
	 * @param page
	 *            the page
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listObservations(String executionName, String dimensionFilter, int page)
			throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException {
		Map qs = new HashMap();
		qs.put("page", String.valueOf(page));
		return query(Verb.POST, "/kpi/observation/" + executionName + "/", qs,
				StringUtils.defaultIfBlank(dimensionFilter, ""));
	}

	/**
	 * List accessions.
	 *
	 * @param instCode
	 *            the inst code
	 * @param page
	 *            the page
	 * @param query
	 *            the query
	 * @return the string
	 * @throws OAuthAuthenticationException
	 *             the o auth authentication exception
	 * @throws PleaseRetryException
	 *             the please retry exception
	 * @throws GenesysApiException
	 *             the genesys api exception
	 */
	public String listAccessions(String instCode, int page, String query) throws OAuthAuthenticationException,
			PleaseRetryException, GenesysApiException {
		Map params = new HashMap();
		params.put("page", String.valueOf(page));
		params.put("query", query);
		return query(Verb.GET, "/acn/" + instCode + "/list", params, null);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy