Lucio Lelii 2017-02-20 15:28:44 +00:00
commit 7f6b26e1a6
872 changed files with 569265 additions and 0 deletions

36
.classpath Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

13524
.metadata/.bak_0.log Executable file

File diff suppressed because it is too large Load Diff

15970
.metadata/.bak_1.log Executable file

File diff suppressed because it is too large Load Diff

15970
.metadata/.bak_2.log Executable file

File diff suppressed because it is too large Load Diff

15970
.metadata/.bak_3.log Executable file

File diff suppressed because it is too large Load Diff

15970
.metadata/.bak_4.log Executable file

File diff suppressed because it is too large Load Diff

15970
.metadata/.bak_5.log Executable file

File diff suppressed because it is too large Load Diff

11360
.metadata/.bak_6.log Executable file

File diff suppressed because it is too large Load Diff

11327
.metadata/.bak_7.log Executable file

File diff suppressed because it is too large Load Diff

11327
.metadata/.bak_8.log Executable file

File diff suppressed because it is too large Load Diff

11327
.metadata/.bak_9.log Executable file

File diff suppressed because it is too large Load Diff

0
.metadata/.lock Executable file
View File

7770
.metadata/.log Executable file

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
.metadata/.mylyn/tasks.xml.zip Executable file

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
submissionId=1002

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="AddSoftware">
<wb-resource deploy-path="/" source-path="/WebContent" tag="defaultRootSource"/>
<property name="context-root" value="AddSoftware"/>
<property name="java-output-path" value="/AddSoftware/build/classes"/>
</wb-module>
</project-modules>

View File

@ -0,0 +1,124 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/*
* JavaAlgooptimizeModel class is responsible to model the input data model of the optimize resource. This models the data
* that will be sent to the third party service.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class JavaAlgooptimizeModel{
/* There follows a list with the properties that model the optimize resource, as prescribed in the External service layer CIM*/
private String cpuPower;
private int virtualMachineId;
private String hdDimension;
private String softwareName;
private String softwareVersion;
private String virtualMachineName;
private String foremanUsername;
private String foremanPassword;
private int virtualEnvironmentId;
/* There follows a list of setter and getter functions.*/
public void setCpuPower(String cpuPower){
this.cpuPower = cpuPower;
}
public void setVirtualMachineId(int id){
this.virtualMachineId = id;
}
public void setHdDimension(String hdDimension){
this.hdDimension = hdDimension;
}
public void setSoftwareName(String softwareName){
this.softwareName = softwareName;
}
public void setSoftwareVersion(String softwareVersion){
this.softwareVersion = softwareVersion;
}
public String getCpuPower(){
return this.cpuPower;
}
public int getVirtualMachineId(){
return this.virtualMachineId;
}
public String getHdDimension(){
return this.hdDimension;
}
public String getSoftwareName(){
return this.softwareName;
}
public String getSoftwareVersion(){
return this.softwareVersion;
}
public int getVirtualEnvironmentId() {
return virtualEnvironmentId;
}
public void setVirtualEnvironmentId(int virtualEnvironmentId) {
this.virtualEnvironmentId = virtualEnvironmentId;
}
public String getVirtualMachineName() {
return virtualMachineName;
}
public void setVirtualMachineName(String virtualMachineName) {
this.virtualMachineName = virtualMachineName;
}
public String getForemanUsername() {
return foremanUsername;
}
public void setForemanUsername(String foremanUsername) {
this.foremanUsername = foremanUsername;
}
public String getForemanPassword() {
return foremanPassword;
}
public void setForemanPassword(String foremanPassword) {
this.foremanPassword = foremanPassword;
}
}

View File

@ -0,0 +1,143 @@
REQUIREMENTS
------------
The User must be able to create and read a Project, identified by a name
The User must be able to delete a Project
The User must be able to delete a Virtual Environment
The User must be able to create a Virtual Machine, identified by an id given CPU power and HD dimension
The User must be able to delete a Virtual Machine
The User must be able to search a Virtual Machine given CPU power, HD dimension and id
The User must be able to update a Virtual Machine
The System must be able to commit the operation on the Virtual Environment on the Virtual Infrastructure
The User must be able to create and read a Virtual Machine
The User must be able to create, read, update and delete a software identified by a id, a name and a version
The User must be able to create and a Virtual Environment identified by an id and a type
The User must be able to log by an account with username and password
The User must be able to create, read and delete an account
------------
ANNOTATIONS
------------
1:R1 ActsOn 1:T1 1:T2
1:R2 IsActorOf 1:T3 1:T1
1:R3 ActsOn 1:T4 1:T2
1:R4 IsActorOf 1:T3 1:T4
1:T1 Action 25 31 create
1:T2 Object 43 50 Project
1:T3 Actor 4 8 User
1:T4 Action 36 40 read
2:R1 ActsOn 2:T1 2:T2
2:R2 IsActorOf 2:T3 2:T1
2:T1 Action 25 31 delete
2:T2 Object 34 41 Project
2:T3 Actor 4 8 User
3:R1 ActsOn 3:T1 3:T2
3:R2 IsActorOf 3:T3 3:T1
3:R3 ActsOn 3:T1 3:T4
3:R4 HasProperty 3:T4 3:T2
3:T1 Action 25 31 delete
3:T2 Object 34 41 Virtual
3:T3 Actor 4 8 User
3:T4 Object 42 53 Environment
4:R1 IsActorOf 4:T2 4:T1
4:R2 ActsOn 4:T1 4:T3
4:R3 ActsOn 4:T1 4:T4
4:R4 HasProperty 4:T4 4:T3
4:R5 HasProperty 4:T6 4:T7
4:R6 HasProperty 4:T8 4:T9
4:T1 Action 25 31 create
4:T2 Actor 4 8 User
4:T3 Object 34 41 Virtual
4:T4 Object 42 49 Machine
4:T5 Object 68 70 id
4:T6 Object 81 86 power
4:T7 Property 77 80 CPU
4:T8 Object 94 103 dimension
4:T9 Property 91 93 HD
5:R1 ActsOn 5:T1 5:T2
5:R2 IsActorOf 5:T3 5:T1
5:R3 ActsOn 5:T1 5:T4
5:R4 HasProperty 5:T2 5:T4
5:T1 Action 25 31 delete
5:T2 Object 42 49 Machine
5:T3 Actor 4 8 User
5:T4 Object 34 41 Virtual
6:R1 ActsOn 6:T1 6:T2
6:R2 ActsOn 6:T1 6:T3
6:R3 IsActorOf 6:T4 6:T1
6:R4 HasProperty 6:T2 6:T5
6:R5 HasProperty 6:T2 6:T6
6:R6 HasProperty 6:T7 6:T8
6:R7 ActsOn 6:T9 6:T2
6:T1 Action 25 31 search
6:T2 Object 60 65 power
6:T3 Object 42 49 Machine
6:T4 Actor 4 8 User
6:T5 Property 50 55 given
6:T6 Property 56 59 CPU
6:T7 Object 70 79 dimension
6:T8 Property 67 69 HD
6:T9 Action 84 86 id
7:R1 IsActorOf 7:T2 7:T1
7:R2 ActsOn 7:T1 7:T3
7:R3 ActsOn 7:T1 7:T4
7:R4 HasProperty 7:T4 7:T3
7:T1 Action 25 31 update
7:T2 Actor 4 8 User
7:T3 Object 34 41 Virtual
7:T4 Object 42 49 Machine
8:R1 ActsOn 8:T1 8:T2
8:R2 IsActorOf 8:T3 8:T1
8:T1 Action 27 33 commit
8:T2 Object 38 47 operation
8:T3 Actor 4 10 System
9:R1 IsActorOf 9:T2 9:T1
9:R2 ActsOn 9:T3 9:T4
9:R3 IsActorOf 9:T2 9:T3
9:R4 HasProperty 9:T4 9:T5
9:T1 Action 25 31 create
9:T2 Actor 4 8 User
9:T3 Action 36 40 read
9:T4 Object 51 58 Machine
9:T5 Property 43 50 Virtual
10:R1 ActsOn 10:T1 10:T2
10:R2 IsActorOf 10:T3 10:T1
10:R3 ActsOn 10:T4 10:T2
10:R4 IsActorOf 10:T3 10:T4
10:R5 ActsOn 10:T6 10:T2
10:R6 IsActorOf 10:T3 10:T6
10:R7 HasProperty 10:T2 10:T7
10:T1 Action 25 31 create
10:T2 Object 59 67 software
10:T3 Actor 4 8 User
10:T4 Action 33 37 read
10:T5 Action 39 45 update
10:T6 Action 50 56 delete
10:T7 Property 68 78 identified
10:T8 Object 84 86 id
10:T9 Object 101 108 version
11:R1 IsActorOf 11:T2 11:T1
11:R2 HasProperty 11:T3 11:T4
11:T1 Action 25 31 create
11:T2 Actor 4 8 User
11:T3 Object 46 57 Environment
11:T4 Property 38 45 Virtual
11:T5 Object 84 88 type
12:R1 IsActorOf 12:T2 12:T1
12:R2 ActsOn 12:T1 12:T3
12:R3 ActsOn 12:T1 12:T4
12:T1 Action 25 28 log
12:T2 Actor 4 8 User
12:T3 Object 48 56 username
12:T4 Object 35 42 account
13:R1 IsActorOf 13:T2 13:T1
13:R2 ActsOn 13:T1 13:T3
13:R3 IsActorOf 13:T2 13:T4
13:R4 ActsOn 13:T4 13:T3
13:R5 IsActorOf 13:T2 13:T5
13:R6 ActsOn 13:T5 13:T3
13:T1 Action 25 31 create
13:T2 Actor 4 8 User
13:T3 Object 52 59 account
13:T4 Action 33 37 read
13:T5 Action 42 48 delete
------------

