Commit b6ef8c98 authored by Matija Obreza's avatar Matija Obreza

Extracted CLI from GenesysClient

parent 1e19babb
#OAuth client properties
#Mon Jul 14 14:57:45 CEST 2014
client.callback=oob
base.url=http\://localhost\:8080
access.token=4690da94-d387-4b93-8377-699ac0ca8639
client.key=CropHub
client.secret=0xcafebabe
refresh.token=d5294375-3ac7-4134-9f28-98068f02d926
api.url=/api/v0
package org.genesys2.client.oauth;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Properties;
import java.util.Scanner;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.scribe.exceptions.OAuthConnectionException;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* Command line interface to Genesys
*
* @author matijaobreza
*
*/
public class CLI {
private static final Logger _log = LogManager.getLogger(CLI.class);
private File propertiesFile;
private Properties properties;
private Scanner in = new Scanner(System.in);
private static ObjectMapper mapper = new ObjectMapper();
private GenesysClient genesysClient = new GenesysClient();
public static void main(String[] args) {
_log.info("Hello World!");
CLI cli = new CLI();
cli.loadProperties("client.properties");
cli.run();
}
private void run() {
checkPreconditions();
try {
System.out.println("/me: " + genesysClient.query("/me"));
} catch (OAuthAuthenticationException e) {
_log.error("Failed to fetch /me", e);
authenticate();
} catch (OAuthConnectionException e) {
if (e.getCause() != null && e.getCause() instanceof SocketException) {
_log.error("Could not connect to host");
return;
} else {
_log.error(e.getMessage(), e);
}
} catch (Throwable e) {
_log.error(e.getMessage(), e);
return;
}
try {
doWork();
} catch (Throwable e) {
_log.error(e.getMessage(), e);
}
}
private void doWork() throws GenesysApiException {
String line = null;
do {
System.out.println("1 Datasets");
System.out.println("2 Traits");
System.out.println("0 Custom");
System.out.println("Q QUIT");
line = in.nextLine();
if ("1".equals(line))
doDatasets();
else if ("2".equals(line))
doTraits();
else if ("0".equals(line))
doCustom();
} while (!"Q".equalsIgnoreCase(line));
}
private void doCustom() throws GenesysApiException {
System.out.print("URL: ");
String url = in.nextLine();
System.out.print("Method [GET]: ");
String method = StringUtils.defaultIfBlank(in.nextLine(), "GET");
System.out.println("JSON: ");
String data = StringUtils.defaultIfBlank(in.nextLine(), null);
// Exec
System.out.println(genesysClient.query(Verb.valueOf(method), url, null, data));
}
private void doTraits() throws GenesysApiException {
String line = null;
do {
System.out.println("1 List parameters");
System.out.println("2 List my methods");
System.out.println("9 List all methods");
System.out.println("3 Add method");
System.out.println("0 Back");
line = in.nextLine();
if ("1".equals(line))
System.out.println("/parameters: " + genesysClient.query("/descriptors"));
else if ("2".equals(line))
System.out.println("/mymethods: " + genesysClient.query("/mymethods"));
else if ("3".equals(line))
addMethod();
else if ("9".equals(line))
System.out.println("/methods: " + genesysClient.query("/methods"));
else if ("0".equalsIgnoreCase(line))
return;
} while (!("0".equalsIgnoreCase(line)));
}
private void doDatasets() throws GenesysApiException {
String line = null;
do {
System.out.println("1 List");
System.out.println("2 Add");
System.out.println("3 Add data");
System.out.println("4 Add RAW");
System.out.println("0 Back");
line = in.nextLine();
if ("1".equals(line))
System.out.println("/datasets: " + genesysClient.query("/datasets"));
else if ("2".equals(line))
addDataset();
else if ("3".equals(line))
addDatasetData();
else if ("4".equals(line))
addDatasetRaw();
else if ("0".equalsIgnoreCase(line))
return;
} while (!("0".equalsIgnoreCase(line)));
}
private void addMethod() throws GenesysApiException {
ObjectNode datasetJson = mapper.createObjectNode();
System.out.println("Method description: ");
datasetJson.put("description", in.nextLine());
System.out.println("UOM: ");
datasetJson.put("unit", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Field name: ");
datasetJson.put("fieldName", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Field type: (0=String, 1=Double, 2=Long)");
int fieldType = Integer.parseInt(in.nextLine());
datasetJson.put("fieldType", fieldType);
if (fieldType == 0) {
System.out.println("Field size: ");
datasetJson.put("fieldSize", Integer.parseInt(in.nextLine()));
}
System.out.println("Options: ");
datasetJson.put("options", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Range: ");
datasetJson.put("range", StringUtils.defaultIfBlank(in.nextLine(), null));
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put method: " + genesysClient.query(Verb.PUT, "/methods", null, datasetJson.toString()));
}
private void addDataset() throws GenesysApiException {
ObjectNode datasetJson = mapper.createObjectNode();
System.out.println("WIEWS Code: ");
datasetJson.put("institute", in.nextLine());
System.out.println("Dataset title: ");
datasetJson.put("title", in.nextLine());
System.out.println("Dataset description: ");
datasetJson.put("description", in.nextLine());
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put dataset: " + genesysClient.query(Verb.PUT, "/datasets", null, datasetJson.toString()));
}
private void addDatasetData() throws GenesysApiException {
ObjectNode datasetJson = mapper.createObjectNode();
System.out.println("Dataset ID: ");
long datasetId = Long.parseLong(in.nextLine());
System.out.println("WIEWS Code: ");
datasetJson.put("instCode", in.nextLine());
System.out.println("Data data: ");
datasetJson.put("data", in.nextLine());
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put dataset: " + genesysClient.query(Verb.PUT, "/datasets/" + datasetId + "/data", null, datasetJson.toString()));
}
private void addDatasetRaw() throws GenesysApiException {
System.out.println("Dataset ID: ");
long datasetId = Long.parseLong(in.nextLine());
System.out.println("JSON: ");
String json = in.nextLine();
System.err.println(json);
// make a dataset
System.out.println("Put dataset: " + genesysClient.query(Verb.PUT, "/datasets/" + datasetId + "/data", null, json));
}
private void checkPreconditions() {
boolean restart = false;
if (StringUtils.isBlank(properties.getProperty("client.key"))) {
System.out.print("Provide client key: ");
properties.put("client.key", in.nextLine());
restart = true;
}
if (StringUtils.isBlank(properties.getProperty("client.secret"))) {
System.out.print("Provide client secret: ");
properties.put("client.secret", in.nextLine());
restart = true;
}
if (StringUtils.isBlank(properties.getProperty("api.url"))) {
System.out.print("Provide API url: ");
properties.put("api.url", in.nextLine());
restart = true;
}
if (restart) {
saveProperties();
_log.warn("Properties udpated, please restart CLI application");
System.exit(-1);
}
}
private void authenticate() {
String authorizationUrl = genesysClient.getAuthorizationUrl(GenesysClient.EMPTY_TOKEN);
System.out.println("Authorization URL: \n" + authorizationUrl);
System.out.print("\nVerifier: ");
String verifierCode = in.nextLine();
System.out.println();
// Trade the Request Token and Verifier for the Access Token
genesysClient.authenticate(verifierCode);
Token accessToken = genesysClient.getAccessToken();
this.properties.put("access.token", accessToken.getToken());
// Get refresh token ()
Token refreshToken = genesysClient.getRefreshToken();
if (refreshToken != null) {
this.properties.put("refresh.token", refreshToken.getToken());
} else {
this.properties.remove("refresh.token");
}
saveProperties();
}
private void saveProperties() {
FileOutputStream fis = null;
try {
fis = new FileOutputStream(propertiesFile);
this.properties.store(fis, "OAuth client properties");
} catch (IOException e) {
_log.error(e);
} finally {
IOUtils.closeQuietly(fis);
}
}
private void loadProperties(String propertiesFileName) {
// .properties file location
propertiesFile = new File(propertiesFileName);
Properties properties = new Properties();
FileInputStream fis = null;
try {
_log.info("Loading " + propertiesFile.getAbsolutePath());
fis = new FileInputStream(propertiesFile);
properties.load(fis);
// Keep properties
this.properties = properties;
} catch (FileNotFoundException e) {
_log.warn(e, e);
} catch (IOException e) {
_log.error(e, e);
} finally {
IOUtils.closeQuietly(fis);
}
genesysClient.loadProperties(properties);
}
}
/**
* Copyright 2013 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;
public class GenesysApiException extends Exception {
private static final long serialVersionUID = -6008425446284829953L;
public GenesysApiException() {
}
public GenesysApiException(String string) {
super(string);
}
}
......@@ -16,25 +16,16 @@
package org.genesys2.client.oauth;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.ConnectException;
import java.net.PasswordAuthentication;
import java.net.SocketTimeoutException;
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.Scanner;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
......@@ -55,61 +46,34 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
public class GenesysClient {
private static final Logger _log = LogManager.getLogger(GenesysClient.class);
private static final Token EMPTY_TOKEN = null;
public static final Token EMPTY_TOKEN = null;
private static final String SCOPE = "read,write";
private static final String OOB_CALLBACK = "oob";
private File propertiesFile;
private static ObjectMapper mapper = new ObjectMapper();
private OAuthService service;
private Token accessToken;
private Token refreshToken;
private Properties properties;
private Scanner in = new Scanner(System.in);
private String apiUrl;
private GenesysApi genesysApi;
public GenesysClient() {
}
public static void main(String[] args) {
_log.info("Hello World!");
GenesysClient genesysClient = new GenesysClient();
genesysClient.loadProperties("client.properties");
genesysClient.run();
}
public void loadProperties(String propertiesFileName) {
// .properties file location
propertiesFile = new File(propertiesFileName);
Properties properties = new Properties();
FileInputStream fis = null;
try {
_log.info("Loading " + propertiesFile.getAbsolutePath());
fis = new FileInputStream(propertiesFile);
properties.load(fis);
// Keep properties
this.properties = properties;
} catch (FileNotFoundException e) {
_log.warn(e, e);
} catch (IOException e) {
_log.error(e, e);
} finally {
IOUtils.closeQuietly(fis);
}
/**
* Load client configuration from {@link Properties}
*
* @param properties
*/
public void loadProperties(Properties properties) {
final String baseUrl = this.properties.getProperty("base.url");
final String baseUrl = properties.getProperty("base.url");
this.genesysApi = new GenesysApi(baseUrl, properties.getProperty("client.key"), properties.getProperty("client.secret"));
this.apiUrl = baseUrl + this.properties.getProperty("api.url");
this.apiUrl = baseUrl + properties.getProperty("api.url");
final String httpAuth = this.properties.getProperty("http.auth");
final String httpAuth = properties.getProperty("http.auth");
if (StringUtils.isNotBlank(httpAuth) && httpAuth.contains(":")) {
_log.warn("Using HTTP AUTH " + httpAuth);
......@@ -121,262 +85,32 @@ public class GenesysClient {
});
}
// CropHub auth service
this.service = new ServiceBuilder().provider(this.genesysApi).apiKey(properties.getProperty("client.key")).apiSecret(properties.getProperty("client.secret")).callback(OOB_CALLBACK)
.scope(SCOPE).build();
this.accessToken = makeToken(this.properties.getProperty("access.token"));
this.refreshToken = makeToken(this.properties.getProperty("refresh.token"));
}
private Token makeToken(String tokenKey) {
if (StringUtils.isBlank(tokenKey))
return null;
return new Token(tokenKey, "");
}
private void run() {
checkPreconditions();
try {
System.out.println("/me: " + query("/me"));
doWork();
} catch (OAuthAuthenticationException e) {
e.printStackTrace();
System.err.println("Auth problem.");
}
}
private void doWork() throws OAuthAuthenticationException {
String line = null;
do {
System.out.println("1 Datasets");
System.out.println("2 Traits");
System.out.println("0 Custom");
System.out.println("Q QUIT");
line = in.nextLine();
if ("1".equals(line))
doDatasets();
else if ("2".equals(line))
doTraits();
else if ("0".equals(line))
doCustom();
} while (!"Q".equalsIgnoreCase(line));
}
private void doCustom() throws OAuthAuthenticationException {
System.out.print("URL: ");
String url = in.nextLine();
System.out.print("Method [GET]: ");
String method = StringUtils.defaultIfBlank(in.nextLine(), "GET");
System.out.println("JSON: ");
String data = StringUtils.defaultIfBlank(in.nextLine(), null);
// Exec
System.out.println("Put dataset: " + query(Verb.valueOf(method), url, null, data));
}
private void doTraits() throws OAuthAuthenticationException {
String line = null;
do {
System.out.println("1 List parameters");
System.out.println("2 List my methods");
System.out.println("9 List all methods");
System.out.println("3 Add method");
System.out.println("0 Back");
line = in.nextLine();
if ("1".equals(line))
System.out.println("/parameters: " + query("/descriptors"));
else if ("2".equals(line))
System.out.println("/mymethods: " + query("/mymethods"));
else if ("3".equals(line))
addMethod();
else if ("9".equals(line))
System.out.println("/methods: " + query("/methods"));
else if ("0".equalsIgnoreCase(line))
return;
} while (!("0".equalsIgnoreCase(line)));
}
private void doDatasets() throws OAuthAuthenticationException {
String line = null;
do {
System.out.println("1 List");
System.out.println("2 Add");
System.out.println("3 Add data");
System.out.println("4 Add RAW");
System.out.println("0 Back");
line = in.nextLine();
if ("1".equals(line))
System.out.println("/datasets: " + query("/datasets"));
else if ("2".equals(line))
addDataset();
else if ("3".equals(line))
addDatasetData();
else if ("4".equals(line))
addDatasetRaw();
else if ("0".equalsIgnoreCase(line))
return;
} while (!("0".equalsIgnoreCase(line)));
}
private void addMethod() throws OAuthAuthenticationException {
ObjectNode datasetJson = mapper.createObjectNode();
System.out.println("Method description: ");
datasetJson.put("description", in.nextLine());
System.out.println("UOM: ");
datasetJson.put("unit", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Field name: ");
datasetJson.put("fieldName", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Field type: (0=String, 1=Double, 2=Long)");
int fieldType = Integer.parseInt(in.nextLine());
datasetJson.put("fieldType", fieldType);
if (fieldType == 0) {
System.out.println("Field size: ");
datasetJson.put("fieldSize", Integer.parseInt(in.nextLine()));
}
System.out.println("Options: ");
datasetJson.put("options", StringUtils.defaultIfBlank(in.nextLine(), null));
System.out.println("Range: ");
datasetJson.put("range", StringUtils.defaultIfBlank(in.nextLine(), null));
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put method: " + query(Verb.PUT, "/methods", null, datasetJson.toString()));
}
private void addDataset() throws OAuthAuthenticationException {
ObjectNode datasetJson = mapper.createObjectNode();
System.out.println("WIEWS Code: ");
datasetJson.put("institute", in.nextLine());
System.out.println("Dataset title: ");
datasetJson.put("title", in.nextLine());
System.out.println("Dataset description: ");
datasetJson.put("description", in.nextLine());
setAccessToken(properties.getProperty("access.token"));
setRefreshToken(properties.getProperty("refresh.token"));
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put dataset: " + query(Verb.PUT, "/datasets", null, datasetJson.toString()));
}
private void addDatasetData() throws OAuthAuthenticationException {
ObjectNode datasetJson = mapper.createObjectNode();
System.out.println("Dataset ID: ");
long datasetId = Long.parseLong(in.nextLine());
System.out.println("WIEWS Code: ");
datasetJson.put("instCode", in.nextLine());
System.out.println("Data data: ");
datasetJson.put("data", in.nextLine());
System.err.println(datasetJson.toString());
// make a dataset
System.out.println("Put dataset: " + query(Verb.PUT, "/datasets/" + datasetId + "/data", null, datasetJson.toString()));
}
private void addDatasetRaw() throws OAuthAuthenticationException {
System.out.println("Dataset ID: ");
long datasetId = Long.parseLong(in.nextLine());
System.out.println("JSON: ");
String json = in.nextLine();
System.err.println(json);
// make a dataset
System.out.println("Put dataset: " + query(Verb.PUT, "/datasets/" + datasetId + "/data", null, json));
// CropHub auth service
connect(properties.getProperty("client.key"), properties.getProperty("client.secret"), properties.getProperty("client.callback"));
}
private void authenticate() {
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
System.out.println("Authorization URL: \n" + authorizationUrl);
System.out.print("\nVerifier: ");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);
_log.info("ACCESS TOKEN: " + accessToken.getToken() + " sec=" + accessToken.getSecret() + " raw=" + accessToken.getRawResponse());
this.properties.put("access.token", accessToken.getToken());
// Get refresh token ()
Token refreshToken = genesysApi.getRefreshToken(accessToken);
if (refreshToken != null) {
this.properties.put("refresh.token", refreshToken.getToken());
} else {
this.properties.remove("refresh.token");
}
saveProperties();
public void connect(String clientId, String clientSecret, String callback) {
this.service = new ServiceBuilder().provider(this.genesysApi).apiKey(clientId).apiSecret(clientSecret).callback(callback).scope(SCOPE).build();