Commit 7e06f4d2 authored by Erica Freitas de Linhares e Riello's avatar Erica Freitas de Linhares e Riello
Browse files

initial

parents
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.puc-rio.tecgraf</groupId>
<artifactId>resttest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>resttest</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- JAX-RS -->
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.23.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.24</version>
</dependency>
<!-- if you are using Jersey client specific features without the server
side -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
</dependency>
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
package Helper;
import java.io.StringReader;
import java.lang.reflect.Array;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonReader;
import com.google.gson.Gson;
public class JSONHelper {
public static <T> T[] splitArray(String jsonArray, Class<T> objClass) {
JsonReader jsonReader = Json.createReader(new StringReader(jsonArray));
JsonArray array = jsonReader.readArray();
jsonReader.close();
@SuppressWarnings("unchecked")
T[] objects = (T[]) Array.newInstance(objClass, array.size());
for (int i=0; i<array.size(); i++)
objects[i] = objClass.cast(new Gson().fromJson(array.get(i).toString(), objClass));
return objects;
}
}
package Requests.Algorithms;
import Requests.User.User;
public class Algorithm {
private String id;
private String name;
private String description;
private User who_created;
private AlgorithmVersion lastVersion;
private AlgorithmVersion[] versions;
public Algorithm() {
}
public String getName() {
return this.name;
}
public AlgorithmVersion getLastVersion() {
return this.lastVersion;
}
public String getId() {
return this.id;
}
public AlgorithmVersion[] getVersions() {
return this.versions;
}
}
package Requests.Algorithms;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import Helper.JSONHelper;
import Requests.Authentication.Token;
public class AlgorithmExplorer {
public static Algorithm findAlgorithm(String host, Token token, String algorithmName) {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host);
Response response = webTarget.path("algorithms").queryParam("name", algorithmName)
.request("application/json;charset=UTF-8")
.header(HttpHeaders.AUTHORIZATION, token.getTokenType() + token.getAccessToken()).get();
if (response.getStatus() == Response.Status.OK.getStatusCode())
{
Algorithm[] algorithms = getAlgorithms(response.readEntity(String.class));
for (Algorithm algo:algorithms)
if (algo.getName().equals(algorithmName))
return algo;
}
return null;
}
public static Algorithm[] getAlgorithms(String host, Token token) {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host);
Response response = webTarget.path("algorithms")
.request("application/json;charset=UTF-8")
.header(HttpHeaders.AUTHORIZATION, token.getTokenType() + token.getAccessToken()).get();
if (response.getStatus() == Response.Status.OK.getStatusCode())
return getAlgorithms(response.readEntity(String.class));
return null;
}
private static Algorithm[] getAlgorithms(String jsonArray) {
return JSONHelper.splitArray(jsonArray, Algorithm.class);
}
}
package Requests.Algorithms;
public class AlgorithmVersion {
private String id;
private String description;
private Requirement[] requirements;
public AlgorithmVersion() {
}
public String getId() {
return this.id;
}
}
\ No newline at end of file
package Requests.Algorithms;
import javax.json.JsonObject;
public class Requirement {
private String key;
private String name;
private String type;
private boolean editable;
private String value;
public Requirement(JsonObject jsonObject) {
//System.out.println(jsonObject);
this.key = jsonObject.getString("key");
this.name = jsonObject.getString("name");
this.type = jsonObject.getString("type");
this.editable = jsonObject.getBoolean("editable");
//TODO: como ler value?
}
public Requirement() {
}
}
package Requests.Authentication;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
public class Authentication {
public static Token authenticate(String host, String username, String password)
throws LoginOrPasswordNotProvidedException, InvalidLoginOrPasswordException {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host).path("authentication");
Form form = new Form();
form.param("login", username);
form.param("password", password);
Invocation.Builder invocationBuilder = webTarget.request("application/json;charset=UTF-8");
Response response = invocationBuilder.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE),
Response.class);
if (response.getStatus() == Response.Status.OK.getStatusCode())
return new Gson().fromJson(response.readEntity(String.class), Token.class);
else if (response.getStatus() == Response.Status.BAD_REQUEST.getStatusCode())
throw new LoginOrPasswordNotProvidedException();
else if (response.getStatus() == Response.Status.UNAUTHORIZED.getStatusCode())
throw new InvalidLoginOrPasswordException();
return null;
// return (Token) response.readEntity(Token.class);
}
}
package Requests.Authentication;
@SuppressWarnings("serial")
public class InvalidLoginOrPasswordException extends Exception {
}
package Requests.Authentication;
@SuppressWarnings("serial")
public class LoginOrPasswordNotProvidedException extends Exception {
}
package Requests.Authentication;
import java.io.Serializable;
import Requests.User.User;
@SuppressWarnings("serial")
public class Token implements Serializable {
public String accessToken;
public String tokenType;
public User user;
public Token() {
}
public String getTokenType() {
return this.tokenType;
}
public String getAccessToken() {
return this.accessToken;
}
}
package Requests.Jobs;
public class HistoryInfo {
private String status;
private String timestamp;
public HistoryInfo() {
}
public String getStatus() {
return this.status;
}
public String getTimestamp() {
return this.timestamp;
}
}
package Requests.Jobs;
public class JobInfo {
/*
* {"jobId":"eric@Demo.CBLA7K7VDO","sessionId":"erica/DemoProject",
* "projectId":"ZXJpY2EvRGVtb1Byb2plY3Q=","algorithmId":"case",
* "algorithmVersion":"1.0.0","jobOwner":"erica","submissionMachine":"",
* "submissionTime":1478520460508,"description":"teste rest java","state":
* "scheduled","exitStatus":"undefined"}
*/
private String jobId;
private String sessionId;
private String projectId;
private String algorithmId;
private String algorithmVersion;
private String jobOwner;
private String submissionMachine;
private String submissionTime;
private String description;
private String state;
private String exitStatus;
private String projectInfo;
private HistoryInfo[] statusHistory;
private String lastModifiedTime;
public JobInfo() {
}
public String getId() {
return this.jobId;
}
public String getState() {
return this.state;
}
public HistoryInfo getLastestHistoryInfo() {
return this.statusHistory[0];
}
public String getLastModifiedTime() {
return this.lastModifiedTime;
}
}
package Requests.Jobs;
public class JobPullInfo {
/*
* {"date":1479297392110,"jobs":[{"jobId":"eric@Demo.CBLBWP5XDT","sessionId"
* :"erica/DemoProject","projectId":"ZXJpY2EvRGVtb1Byb2plY3Q=",
* "algorithmId":"Alterar case","algorithmVersion":"1.0.0","jobOwner":
* "erica","automaticallyMachineSelection":true,"submissionMachine":"",
* "submissionTime":"2016-11-16T09:56:31.698","executionMachine":"",
* "numberOfAttempts":0,"description":"teste rest java","priority":0,"state"
* :"SCHEDULED","progressInfo":"NaN%","statusHistory":[{"status":"SCHEDULED"
* ,"timestamp":"2016-11-16T09:56:31.845"}],"lastModifiedTime":
* "2016-11-16T09:56:31.846"}]}
*/
private long date;
private JobInfo[] jobs;
private boolean timeout;
public JobPullInfo() {
}
public JobInfo getJob(String jobId) {
if (jobs==null)
return null;
for(JobInfo j:jobs)
if (j.getId().equals(jobId))
return j;
return null;
}
public long getDate() {
return this.date;
}
public boolean getTimeout() {
return this.timeout;
}
}
package Requests.Jobs;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import Requests.Algorithms.Algorithm;
import Requests.Algorithms.AlgorithmVersion;
import Requests.Authentication.Token;
import Requests.Projects.Project;
public class JobServices {
public static JobSession createJobSession(String host, Token token, String jobSessionName) {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host).path("drmaa2").path("jobsession");
Form form = new Form();
form.param("name", jobSessionName);
Invocation.Builder invocationBuilder = webTarget.request("application/json;charset=UTF-8");
Response response = invocationBuilder
.header(HttpHeaders.AUTHORIZATION, token.getTokenType() + token.getAccessToken())
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class);
System.out.println("jobSession response status "+response.getStatus());
return new Gson().fromJson(response.readEntity(String.class), JobSession.class);
}
public static String submitJob(String host, Token token, JobSession session, Project project, Algorithm algorithm,
AlgorithmVersion version, String description, int priority, boolean emailOnTerminated,
String[] candidateMachines, Map<String, String> args) {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host).path("drmaa2").path("job");
String body = createJobSubmissionBodyJson(project, algorithm, version, description, priority, emailOnTerminated,
candidateMachines, args);
Invocation.Builder invocationBuilder = webTarget.request("application/json;charset=UTF-8");
Response response = invocationBuilder
.header(HttpHeaders.AUTHORIZATION, token.getTokenType() + token.getAccessToken())
.header(HttpHeaders.CONTENT_TYPE, "application/json").header(HttpHeaders.CACHE_CONTROL, "no-cache")
.post(Entity.entity(body, MediaType.APPLICATION_JSON_TYPE), Response.class);
if (response.getStatus() == Response.Status.OK.getStatusCode())
return response.readEntity(String.class);
return null;
}
public static JobInfo getJobInfo(String host, Token token, String jobId) {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host).path("drmaa2").path("job").path(jobId);
Invocation.Builder invocationBuilder = webTarget.request("application/json;charset=UTF-8");
Response response = invocationBuilder
.header(HttpHeaders.AUTHORIZATION, token.getTokenType() + token.getAccessToken())
.header(HttpHeaders.CONTENT_TYPE, "application/json").header(HttpHeaders.CACHE_CONTROL, "no-cache")
.get(Response.class);
if (response.getStatus() == Response.Status.OK.getStatusCode())
return new Gson().fromJson(response.readEntity(String.class), JobInfo.class);
return null;
}
public static void awaitJobEnd(String host, Token token, String jobId) {
JobInfo jinfo = getJobInfo(host, token, jobId);
if (jinfo==null)
return;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date;
try {
date = format.parse(jinfo.getLastModifiedTime());
} catch (ParseException e1) {
e1.printStackTrace();
return;
}
long currDate = date.getTime();
while (true)
{
JobPullInfo info = getJobPullInfo(host, token, jobId, currDate);
if (info!=null && info.getJob(jobId)!=null)
{
if (info.getJob(jobId).getState().equals("FINISHED"))
break;
else
{
System.out.println(currDate);
currDate = info.getDate();
}
}
}
}
private static JobPullInfo getJobPullInfo(String host, Token token, String jobId, long date) {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target(host)
.path("jobs")
.path("pull")
.queryParam("jobId", jobId)
.queryParam("date", date);
Invocation.Builder invocationBuilder = webTarget.request("application/json;charset=UTF-8");
Response response = invocationBuilder
.header(HttpHeaders.AUTHORIZATION, token.getTokenType() + token.getAccessToken())
.header(HttpHeaders.CONTENT_TYPE, "application/json").header(HttpHeaders.CACHE_CONTROL, "no-cache")
.get(Response.class);
if (response.getStatus() == Response.Status.OK.getStatusCode())
{
String str = response.readEntity(String.class);
System.out.println(str);
return new Gson().fromJson(str, JobPullInfo.class);
}
return null;
}
private static String createJobSubmissionBodyJson(Project project, Algorithm algorithm, AlgorithmVersion version,
String description, int priority, boolean emailOnTerminated, String[] candidateMachines,
Map<String, String> args) {
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("description", description);
addRemoteCommand(builder, project, algorithm, version);
addArgs(builder, args);
builder.add("priority", Integer.toString(priority));
builder.add("emailOnTerminated", Boolean.toString(emailOnTerminated));
addCandidateMachines(builder, candidateMachines);
return builder.build().toString();
}
private static void addCandidateMachines(JsonObjectBuilder builder, String[] candidateMachines) {
JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
for (String machine : candidateMachines)
arrayBuilder.add(machine);
builder.add("candidateMachines", arrayBuilder);
}
private static void addArgs(JsonObjectBuilder builder, Map<String, String> args) {
JsonObjectBuilder objBuilder = Json.createObjectBuilder();
for (String arg : args.keySet())
objBuilder.add(arg, args.get(arg));
builder.add("args", objBuilder);
}
private static void addRemoteCommand(JsonObjectBuilder builder, Project project, Algorithm algorithm,
AlgorithmVersion version) {
builder.add("remoteCommand", Json.createObjectBuilder().add("algorithmId", algorithm.getId())
.add("versionId", version.getId()).add("projectId", project.getId()));
}
}
package Requests.Jobs;
public class JobSession {
private String contact;
private String sessionName;
private String[] jobCategory;
public JobSession() {
}
public String getName() {
return this.sessionName;
}
}
package Requests.Projects;
import java.io.File;
import java.io.IOException;
import java.text.Normalizer;
import java.util.Base64;
<