View File

@ -0,0 +1,548 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,53 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
//Please add any needed imports here.
/* JavaAlgosearchVirtualMachineModel class is responsible to model any data the searchVirtualMachine resource handles. Since this one
is not automatable, the developer has to manually define it by providing its properties and setter/getter functions.*/
@XmlRootElement
public class JavaSinglesearchVirtualMachineModel{
/* There follows a list with the properties that model the searchVirtualMachine resource, as prescribed in the service CIM*/
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
//Please add any properties of this model here.
/* There follows a list of setter and getter functions.*/
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
//Please add the constructors and any functions of this model here.
}

View File

@ -0,0 +1,64 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
/*
* JavaOptimizeOutputModel class is responsible to model the output data model of the optimize resource. This models the data
* that will be received as output from the third party service.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class JavaOptimizeOutputModel{
/* There follows a list with the properties that model the optimize resource, as prescribed in the External service layer CIM*/
private Boolean completed;
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
/* There follows a list of setter and getter functions.*/
public void setCompleted(Boolean completed){
this.completed = completed;
}
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public Boolean getCompleted(){
return this.completed;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
}

View File

@ -0,0 +1,548 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.ws.rs.core.UriInfo;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.ws.rs.WebApplicationException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClientFactory;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareControllerManager;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
//construct the POST query
this.oOutputDataModel = new JavaOptimizeOutputModel();
// Iterator<String> keys = this.searchKeywords.keySet().iterator();
//
// while (keys.hasNext())
// {
// String key = keys.next();
// String searchKeyword = this.searchKeywords.get(key);
// WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword).queryParam("searchVirtualEnvironmentType", this.searchVirtualEnvironmentType);
// ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
//
// if (isSuccessfullResponseCode(oResponse) == false) {
// throw new WebApplicationException();
// }
//
// JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
//
// this.oOutputDataModel.getlinklist().addAll(tempotputDataModel.getlinklist());
// }
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true"))
{
}
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
return this.oOutputDataModel;
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
ClientResponse deleteVirtualMachineResponse = deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,551 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient, String virtualMachineUrl)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
details.setGetSoftware(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getSoftwareVirtualMachine (Client oJAXRSRESTClient, VirtualMachineDetails details, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,55 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,35 @@
package it.eng.btem.client.test;
import it.eng.btemanager.client.json.LinkListJSonModel;
import it.eng.btemanager.client.json.scase.AccountJSonModel;
import it.eng.btemanager.client.operations.ServiceEngine;
import it.eng.btemanager.client.operations.beans.InputDataBean;
import it.eng.btemanager.client.operations.beans.OperationBean;
import it.eng.btemanager.client.operations.beans.OperationBean.Operation;
import it.eng.btemanager.client.operations.beans.OutputDataBean;
public class Test {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InputDataBean input = new InputDataBean();
input.setBaseUrl("http://localhost:8080/eticsbte/api");
input.setInputData(new AccountJSonModel());
input.setObjectIdentifier("1");
OperationBean operation = new OperationBean(input,Operation.READ_OBJECT);
OperationBean response = ServiceEngine.getInstance().execute(operation);
System.out.println(response.getOutputData());
AccountJSonModel responseModel = new AccountJSonModel();
responseModel.fromJson(response.getOutputData().getResponseData().getBytes());
System.out.println("UserName "+responseModel.getUsername());
}
}

View File

@ -0,0 +1,104 @@
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
public class VirtualMachineDetails {
private List<Integer> virtualEnvironmentIds;
private List<String> softwareElements;
private String updateUrl;
private String deleteUrl;
private String getSoftware;
private String mainUrl;
public VirtualMachineDetails() {
this.virtualEnvironmentIds = new ArrayList<>();
this.softwareElements = new ArrayList<>();
}
public List<Integer> getVirtualEnvironmentIds() {
return virtualEnvironmentIds;
}
public void setVirtualEnvironmentIds(List<Integer> virtualEnvironmentIds) {
this.virtualEnvironmentIds = virtualEnvironmentIds;
}
public List<String> getSoftwareElements() {
return softwareElements;
}
public void setSoftwareElements(List<String> softwareElements) {
this.softwareElements = softwareElements;
}
public String getUpdateUrl() {
return updateUrl;
}
public void setUpdateUrl(String updateUrl) {
this.updateUrl = updateUrl;
}
public String getDeleteUrl() {
return deleteUrl;
}
public void setDeleteUrl(String deleteUrl) {
this.deleteUrl = deleteUrl;
}
public String getGetSoftware() {
return getSoftware;
}
public void setGetSoftware(String getSoftware) {
this.getSoftware = getSoftware;
}
public String getMainUrl() {
return mainUrl;
}
public void setMainUrl(String mainUrl) {
this.mainUrl = mainUrl;
}
}

View File

@ -0,0 +1,543 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,72 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.CreateHostRequest;
import eu.fp7.scase.eticsbte.operationcommit.json.Host;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class CreateVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/CreateVirtualMachineAndSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
CreateHostRequest inputBean = new CreateHostRequest();
inputBean.setHost(new Host(hostId,null,null,"5","1","1","1"));
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("puppetclass_id2", softwareName);
response.setoResponse( oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
//response.responseString = response.oResponse.getEntity(String.class);
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM2");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
bean.addParameter("tomcat");
CreateVirtualHostClient client = new CreateVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.7

View File

@ -0,0 +1,551 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID, int virtualEnvironmentID)
{
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
details.setGetSoftware(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getSoftwareVirtualMachine (Client oJAXRSRESTClient, VirtualMachineDetails details, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,27 @@
package eu.fp7.scase.eticsbte.operationcommit.service;
import com.sun.jersey.api.client.ClientResponse;
import eu.fp7.scase.eticsbte.operationcommit.json.namelist.NameListProvider;
public class ResponseBean {
private NameListProvider responseObject;
private ClientResponse oResponse;
public NameListProvider getResponseObject() {
return responseObject;
}
public void setResponseObject(NameListProvider responseObject) {
this.responseObject = responseObject;
}
public ClientResponse getoResponse() {
return oResponse;
}
public void setoResponse(ClientResponse oResponse) {
this.oResponse = oResponse;
}
}

View File

@ -0,0 +1,547 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
System.out.println("MAIN URI "+details.getMainUrl());
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -0,0 +1,74 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.SoftwareRequest;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class AddSoftwareClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId().toLowerCase();
if (!this.hostId.endsWith(".res.eng.it")) this.hostId = this.hostId+".res.eng.it";
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/CreateSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
SoftwareRequest inputBean = new SoftwareRequest(softwareName);
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
bean.addParameter("tomcat");
AddSoftwareClient client = new AddSoftwareClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,72 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.CreateHostRequest;
import eu.fp7.scase.eticsbte.operationcommit.json.Host;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class CreateVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/CreateVirtualMachineAndSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
CreateHostRequest inputBean = new CreateHostRequest();
inputBean.setHost(new Host(hostId,null,null,"5","1","1","1"));
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("puppetclass_id2", softwareName);
response.setoResponse( oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
//response.responseString = response.oResponse.getEntity(String.class);
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
bean.addParameter("apache");
CreateVirtualHostClient client = new CreateVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,57 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinaltestvm");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,76 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.SoftwareRequest;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class AddSoftwareClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId().toLowerCase();
if (!this.hostId.endsWith(".res.eng.it")) this.hostId = this.hostId+".res.eng.it";
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/CreateSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
SoftwareRequest inputBean = new SoftwareRequest(softwareName);
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println(inputString);
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
bean.addParameter("tomcat");
AddSoftwareClient client = new AddSoftwareClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,75 @@
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
public class VirtualMachineDetails {
private List<Integer> virtualEnvironmentIds;
private List<String> softwareElements;
private String updateUrl;
private String deleteUrl;
public VirtualMachineDetails() {
this.virtualEnvironmentIds = new ArrayList<>();
this.softwareElements = new ArrayList<>();
}
public List<Integer> getVirtualEnvironmentIds() {
return virtualEnvironmentIds;
}
public void setVirtualEnvironmentIds(List<Integer> virtualEnvironmentIds) {
this.virtualEnvironmentIds = virtualEnvironmentIds;
}
public List<String> getSoftwareElements() {
return softwareElements;
}
public void setSoftwareElements(List<String> softwareElements) {
this.softwareElements = softwareElements;
}
public String getUpdateUrl() {
return updateUrl;
}
public void setUpdateUrl(String updateUrl) {
this.updateUrl = updateUrl;
}
public String getDeleteUrl() {
return deleteUrl;
}
public void setDeleteUrl(String deleteUrl) {
this.deleteUrl = deleteUrl;
}
}

View File

@ -0,0 +1,42 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
private void mai() {
RequestBean bean = new RequestBean();
bean.setHostId("scasefinalTestVM");
}
}

View File

@ -0,0 +1,73 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import eu.fp7.scase.eticsbte.operationcommit.json.JSonModel;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
//Please add any needed imports here.
/* JavaAlgosearchVirtualMachineModel class is responsible to model any data the searchVirtualMachine resource handles. Since this one
is not automatable, the developer has to manually define it by providing its properties and setter/getter functions.*/
@XmlRootElement
public class JavaSearchResultModel extends JSonModel{
/* There follows a list with the properties that model the searchVirtualMachine resource, as prescribed in the service CIM*/
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
//Please add any properties of this model here.
/* There follows a list of setter and getter functions.*/
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
//Please add the constructors and any functions of this model here.
@Override
protected int checkKey(String key) {
// TODO Auto-generated method stub
return 0;
}
@Override
protected JSonModel generateInternalObject(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
protected JSonModel generateInternalArrayObject(String key, int element) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,522 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,544 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,89 @@
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
public class VirtualMachineDetails {
private List<Integer> virtualEnvironmentIds;
private List<String> softwareElements;
private String updateUrl;
private String deleteUrl;
private String getSoftware;
public VirtualMachineDetails() {
this.virtualEnvironmentIds = new ArrayList<>();
this.softwareElements = new ArrayList<>();
}
public List<Integer> getVirtualEnvironmentIds() {
return virtualEnvironmentIds;
}
public void setVirtualEnvironmentIds(List<Integer> virtualEnvironmentIds) {
this.virtualEnvironmentIds = virtualEnvironmentIds;
}
public List<String> getSoftwareElements() {
return softwareElements;
}
public void setSoftwareElements(List<String> softwareElements) {
this.softwareElements = softwareElements;
}
public String getUpdateUrl() {
return updateUrl;
}
public void setUpdateUrl(String updateUrl) {
this.updateUrl = updateUrl;
}
public String getDeleteUrl() {
return deleteUrl;
}
public void setDeleteUrl(String deleteUrl) {
this.deleteUrl = deleteUrl;
}
public String getGetSoftware() {
return getSoftware;
}
public void setGetSoftware(String getSoftware) {
this.getSoftware = getSoftware;
}
}

View File

@ -0,0 +1,178 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.virtualmachine;
import java.util.List;
import java.util.Arrays;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.virtualenvironment.JavavirtualEnvironmentModel;
/* This class processes PUT requests for virtualMachine resources and creates the hypermedia to be returned to the client*/
public class PutvirtualMachineHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private String strResourcePath; //relative path to the current resource
private JavavirtualMachineModel oJavavirtualMachineModel;
private JavavirtualEnvironmentModel oJavavirtualEnvironmentModel;
private String strOptionalUpdateRelations;
private String strOptionalUpdateParent;
private String strOptionalRelationName;
private Integer iOptionalResourceId;
private String strOptionalAddRelation;
private final List<String> listOfParentResources = Arrays.asList("virtualEnvironment");
private final List<String> listOfChildrenResources = Arrays.asList("software");
public PutvirtualMachineHandler(int virtualEnvironmentId, int virtualMachineId, JavavirtualMachineModel oJavavirtualMachineModel, UriInfo oApplicationUri, String strOptionalUpdateRelations, String strOptionalUpdateParent, String strOptionalRelationName, String strOptionalAddRelation, Integer iOptionalResourceId){
this.oJavavirtualMachineModel = oJavavirtualMachineModel;
this.oJavavirtualMachineModel.setvirtualMachineId(virtualMachineId);
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.strResourcePath = calculateProperResourcePath();
oJavavirtualEnvironmentModel = new JavavirtualEnvironmentModel();
oJavavirtualEnvironmentModel.setvirtualEnvironmentId(virtualEnvironmentId);
oJavavirtualMachineModel.getSetOfParentJavavirtualEnvironmentModel().add(this.oJavavirtualEnvironmentModel);
this.strOptionalUpdateRelations = strOptionalUpdateRelations;
System.out.println(this.strOptionalUpdateRelations);
this.strOptionalUpdateParent = strOptionalUpdateParent;
System.out.println(this.strOptionalUpdateParent);
this.strOptionalRelationName = strOptionalRelationName;
System.out.println(this.strOptionalRelationName);
this.iOptionalResourceId = iOptionalResourceId;
System.out.println(this.iOptionalResourceId);
this.strOptionalAddRelation = strOptionalAddRelation;
System.out.println(this.strOptionalAddRelation);
if(this.strOptionalUpdateRelations != null && this.strOptionalUpdateRelations.equalsIgnoreCase("true")){
checkRelationUpdateInfo();
}
}
public String calculateProperResourcePath(){
if(this.oApplicationUri.getPath().lastIndexOf('/') == this.oApplicationUri.getPath().length() - 1){
return this.oApplicationUri.getPath().substring(0, this.oApplicationUri.getPath().length() - 1);
}
else{
return this.oApplicationUri.getPath();
}
}
private boolean hasParent(String strPossibleParentName){
for(int i = 0; i < this.listOfParentResources.size(); i++){
if(this.listOfParentResources.get(i).equalsIgnoreCase(strPossibleParentName)){
return true;
}
}
return false;
}
private boolean hasChild(String strPossibleChildName){
for(int i = 0; i < this.listOfChildrenResources.size(); i++){
if(this.listOfChildrenResources.get(i).equalsIgnoreCase(strPossibleChildName)){
return true;
}
}
return false;
}
private void checkRelationUpdateInfo(){
//check if the request is about updating relations to parent resources
if(this.strOptionalUpdateParent != null && this.strOptionalUpdateParent.equalsIgnoreCase("true")){
//check if the request is to update relations to a valid parent resource
if(this.strOptionalRelationName != null && hasParent(this.strOptionalRelationName)){
if(this.strOptionalAddRelation != null && (this.strOptionalAddRelation.equalsIgnoreCase("true") || this.strOptionalAddRelation.equalsIgnoreCase("false"))
&& (this.iOptionalResourceId != null && this.iOptionalResourceId > 0) ){
//then this is a valid request and should be processed
return;
}
else{ //else it is an invalid request
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
else{ //else the selected parent resource is an invalid parent and this is a bad request
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
//of if it is about updating relations to children resources
else if(this.strOptionalUpdateParent != null && this.strOptionalUpdateParent.equalsIgnoreCase("false")){
//check if the request is to update relations to a valid child resource
if(this.strOptionalRelationName != null && hasChild(this.strOptionalRelationName)){
if(this.strOptionalAddRelation != null && (this.strOptionalAddRelation.equalsIgnoreCase("true") || this.strOptionalAddRelation.equalsIgnoreCase("false"))
&& (this.iOptionalResourceId != null && this.iOptionalResourceId > 0) ){
//then this is a valid request and should be processed
return;
}
else{ //else it is an invalid request
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
else{ //else the selected parent resource is an invalid parent and this is a bad request
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
else{ //otherwise this is a bad request
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
public JavavirtualMachineModel putJavavirtualMachineModel(){
return createHypermedia(oHibernateController.putvirtualMachine(oJavavirtualMachineModel, this.strOptionalUpdateRelations, this.strOptionalUpdateParent, this.strOptionalRelationName, this.strOptionalAddRelation, this.iOptionalResourceId));
}
/* This function produces hypermedia links to be sent to the client so as it will be able to forward the application state in a valid way.*/
public JavavirtualMachineModel createHypermedia(JavavirtualMachineModel oJavavirtualMachineModel){
/* Create hypermedia links towards this specific Resource resource. These can be GET, PUT and/or delete depending on what was specified in the service CIM.*/
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), this.strResourcePath), "Get the virtualMachine", "GET", "Sibling"));
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), this.strResourcePath), "Update the virtualMachine", "PUT", "Sibling"));
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), this.strResourcePath), "Delete the virtualMachine", "DELETE", "Sibling"));
/* Calculate the relative path towards any related resources of this one. Then add each new hypermedia link with that relative path to the hypermedia linklist to be sent back to client.*/
String oRelativePath;
oRelativePath = this.strResourcePath.substring(this.strResourcePath.indexOf("/virtualMachine") + 1);
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s/%s", oApplicationUri.getBaseUri(), oRelativePath, "software"), "Get all the softwares of this virtualMachine", "GET", "Child"));
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s/%s", oApplicationUri.getBaseUri(), oRelativePath, "software"), "Create a new software for this virtualMachine", "POST", "Child"));
/* Finally, truncate the current URI so as to point to the resource manager of which this resource is related.
Then create the hypermedia links towards the parent resources.*/
int iLastSlashIndex = String.format("%s%s", oApplicationUri.getBaseUri(), this.strResourcePath).lastIndexOf("/");
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), this.strResourcePath).substring(0, iLastSlashIndex), "Create a new virtualMachine", "POST", "Parent"));
oJavavirtualMachineModel.getlinklist().add(new HypermediaLink(String.format("%s%s", oApplicationUri.getBaseUri(), this.strResourcePath).substring(0, iLastSlashIndex), "Get all virtualMachines of this virtualEnvironment", "GET", "Parent"));
return oJavavirtualMachineModel;
}
}

View File

@ -0,0 +1,72 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.CreateHostRequest;
import eu.fp7.scase.eticsbte.operationcommit.json.Host;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class CreateVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/CreateVirtualMachineAndSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
CreateHostRequest inputBean = new CreateHostRequest();
inputBean.setHost(new Host(hostId,null,null,"5","1","1","1"));
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("puppetclass_id2", softwareName);
System.out.println("INPUT STRING "+inputString);
response.setoResponse( oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
//response.responseString = response.oResponse.getEntity(String.class);
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinaltestvm.res.eng.it");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
CreateVirtualHostClient client = new CreateVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,567 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getSoftwareVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,57 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,73 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.CreateHostRequest;
import eu.fp7.scase.eticsbte.operationcommit.json.Host;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class CreateVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/CreateVirtualMachineAndSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
CreateHostRequest inputBean = new CreateHostRequest();
inputBean.setHost(new Host(hostId,null,null,"5","1","1","1"));
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("puppetclass_id2", softwareName);
System.out.println("INPUT STRING "+inputString);
response.setoResponse( oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
//response.responseString = response.oResponse.getEntity(String.class);
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
bean.addParameter("apache");
CreateVirtualHostClient client = new CreateVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,547 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
System.out.println("Parent URI "+virtualEnvironmentUrl);
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,519 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,522 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
System.out.println("Delete process");
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,546 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId">
<wb-module deploy-name="AddSoftware"/>
</project-modules>

View File

@ -0,0 +1,54 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,551 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
System.out.println("Create");
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() == 200 || response.getoResponse().getStatus() == 201)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else throw new WebApplicationException();
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
System.out.println(url);
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,526 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.ws.rs.core.UriInfo;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.ws.rs.WebApplicationException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClientFactory;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareControllerManager;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,552 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() == 200 || response.getoResponse().getStatus() == 201)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else throw new WebApplicationException();
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
String softwareString = getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion();
System.out.println("Software String = "+softwareString);
details.getSoftwareElements().add(softwareString);
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

View File

@ -0,0 +1,546 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,8 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -0,0 +1,550 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() == 200 || response.getoResponse().getStatus() == 201)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else throw new WebApplicationException();
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,76 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.json.SoftwareRequest;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class AddSoftwareClient implements ServiceClient {
private String hostId,
username,
password,
softwareName,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId().toLowerCase();
if (!this.hostId.endsWith(".res.eng.it")) this.hostId = this.hostId+".res.eng.it";
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.softwareName = requestBean.getParameter(0);
this.url = requestBean.getBaseUrl()+"/AddSoftware/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
SoftwareRequest inputBean = new SoftwareRequest(softwareName);
String inputString = null;
try{
inputString = inputBean.toJson();
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println(inputString);
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id0", hostId).queryParam("puppetclass_id2", this.softwareName);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, inputString));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
bean.addParameter("tomcat");
AddSoftwareClient client = new AddSoftwareClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,57 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM.res.eng.it");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,47 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
private void mai() {
RequestBean bean = new RequestBean();
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
client.execute(oJAXRSRESTClient)
}
}

View File

@ -0,0 +1,550 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() == 200 || response.getoResponse().getStatus() == 201)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else throw new WebApplicationException();
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
System.out.println(url);
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,57 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class));
return response;
}
public static void main(String[] args) {
RequestBean bean = new RequestBean();
bean.setBaseUrl("http://localhost:8080");
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,12 @@
package eu.fp7.scase.eticsbte.optimize;
import java.util.List;
public class VirtualMachineDetails {
private List<String> virtualEnvironmentUrls;
private List<String> softwareElements;
}

View File

@ -0,0 +1,554 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.ws.rs.core.UriInfo;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.ws.rs.WebApplicationException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClientFactory;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareControllerManager;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
//construct the POST query
this.oOutputDataModel = new JavaOptimizeOutputModel();
// Iterator<String> keys = this.searchKeywords.keySet().iterator();
//
// while (keys.hasNext())
// {
// String key = keys.next();
// String searchKeyword = this.searchKeywords.get(key);
// WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword).queryParam("searchVirtualEnvironmentType", this.searchVirtualEnvironmentType);
// ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
//
// if (isSuccessfullResponseCode(oResponse) == false) {
// throw new WebApplicationException();
// }
//
// JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
//
// this.oOutputDataModel.getlinklist().addAll(tempotputDataModel.getlinklist());
// }
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true"))
{
}
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
return this.oOutputDataModel;
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
ClientResponse deleteVirtualMachineResponse = deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Virtual machine Deleted");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,523 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
System.out.println("Delete process");
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,45 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
private void mai() {
RequestBean bean = new RequestBean();
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
}
}

View File

@ -0,0 +1,549 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() == 200)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else throw new WebApplicationException();
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,73 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import eu.fp7.scase.eticsbte.operationcommit.json.JSonModel;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
//Please add any needed imports here.
/* JavaAlgosearchVirtualMachineModel class is responsible to model any data the searchVirtualMachine resource handles. Since this one
is not automatable, the developer has to manually define it by providing its properties and setter/getter functions.*/
@XmlRootElement
public class JavaSearchResultModel extends JSonModel{
/* There follows a list with the properties that model the searchVirtualMachine resource, as prescribed in the service CIM*/
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
//Please add any properties of this model here.
/* There follows a list of setter and getter functions.*/
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
//Please add the constructors and any functions of this model here.
@Override
protected int checkKey(String key)
{
return if (key.equals("));
}
@Override
protected JSonModel generateInternalObject(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
protected JSonModel generateInternalArrayObject(String key, int element) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,62 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.QueryParam;
/*
* JavaAlgooptimizeController class is responsible to handle incoming HTTP requests for the optimize resource. More specifically
* this resource controller handles client requests that are delegated to an external server, which is executed at
* http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine
*/
@Path("/Algooptimize")
public class JavaAlgooptimizeController{
@Context
private UriInfo oApplicationUri;
/*
* This function is the WEB API of resource optimize and accepts http POST requests,
* which it delegates to the underlying Handler PostoptimizeHandler.
* It returns any response formatted as stated in the @Produces JAX-RS annotation below.
*/
@Path("/")
@POST
@Produces("application/JSON")
@Consumes("application/JSON")
public JavaOptimizeOutputModel postoptimize(@QueryParam("searchVirtualMachineCpuPower") String searchVirtualMachineCpuPower, @QueryParam("searchVirtualMachineHdDimension") String searchVirtualMachineHdDimension, @QueryParam("searchKeyword") String searchKeyword, @QueryParam("searchVirtualEnvironmentType") String searchVirtualEnvironmentType, JavaAlgooptimizeModel oJavaAlgooptimizeModel){
//create a new PostoptimizeHandler
PostoptimizeHandler oPostoptimizeHandler = new PostoptimizeHandler(searchVirtualMachineCpuPower, searchVirtualMachineHdDimension, searchKeyword, searchVirtualEnvironmentType, oJavaAlgooptimizeModel, oApplicationUri);
return oPostoptimizeHandler.postoptimize();
}
}

View File

@ -0,0 +1,549 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() != 200)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else if (this.oJavaAlgooptimizeModel.getVirtualMachineId() < 0)
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
else // this.oJavaAlgooptimizeModel.getVirtualMachineId() == 0
{
// Direct creation forced
directCreation(oJAXRSRESTClient);
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus() == 200 || response.getoResponse().getStatus() == 201)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else throw new WebApplicationException();
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,545 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="AddSoftware">
<wb-resource deploy-path="/" source-path="/WebContent" tag="defaultRootSource"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
<property name="context-root" value="AddSoftware"/>
<property name="java-output-path" value="/AddSoftware/build/classes"/>
</wb-module>
</project-modules>

View File

@ -0,0 +1,53 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
//Please add any needed imports here.
/* JavaAlgosearchVirtualMachineModel class is responsible to model any data the searchVirtualMachine resource handles. Since this one
is not automatable, the developer has to manually define it by providing its properties and setter/getter functions.*/
@XmlRootElement
public class JavaSinglesearchVirtualMachineModel{
/* There follows a list with the properties that model the searchVirtualMachine resource, as prescribed in the service CIM*/
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
//Please add any properties of this model here.
/* There follows a list of setter and getter functions.*/
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
//Please add the constructors and any functions of this model here.
}

View File

@ -0,0 +1,89 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/*
* JavaAlgooptimizeModel class is responsible to model the input data model of the optimize resource. This models the data
* that will be sent to the third party service.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class JavaAlgooptimizeModel{
/* There follows a list with the properties that model the optimize resource, as prescribed in the External service layer CIM*/
private String cpuPower;
private String id;
private String hdDimension;
private String softwareName;
private String softwareVersion;
/* There follows a list of setter and getter functions.*/
public void setCpuPower(String cpuPower){
this.cpuPower = cpuPower;
}
public void setId(String id){
this.id = id;
}
public void setHdDimension(String hdDimension){
this.hdDimension = hdDimension;
}
public void setSoftwareName(String softwareName){
this.softwareName = softwareName;
}
public void setSoftwareVersion(String softwareVersion){
this.softwareVersion = softwareVersion;
}
public String getCpuPower(){
return this.cpuPower;
}
public String getId(){
return this.id;
}
public String getHdDimension(){
return this.hdDimension;
}
public String getSoftwareName(){
return this.softwareName;
}
public String getSoftwareVersion(){
return this.softwareVersion;
}
}

View File

@ -0,0 +1,33 @@
package eu.fp7.scase.eticsbte.operationcommit.service;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.GetSoftwareClient;
public class ServiceClientFactory
{
public static ServiceClient generateService (int operation)
{
switch (operation)
{
case 0: // read VMs and Software
return new GetSoftwareClient();
case 1: // create VM and Software
return new CreateHostClient();
case 2: //add software
return new AddSoftwareClient();
case 3: //Delete sofwrare
return new DeleteSoftwareClient();
case 4: // Delete VM
return new RemoveSoftwareClient();
}
return null;
}
}

View File

@ -0,0 +1,34 @@
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
public class VirtualMachineDetails {
private List<String> virtualEnvironmentUrls;
private List<String> softwareElements;
public VirtualMachineDetails() {
this.virtualEnvironmentUrls = new ArrayList<>();
this.softwareElements = new ArrayList<>();
}
public List<String> getVirtualEnvironmentUrls() {
return virtualEnvironmentUrls;
}
public void setVirtualEnvironmentUrls(List<String> virtualEnvironmentUrls) {
this.virtualEnvironmentUrls = virtualEnvironmentUrls;
}
public List<String> getSoftwareElements() {
return softwareElements;
}
public void setSoftwareElements(List<String> softwareElements) {
this.softwareElements = softwareElements;
}
}

View File

@ -0,0 +1,91 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>scase-auto-generated</groupId>
<artifactId>eticsbte</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>eticsbte</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.13.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.18.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey.samples</groupId>
<artifactId>json-from-jaxb</artifactId>
<version>1.18.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search</artifactId>
<version>4.4.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search</artifactId>
<version>4.4.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.13.Final</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
</dependencies>
<build>
<finalName>eticsbte</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,522 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID;
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,125 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import javax.xml.bind.annotation.XmlRootElement;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/*
* JavaAlgooptimizeModel class is responsible to model the input data model of the optimize resource. This models the data
* that will be sent to the third party service.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class JavaAlgooptimizeModel{
/* There follows a list with the properties that model the optimize resource, as prescribed in the External service layer CIM*/
private String cpuPower;
private int virtualMachineId;
private String hdDimension;
private String softwareName;
private String softwareVersion;
private String virtualMachineName;
private String foremanUsername;
private String foremanPassword;
private int virtualEnvironmentId;
private boolean delete;
/* There follows a list of setter and getter functions.*/
public void setCpuPower(String cpuPower){
this.cpuPower = cpuPower;
}
public void setVirtualMachineId(int id){
this.virtualMachineId = id;
}
public void setHdDimension(String hdDimension){
this.hdDimension = hdDimension;
}
public void setSoftwareName(String softwareName){
this.softwareName = softwareName;
}
public void setSoftwareVersion(String softwareVersion){
this.softwareVersion = softwareVersion;
}
public String getCpuPower(){
return this.cpuPower;
}
public int getVirtualMachineId(){
return this.virtualMachineId;
}
public String getHdDimension(){
return this.hdDimension;
}
public String getSoftwareName(){
return this.softwareName;
}
public String getSoftwareVersion(){
return this.softwareVersion;
}
public int getVirtualEnvironmentId() {
return virtualEnvironmentId;
}
public void setVirtualEnvironmentId(int virtualEnvironmentId) {
this.virtualEnvironmentId = virtualEnvironmentId;
}
public String getVirtualMachineName() {
return virtualMachineName;
}
public void setVirtualMachineName(String virtualMachineName) {
this.virtualMachineName = virtualMachineName;
}
public String getForemanUsername() {
return foremanUsername;
}
public void setForemanUsername(String foremanUsername) {
this.foremanUsername = foremanUsername;
}
public String getForemanPassword() {
return foremanPassword;
}
public void setForemanPassword(String foremanPassword) {
this.foremanPassword = foremanPassword;
}
}

View File

@ -0,0 +1,544 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteVirtualHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.RemoveSoftwareClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteVirtualHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getoResponse().getStatus()!= 200)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateVirtualHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET")&&searchResult.getLinkRel().equals("virtualEnvironment"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,541 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.ws.rs.core.UriInfo;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.ws.rs.WebApplicationException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClientFactory;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareControllerManager;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
//construct the POST query
this.oOutputDataModel = new JavaOptimizeOutputModel();
// Iterator<String> keys = this.searchKeywords.keySet().iterator();
//
// while (keys.hasNext())
// {
// String key = keys.next();
// String searchKeyword = this.searchKeywords.get(key);
// WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword).queryParam("searchVirtualEnvironmentType", this.searchVirtualEnvironmentType);
// ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
//
// if (isSuccessfullResponseCode(oResponse) == false) {
// throw new WebApplicationException();
// }
//
// JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
//
// this.oOutputDataModel.getlinklist().addAll(tempotputDataModel.getlinklist());
// }
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true"))
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
ClientResponse deleteVirtualMachineResponse = deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
}
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getDetailsVirtualMachine(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
return this.oOutputDataModel;
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getDetailsVirtualMachine (Client oJAXRSRESTClient, int virtualMachineID)
{
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
VirtualMachineDetails details = new VirtualMachineDetails();
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,73 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import eu.fp7.scase.eticsbte.operationcommit.json.JSonModel;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
//Please add any needed imports here.
/* JavaAlgosearchVirtualMachineModel class is responsible to model any data the searchVirtualMachine resource handles. Since this one
is not automatable, the developer has to manually define it by providing its properties and setter/getter functions.*/
@XmlRootElement
public class JavaSearchResultModel extends JSonModel{
/* There follows a list with the properties that model the searchVirtualMachine resource, as prescribed in the service CIM*/
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
//Please add any properties of this model here.
/* There follows a list of setter and getter functions.*/
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
//Please add the constructors and any functions of this model here.
@Override
protected int checkKey(String key) {
// TODO Auto-generated method stub
return 0;
}
@Override
protected JSonModel generateInternalObject(String key) {
// TODO Auto-generated method stub
return null;
}
@Override
protected JSonModel generateInternalArrayObject(String key, int element) {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,546 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.map.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.AddSoftwareClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.CreateHostClient;
import eu.fp7.scase.eticsbte.operationcommit.service.impl.DeleteHostClient;
import eu.fp7.scase.eticsbte.searchvirtualmachine.JavaAlgosearchVirtualMachineModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModel;
import eu.fp7.scase.eticsbte.software.JavasoftwareModelManager;
import eu.fp7.scase.eticsbte.utilities.HibernateController;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModel;
import eu.fp7.scase.eticsbte.virtualmachine.JavavirtualMachineModelManager;
/*
*This class processes client requests for optimize resource that are to be delegated to an existing 3rd party service.
*Uppon its output receival, this class repackages the output and creates the hypermedia links with the search results to be returned to the client
*/
public class PostoptimizeHandler{
private HibernateController oHibernateController;
private UriInfo oApplicationUri; //Standard datatype that holds information on the URI info of this request
private JavaAlgooptimizeModel oJavaAlgooptimizeModel;
private JavaOptimizeOutputModel oOutputDataModel;
private Map<String, String> searchKeywords;
private ClientConfig oClientConfiguration;
private final String ENV_TYPE = "testing";
public PostoptimizeHandler(JavaAlgooptimizeModel oTempJavaAlgooptimizeModel, UriInfo oApplicationUri){
oJavaAlgooptimizeModel = new JavaAlgooptimizeModel();
this.oHibernateController = HibernateController.getHibernateControllerHandle();
this.oApplicationUri = oApplicationUri;
this.oJavaAlgooptimizeModel = oTempJavaAlgooptimizeModel;
this.searchKeywords = new HashMap<>() ;
searchKeywords.put("searchVirtualMachineCpuPower", oTempJavaAlgooptimizeModel.getCpuPower());
searchKeywords.put("searchVirtualMachineHdDimension", oTempJavaAlgooptimizeModel.getHdDimension());
//initialize JAX-RS Client configuration
this.oClientConfiguration = new DefaultClientConfig();
this.oClientConfiguration.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
}
public JavaOptimizeOutputModel postoptimize(){
//Return any results in the hypermedia links form.
return interoperateWithExternalService();
}
/*
* This function handles the interoperation with the existing 3rd party service. It calls the according functions to create the input
* to be sent to it, to receive its output and if necessary to persist the outcome in the database.
* Finally, the result is returned to the client.
*/
public JavaOptimizeOutputModel interoperateWithExternalService(){
//create a new JAX-RS client
Client oJAXRSRESTClient = Client.create(this.oClientConfiguration);
this.oOutputDataModel = new JavaOptimizeOutputModel();
String delete = this.oJavaAlgooptimizeModel.getDelete();
if (delete != null && delete.equalsIgnoreCase("true")) deleteVMProcess(oJAXRSRESTClient);
else createVMProcess(oJAXRSRESTClient);
return this.oOutputDataModel;
}
private void createVMProcess (Client oJAXRSRESTClient)
{
if (this.oJavaAlgooptimizeModel.getVirtualMachineId() > 0)
{
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
// Virtual Machine selected, getting software
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<String> software = vmDetails.getSoftwareElements();
if (!software.contains(this.oJavaAlgooptimizeModel.getSoftwareName()+"_"+this.oJavaAlgooptimizeModel.getSoftwareVersion()))
{
// Install software on the VM
createSoftware(oJAXRSRESTClient, "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software");
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new AddSoftwareClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
}
if (!vmDetails.getVirtualEnvironmentIds().contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
//Generating new link to the new VirtualEnvironment
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),true);
}
HypermediaLink virtualMachine = new HypermediaLink();
virtualMachine.setIdType(0);
virtualMachine.setLinkRel("Modified Virtual machine");
virtualMachine.setLinkURI("http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"virtualMachine/"+virtualMachineID);
virtualMachine.setLinkVerb("GET");
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
else
{
JavaOptimizeOutputModel firstSearchResults = searchVirtualMachines (oJAXRSRESTClient);
if (firstSearchResults.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else
{
List<String> testvirtualMachinessID = searchVirtualMachinesUnderEnvironments(oJAXRSRESTClient);
if (!testvirtualMachinessID.isEmpty())
{
for (HypermediaLink hl : firstSearchResults.getlinklist())
{
if (!testvirtualMachinessID.contains(hl.getLinkURI()))
{
this.oOutputDataModel.getlinklist().add(hl);
}
}
if (this.oOutputDataModel.getlinklist().size() == 0) directCreation(oJAXRSRESTClient);
else this.oOutputDataModel.setCompleted(false);
}
else
{
this.oOutputDataModel.setCompleted(false);
this.oOutputDataModel.getlinklist().addAll( firstSearchResults.getlinklist());
}
}
}
}
private void deleteVMProcess (Client oJAXRSRESTClient)
{
// Delete
int virtualMachineID = this.oJavaAlgooptimizeModel.getVirtualMachineId();
VirtualMachineDetails vmDetails = getVirtualMachineDetails(oJAXRSRESTClient, virtualMachineID);
List<Integer> virtualEnvironments = vmDetails.getVirtualEnvironmentIds();
if (virtualEnvironments.size()>1 && virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Remve VM from Virtual Environment
System.out.println("Removing relationship");
updateVirtualMachine (oJAXRSRESTClient,vmDetails.getUpdateUrl(),this.oJavaAlgooptimizeModel.getVirtualEnvironmentId(),false);
}
else if (virtualEnvironments.contains(this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()))
{
// Completely remove the Virtual Machine
RequestBean requestBean = createForemanRequestBean();
ServiceClient serviceClient = new DeleteHostClient();
serviceClient.setParameters(requestBean);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() == null)
{
throw new WebApplicationException();
}
// Delete the Host from the DB
WebResource deleteVirtualMachineResource = oJAXRSRESTClient.resource(vmDetails.getDeleteUrl());
deleteVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class);
}
this.oOutputDataModel.setCompleted(true);
}
private void directCreation (Client oJAXRSRESTClient)
{
JavavirtualMachineModel newVirtualMachine = createVirtualMachine(oJAXRSRESTClient);
HypermediaLink createSoftware = null;
HypermediaLink virtualMachine = null;
boolean exit = false;
Iterator<HypermediaLink> hls = newVirtualMachine.getlinklist().iterator();
while (hls.hasNext() && !exit)
{
HypermediaLink hl = hls.next();
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("POST"))
{
createSoftware = hl;
exit = createSoftware != null && virtualMachine != null;
}
else if (hl.getLinkType().equals("Sibling") && hl.getLinkVerb().equals("GET"))
{
virtualMachine = hl;
exit = createSoftware != null && virtualMachine != null;
}
}
if (createSoftware == null)
{
throw new WebApplicationException();
}
String createSoftwareUrl = createSoftware.getLinkURI();
JavasoftwareModel softwareModel = createSoftware(oJAXRSRESTClient, createSoftwareUrl);
// Create VM and software on Foreman
RequestBean request = createForemanRequestBean();
//construct the query
ServiceClient serviceClient = new CreateHostClient();
serviceClient.setParameters(request);
ResponseBean response = serviceClient.execute(oJAXRSRESTClient);
if (response.getResponseObject() != null)
{
this.oOutputDataModel.getlinklist().add(virtualMachine);
this.oOutputDataModel.setCompleted(true);
}
}
private RequestBean createForemanRequestBean ()
{
RequestBean request = new RequestBean();
request.setHostId(this.oJavaAlgooptimizeModel.getVirtualMachineName());
request.setForemanUserName(this.oJavaAlgooptimizeModel.getForemanUsername());
request.setForemanPassword(this.oJavaAlgooptimizeModel.getForemanPassword());
request.setBaseUrl("http://localhost:8080");
String softwareName = this.oJavaAlgooptimizeModel.getSoftwareName();
if (softwareName != null) request.addParameter(softwareName);
return request;
}
private JavaOptimizeOutputModel searchVirtualMachines (Client oJAXRSRESTClient)
{
Iterator<String> keys = this.searchKeywords.keySet().iterator();
JavaOptimizeOutputModel response = new JavaOptimizeOutputModel();
Map<String, HypermediaLink> hyperMediaMap = new HashMap<>();
while (keys.hasNext())
{
String key = keys.next();
String searchKeyword = this.searchKeywords.get(key);
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam(key, "true").queryParam("searchKeyword", searchKeyword);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
String tempotputDataModelString = oResponse.getEntity(String.class);
JavaAlgosearchVirtualMachineModel tempotputDataModel = new JavaAlgosearchVirtualMachineModel();
if (tempotputDataModelString.indexOf('[')==-1)
{
try
{
JavaSinglesearchVirtualMachineModel tempModel = new ObjectMapper().readValue(tempotputDataModelString, JavaSinglesearchVirtualMachineModel.class);
tempotputDataModel.setlinklist(tempModel.getlinklist());
} catch (Exception e)
{
throw new WebApplicationException();
}
}
else
{
try
{
tempotputDataModel = new ObjectMapper().readValue(tempotputDataModelString, JavaAlgosearchVirtualMachineModel.class);
} catch (Exception e)
{
throw new WebApplicationException();
}
}
for (HypermediaLink hl : tempotputDataModel.getlinklist())
{
hyperMediaMap.put(hl.getLinkURI(), hl);
}
}
response.getlinklist().addAll(hyperMediaMap.values());
return response;
}
private List<String> searchVirtualMachinesUnderEnvironments (Client oJAXRSRESTClient)
{
List<String> response = new ArrayList<>();
WebResource oTargetResource = oJAXRSRESTClient.resource("http://localhost:8080/eticsbte/api/AlgosearchVirtualMachine").queryParam("searchVirtualEnvironmentType", "true").queryParam("searchKeyword", ENV_TYPE);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, this.oJavaAlgooptimizeModel);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavaAlgosearchVirtualMachineModel tempotputDataModel = oResponse.getEntity(JavaAlgosearchVirtualMachineModel.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
String url = searchResult.getLinkURI();
url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+url.substring(url.lastIndexOf('/')+1)+"/virtualMachine";
System.out.println("URL "+url);
WebResource getVirtualMachinesResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachinesResponse = getVirtualMachinesResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModelManager getVirtualMachineOutputDataModel = getVirtualMachinesResponse.getEntity(JavavirtualMachineModelManager.class);
for (HypermediaLink hl : getVirtualMachineOutputDataModel.getlinklist())
{
if (hl.getLinkType().equals("Child") && hl.getLinkVerb().equals("GET"))
{
System.out.println("Child VM URI "+hl.getLinkURI());
response.add(hl.getLinkURI());
}
}
}
return response;
}
private VirtualMachineDetails getUrlsVirtualMachine (Client oJAXRSRESTClient,VirtualMachineDetails details)
{
//String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+virtualEnvironmentID+"/virtualMachine/"+virtualMachineID;
WebResource oTargetResource = oJAXRSRESTClient.resource(details.getMainUrl());
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
String virtualEnvironmentUrl = searchResult.getLinkURI();
String idString = virtualEnvironmentUrl.substring(virtualEnvironmentUrl.lastIndexOf('/')+1);
System.out.println("Adding parent id "+idString);
details.getVirtualEnvironmentIds().add(Integer.parseInt(idString));
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("PUT"))
{
details.setUpdateUrl(searchResult.getLinkURI());
}
else if (searchResult.getLinkType().equals("Sibling") && searchResult.getLinkVerb().equals("DELETE"))
{
details.setDeleteUrl(searchResult.getLinkURI());
}
}
return details;
}
private VirtualMachineDetails getVirtualMachineDetails (Client oJAXRSRESTClient, int virtualMachineID)
{
VirtualMachineDetails details = new VirtualMachineDetails();
String url = "http://localhost:8080/eticsbte/api/virtualMachine/"+virtualMachineID+"/software";
WebResource oTargetResource = oJAXRSRESTClient.resource(url);
ClientResponse oResponse = oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (isSuccessfullResponseCode(oResponse) == false) {
throw new WebApplicationException();
}
JavasoftwareModelManager tempotputDataModel = oResponse.getEntity(JavasoftwareModelManager.class);
for (HypermediaLink searchResult : tempotputDataModel.getlinklist())
{
if (searchResult.getLinkType().equals("Child") && searchResult.getLinkVerb().equals("GET"))
{
String softwareUrl = searchResult.getLinkURI();
WebResource getSoftwareDetailsResource = oJAXRSRESTClient.resource(softwareUrl);
ClientResponse getSoftwareDetailsResponse = getSoftwareDetailsResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
JavasoftwareModel getSoftwareDetailsOutputDataModel = getSoftwareDetailsResponse.getEntity(JavasoftwareModel.class);
details.getSoftwareElements().add(getSoftwareDetailsOutputDataModel.getname()+"_"+getSoftwareDetailsOutputDataModel.getversion());
}
else if (searchResult.getLinkType().equals("Parent") && searchResult.getLinkVerb().equals("GET"))
{
details.setMainUrl(searchResult.getLinkURI());
}
}
return getUrlsVirtualMachine(oJAXRSRESTClient, details);
}
private JavavirtualMachineModel updateVirtualMachine (Client oJAXRSRESTClient,String updateUrl,int virtualEnvironmentID,boolean addRelationship)
{
System.out.println("Virtual Environment id "+virtualEnvironmentID);
JavavirtualMachineModel updateVirtualMachine = prepareVMModel ();
WebResource updateVirtualMachineResource = oJAXRSRESTClient.resource(updateUrl).queryParam("strOptionalUpdateRelations", "true").queryParam("strOptionalUpdateParent", "true")
.queryParam("strOptionalRelationName", "virtualEnvironment").queryParam("strOptionalAddRelation", Boolean.toString(addRelationship)).queryParam("iOptionalResourceId", ""+virtualEnvironmentID);
ClientResponse updateVirtualMachineResponse = updateVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).put(ClientResponse.class,updateVirtualMachine);
return parseVMResponse(updateVirtualMachineResponse);
}
private JavavirtualMachineModel createVirtualMachine (Client oJAXRSRESTClient)
{
JavavirtualMachineModel createVirtualMachine = prepareVMModel ();
String url = "http://localhost:8080/eticsbte/api/virtualEnvironment/"+this.oJavaAlgooptimizeModel.getVirtualEnvironmentId()+"/virtualMachine";
ClientResponse oResponse = postRequest(oJAXRSRESTClient, url, createVirtualMachine);
JavavirtualMachineModel tempotputDataModel = oResponse.getEntity(JavavirtualMachineModel.class);
url = url+"/"+ tempotputDataModel.getvirtualMachineId();
WebResource getVirtualMachineResource = oJAXRSRESTClient.resource(url);
ClientResponse getVirtualMachineResponse = getVirtualMachineResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(ClientResponse.class);
return parseVMResponse(getVirtualMachineResponse);
}
private JavavirtualMachineModel prepareVMModel ()
{
JavavirtualMachineModel virtualMachineModel = new JavavirtualMachineModel();
virtualMachineModel.setid(this.oJavaAlgooptimizeModel.getVirtualMachineName());
virtualMachineModel.setcpuPower(this.oJavaAlgooptimizeModel.getCpuPower());
virtualMachineModel.sethdDimension(this.oJavaAlgooptimizeModel.getHdDimension());
return virtualMachineModel;
}
private JavavirtualMachineModel parseVMResponse (ClientResponse getVirtualMachineResponse)
{
if (isSuccessfullResponseCode(getVirtualMachineResponse) == false) {
throw new WebApplicationException();
}
JavavirtualMachineModel getVirtualMachineOutputDataModel = getVirtualMachineResponse.getEntity(JavavirtualMachineModel.class);
return getVirtualMachineOutputDataModel;
}
private JavasoftwareModel createSoftware (Client oJAXRSRESTClient,String createSoftwareUrl)
{
JavasoftwareModel software = new JavasoftwareModel();
software.setname(this.oJavaAlgooptimizeModel.getSoftwareName());
software.setversion(this.oJavaAlgooptimizeModel.getSoftwareVersion());
ClientResponse softwareCreateResponse = postRequest(oJAXRSRESTClient, createSoftwareUrl, software);
JavasoftwareModel softwareotputDataModel = softwareCreateResponse.getEntity(JavasoftwareModel.class);
return softwareotputDataModel;
}
private ClientResponse postRequest (Client oJAXRSRESTClient, String url, Object input)
{
WebResource postOperationResource = oJAXRSRESTClient.resource(url);
ClientResponse postOperationResponse = postOperationResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).post(ClientResponse.class, input);
if (isSuccessfullResponseCode(postOperationResponse) == false) {
throw new WebApplicationException();
}
return postOperationResponse;
}
/*
* This function checks the response code of the server reply against the known success codes. If the server response HTTP
* code is within the success code range, this functions returns true. Otherwise it returns false
*/
private boolean isSuccessfullResponseCode(ClientResponse oResponse){
if(oResponse.getStatus() == 200){ // Status OK
return true;
}
else if(oResponse.getStatus() == 201){ // Status CREATED
return true;
}
else if(oResponse.getStatus() == 202){ // Status Accepted
return true;
}
else if(oResponse.getStatus() == 203){ // Status NON-AUTHORITATIVE INFORMATION
return true;
}
else if(oResponse.getStatus() == 204){ // Status NO CONTENT
return true;
}
else if(oResponse.getStatus() == 205){ // Status RESET CONTENT
return true;
}
else if(oResponse.getStatus() == 206){ // Status PARTIAL CONTENT
return true;
}
return false;
}
}

View File

@ -0,0 +1,53 @@
/*
* ARISTOTLE UNIVERSITY OF THESSALONIKI
* Copyright (C) 2015
* Aristotle University of Thessaloniki
* Department of Electrical & Computer Engineering
* Division of Electronics & Computer Engineering
* Intelligent Systems & Software Engineering Lab
*
* Project : eticsbte
* WorkFile :
* Compiler :
* File Description :
* Document Description:
* Related Documents :
* Note :
* Programmer : RESTful MDE Engine created by Christoforos Zolotas
* Contact : christopherzolotas@issel.ee.auth.gr
*/
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import eu.fp7.scase.eticsbte.utilities.HypermediaLink;
//Please add any needed imports here.
/* JavaAlgosearchVirtualMachineModel class is responsible to model any data the searchVirtualMachine resource handles. Since this one
is not automatable, the developer has to manually define it by providing its properties and setter/getter functions.*/
@XmlRootElement
public class JavaAlgosearchVirtualMachineModel{
/* There follows a list with the properties that model the searchVirtualMachine resource, as prescribed in the service CIM*/
// The Linklist property holds all the hypermedia links to be sent back to the client
@Transient
private List<HypermediaLink> linklist = new ArrayList<HypermediaLink>();
//Please add any properties of this model here.
/* There follows a list of setter and getter functions.*/
public void setlinklist(List<HypermediaLink> linklist){
this.linklist = linklist;
}
public List<HypermediaLink> getlinklist(){
return this.linklist;
}
//Please add the constructors and any functions of this model here.
}

View File

@ -0,0 +1,54 @@
package eu.fp7.scase.eticsbte.operationcommit.service.impl;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import eu.fp7.scase.eticsbte.operationcommit.service.RequestBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ResponseBean;
import eu.fp7.scase.eticsbte.operationcommit.service.ServiceClient;
public class DeleteVirtualHostClient implements ServiceClient {
private String hostId,
username,
password,
url;
@Override
public void setParameters(RequestBean requestBean) {
this.hostId = requestBean.getHostId();
this.username = requestBean.getForemanUserName();
this.password = requestBean.getForemanPassword();
this.url = requestBean.getBaseUrl()+"/DeleteHost/rest/result/query";
}
@Override
public ResponseBean execute(Client oJAXRSRESTClient) {
ResponseBean response = new ResponseBean();
WebResource oTargetResource = oJAXRSRESTClient.resource(this.url).queryParam("username", this.username).queryParam("password", this.password).queryParam("host_id", hostId);
response.setoResponse(oTargetResource.type(javax.ws.rs.core.MediaType.APPLICATION_JSON).accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).delete(ClientResponse.class));
return response;
}
private void mai() {
RequestBean bean = new RequestBean();
bean.setHostId("scasefinalTestVM");
bean.setForemanUserName("admin");
bean.setForemanPassword("temp123!");
DeleteVirtualHostClient client = new DeleteVirtualHostClient();
client.setParameters(bean);
try
{
client.execute(Client.create());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,43 @@
package eu.fp7.scase.eticsbte.optimize;
import java.util.ArrayList;
import java.util.List;
public class VirtualMachineDetails {
private List<Integer> virtualEnvironmentIds;
private List<String> softwareElements;
public VirtualMachineDetails() {
this.virtualEnvironmentIds = new ArrayList<>();
this.softwareElements = new ArrayList<>();
}
public List<Integer> getVirtualEnvironmentIds() {
return virtualEnvironmentIds;
}
public void setVirtualEnvironmentIds(List<Integer> virtualEnvironmentIds) {
this.virtualEnvironmentIds = virtualEnvironmentIds;
}
public List<String> getSoftwareElements() {
return softwareElements;
}
public void setSoftwareElements(List<String> softwareElements) {
this.softwareElements = softwareElements;
}
}

View File

@ -0,0 +1,2 @@
eclipse.preferences.version=1
encoding/<project>=UTF-8

Some files were not shown because too many files have changed in this diff Show More