From 9fe45fd7f0a2a24e385bfcb5e7a2fc7483a8d56e Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 16 Apr 2014 11:50:29 -0300 Subject: [PATCH 001/185] Refactor tests and Implement request state updating --- .../manager/occi/OCCIApplication.java | 38 ++- .../manager/occi/RequestServerResource.java | 6 +- .../manager/occi/core/ResourceRepository.java | 6 +- .../manager/occi/core/ResponseConstants.java | 4 +- .../manager/occi/plugins/ComputePlugin.java | 2 + .../openstack/ComputeOpenStackPlugin.java | 40 ++-- .../occi/request/RequestConstants.java | 2 +- .../manager/occi/request/RequestState.java | 2 +- .../manager/occi/TestGetRequest.java | 8 +- .../manager/occi/TestOCCIApplication.java | 55 +++-- .../occi/model/ComputeApplication.java | 8 +- .../manager/occi/model/RequestHelper.java | 5 +- .../occi/plugins/TestComputeOpenStack.java | 220 +++++++++--------- 13 files changed, 212 insertions(+), 184 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index d78ada2c..a2117e60 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -9,6 +9,7 @@ import org.apache.log4j.Logger; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.plugins.ComputePlugin; @@ -50,11 +51,6 @@ public ComputePlugin getComputePlugin() { return computePlugin; } - // TODO It is really needed? - public Map> getUserToRequestIds() { - return userToRequestIds; - } - public void setIdentityPlugin(IdentityPlugin identityPlugin) { this.identityPlugin = identityPlugin; } @@ -78,28 +74,46 @@ public Request newRequest(String authToken, List categories, if (userToRequestIds.get(user) == null) { userToRequestIds.put(user, new ArrayList()); } + String requestId = String.valueOf(UUID.randomUUID()); Request request = new Request(requestId, "", RequestState.OPEN, categories, xOCCIAtt); userToRequestIds.get(user).add(request.getId()); requestIdToRequest.put(request.getId(), request); - submitRequest(authToken, request, categories, xOCCIAtt); - + try { + submitLocalRequest(authToken, request, categories, xOCCIAtt); + } catch (OCCIException e) { + if (e.getStatus().equals(ErrorType.BAD_REQUEST) + && e.getMessage().equals(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + submitRemoteRequest(authToken, request, categories, xOCCIAtt); + } else { + throw e; + } + } return request; } - // FIXME Should req be an attribute of requestUnit? - private void submitRequest(String authToken, Request request, List categories, + private void submitRemoteRequest(String authToken, Request request, List categories, Map xOCCIAtt) { - // TODO Choose if submit to local or remote cloud and submit + // TODO Auto-generated method stub + + } - // TODO remove fogbow attributes from xOCCIAtt + private void submitLocalRequest(String authToken, Request request, List categories, + Map xOCCIAtt) { + // Removing all xOCCI Attribute specific to request type for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } + String instanceLocation = computePlugin.requestInstance(authToken, categories, xOCCIAtt); + instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); + updateRequestState(request, instanceLocation); + } - computePlugin.requestInstance(authToken, categories, xOCCIAtt); + private void updateRequestState(Request request, String instanceLocation) { + requestIdToRequest.get(request.getId()).setInstanceId(instanceLocation); + requestIdToRequest.get(request.getId()).setState(RequestState.FULFILLED); } public List getRequestsFromUser(String authToken) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java index c5703cc6..7618ed10 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java @@ -80,11 +80,11 @@ public String post() { LOGGER.info("Request " + instanceCount + " instances"); - List currentRequestUnits = new ArrayList(); + List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { - currentRequestUnits.add(application.newRequest(authToken, categories, xOCCIAtt)); + currentRequests.add(application.newRequest(authToken, categories, xOCCIAtt)); } - return HeaderUtils.generateResponseId(currentRequestUnits, req); + return HeaderUtils.generateResponseId(currentRequests, req); } public static Map normalizeXOCCIAtt(Map xOCCIAtt) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java b/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java index 76fa1e75..05d7fe26 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java @@ -30,17 +30,17 @@ public static List getAll() { new ArrayList(), new ArrayList(), FOGBOWCLOUD_ENDPOINT + "/small", "Large Flavor", ""); // image flavors - Resource fogbowUbuntu64Flavor = new Resource(RequestConstants.UBUNTU64_TERM, + Resource fogbowLinuxX86Flavor = new Resource(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS, new ArrayList(), new ArrayList(), FOGBOWCLOUD_ENDPOINT + "/" - + RequestConstants.UBUNTU64_TERM, "Ubuntu64 Image", ""); + + RequestConstants.LINUX_X86_TERM, "Linux-x86 Image", ""); List resources = new ArrayList(); resources.add(fogbowRequest); resources.add(fogbowSmallFlavor); resources.add(fogbowMediumFlavor); resources.add(fogbowLargeFlavor); - resources.add(fogbowUbuntu64Flavor); + resources.add(fogbowLinuxX86Flavor); return resources; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java index 78c8eaca..2283cda3 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java @@ -5,10 +5,10 @@ public class ResponseConstants { public static final String UNAUTHORIZED = "Authentication required."; public static final String NOT_FOUND = "Resource not found."; public static final String IRREGULAR_SYNTAX = "Irregular Syntax."; - public static final String UNSUPPORTED_ATTRIBUTES = - "There are unsupported attributes in the request."; + public static final String UNSUPPORTED_ATTRIBUTES = "There are unsupported attributes in the request."; public static final String OK = "Ok"; public static final String CLOUD_NOT_SUPPORT_CATEGORY = "The cloud does not support category: "; public static final String INVALID_OS_TEMPLATE = "Please provide a valid OS Template."; + public static final String QUOTA_EXCEEDED_FOR_INSTANCES = "Quota exceeded for instances."; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java index eb9b1570..fc63f076 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java @@ -13,4 +13,6 @@ public interface ComputePlugin { public String getInstancesFromUser(String authToken); public ResourcesInfo getResourcesInfo (String authToken); + + public String removeInstance(String authToken, String instanceId); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java index 3da46121..3d135350 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java @@ -34,28 +34,29 @@ public class ComputeOpenStackPlugin implements ComputePlugin { private static final Logger LOGGER = Logger.getLogger(ComputeOpenStackPlugin.class); private final String TERM_COMPUTE = "compute"; - private final String SCHEM_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; + private final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; private final String CLASS_COMPUTE = "kind"; - public static final String FLAVOR_SMALL_TERM = "m1-small"; - public static final String FLAVOR_MEDIUM_TERM = "m1-medium"; - public static final String FLAVOR_LARGE_TERM = "m1-large"; - public static final String IMAGE_UBUNTU_64_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; + public static final String SMALL_FLAVOR_TERM = "m1-small"; + public static final String MEDIUM_FLAVOR_TERM = "m1-medium"; + public static final String LARGE_FLAVOR_TERM = "m1-large"; + public static final String CIRROS_IMAGE_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; - private Map termToOSCategory; + private Map fogTermToOpensStackCategory; public ComputeOpenStackPlugin(String computeEndPoint) { this.computeEndPoint = computeEndPoint; - termToOSCategory = new HashMap(); - - termToOSCategory.put(RequestConstants.SMALL_TERM, new Category(FLAVOR_SMALL_TERM, - "http://schemas.openstack.org/template/resource#", "mixin")); - termToOSCategory.put(RequestConstants.MEDIUM_TERM, new Category(FLAVOR_MEDIUM_TERM, - "http://schemas.openstack.org/template/resource#", "mixin")); - termToOSCategory.put(RequestConstants.LARGE_TERM, new Category(FLAVOR_LARGE_TERM, - "http://schemas.openstack.org/template/resource#", "mixin")); - termToOSCategory.put(RequestConstants.UBUNTU64_TERM, new Category(IMAGE_UBUNTU_64_TERM, - OS_SCHEME, "mixin")); + fogTermToOpensStackCategory = new HashMap(); + + //FIXME this code have to load this configuration from a conf file + fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, new Category(SMALL_FLAVOR_TERM, + "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, new Category(MEDIUM_FLAVOR_TERM, + "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, new Category(LARGE_FLAVOR_TERM, + "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category(CIRROS_IMAGE_TERM, + OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); } @Override @@ -63,15 +64,15 @@ public String requestInstance(String authToken, List categories, Map xOCCIAtt) { List openStackCategories = new ArrayList(); - Category categoryCompute = new Category(TERM_COMPUTE, SCHEM_COMPUTE, CLASS_COMPUTE); + Category categoryCompute = new Category(TERM_COMPUTE, SCHEME_COMPUTE, CLASS_COMPUTE); openStackCategories.add(categoryCompute); for (Category category : categories) { - if (termToOSCategory.get(category.getTerm()) == null) { + if (fogTermToOpensStackCategory.get(category.getTerm()) == null) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.CLOUD_NOT_SUPPORT_CATEGORY + category.getTerm()); } - openStackCategories.add(termToOSCategory.get(category.getTerm())); + openStackCategories.add(fogTermToOpensStackCategory.get(category.getTerm())); } HttpClient httpCLient = new DefaultHttpClient(); @@ -174,6 +175,7 @@ public String removeAllInstances(String authToken) { return null; } + @Override public String removeInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java index 63dc98a3..9916debb 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java @@ -17,7 +17,7 @@ public class RequestConstants { // image flavors public static final String TEMPLATE_OS_SCHEME = "http://schemas.fogbowcloud.org/template/os#"; - public static final String UBUNTU64_TERM = "fogbow-ubuntu64"; + public static final String LINUX_X86_TERM = "fogbow-linux-x86"; // general public static final String MIXIN_CLASS = "mixin"; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java index 0e5badb7..c0d55fb7 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java @@ -2,7 +2,7 @@ public enum RequestState { - OPEN("open"), FAILED("failed"), FULLFIELD("fullfield"), CANCELED("canceled"), CLOSED("closed"); + OPEN("open"), FAILED("failed"), FULFILLED("fulfilled"), CANCELED("canceled"), CLOSED("closed"); private String value; private RequestState(String value) { diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 805af77e..f5993070 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -16,7 +16,9 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.model.ComputeApplication; import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; @@ -32,6 +34,8 @@ public class TestGetRequest { private RequestHelper requestHelper; + private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + RequestHelper.ENDPOINT_PORT + + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; @Before public void setup() throws Exception { @@ -40,7 +44,7 @@ public void setup() throws Exception { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(""); + Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); @@ -190,7 +194,7 @@ public void testGetStatusRequest() throws URISyntaxException, ParseException, IO String requestDetails = EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - Assert.assertEquals(RequestState.OPEN.getValue(), + Assert.assertEquals(RequestState.FULFILLED.getValue(), requestHelper.getStateFromRequestDetails(requestDetails)); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 21680bc5..c626b100 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -6,10 +6,13 @@ import java.util.Map; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.model.ComputeApplication; import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestState; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -18,18 +21,25 @@ public class TestOCCIApplication { private OCCIApplication occiApplication; + private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + + RequestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + private String expectedInstanceId = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "") + .trim(); @Before public void setUp() { this.occiApplication = new OCCIApplication(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(""); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( + RequestHelper.USER_MOCK); occiApplication.setIdentityPlugin(identityPlugin); occiApplication.setComputePlugin(computePlugin); @@ -41,14 +51,15 @@ public void testGetRequestDetails() { new HashMap()); occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), new HashMap()); - Map> userToRequestIds = occiApplication.getUserToRequestIds(); - List list = userToRequestIds.get(RequestHelper.USER_MOCK); - String requestId = list.get(0); + List requests = occiApplication.getRequestsFromUser(RequestHelper.USER_MOCK); + Assert.assertEquals(1, requests.size()); + String requestId = requests.get(0).getId(); Request requestDetails = occiApplication.getRequestDetails(RequestHelper.ACCESS_TOKEN, requestId); - String id = requestDetails.getId(); - Assert.assertEquals(requestId, id); + Assert.assertEquals(requestId, requestDetails.getId()); + Assert.assertEquals(expectedInstanceId, requestDetails.getInstanceId()); + Assert.assertEquals(RequestState.FULFILLED, requestDetails.getState()); } @Test @@ -76,37 +87,37 @@ public void testManyResquestUser() { @Test public void testRemoveAllRequest() { - int valueRequest = 10; - for (int i = 0; i < valueRequest; i++) { - this.occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), + int numberOfRequests = 10; + for (int i = 0; i < numberOfRequests; i++) { + occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), new HashMap()); } - List requestsFromUser = this.occiApplication + List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(valueRequest, requestsFromUser.size()); + Assert.assertEquals(numberOfRequests, requestsFromUser.size()); - this.occiApplication.removeAllRequests(RequestHelper.ACCESS_TOKEN); - requestsFromUser = this.occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + occiApplication.removeAllRequests(RequestHelper.ACCESS_TOKEN); + requestsFromUser = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(0, requestsFromUser.size()); } @Test public void testRemoveSpecificRequest() { - int valueRequest = 10; - for (int i = 0; i < valueRequest; i++) { - this.occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), + int numberOfRequests = 10; + for (int i = 0; i < numberOfRequests; i++) { + occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), new HashMap()); } - List requestsFromUser = this.occiApplication + List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(valueRequest, requestsFromUser.size()); + Assert.assertEquals(numberOfRequests, requestsFromUser.size()); occiApplication.removeRequest(RequestHelper.ACCESS_TOKEN, requestsFromUser.get(1).getId()); - requestsFromUser = this.occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + requestsFromUser = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(valueRequest - 1, requestsFromUser.size()); + Assert.assertEquals(numberOfRequests - 1, requestsFromUser.size()); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java index c7302980..6ff8bbbf 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java @@ -55,23 +55,23 @@ private void normalizeDefaultAttributes() { attributesToValueSmall.put(CORE_ATTRIBUTE_OCCI, "1"); attributesToValueSmall.put(MEMORY_ATTRIBUTE_OCCI, "2"); attributesToValueSmall.put(SPEED_ATTRIBUTE_OCCI, "0"); - this.termToAttributes.put(ComputeOpenStackPlugin.FLAVOR_SMALL_TERM , attributesToValueSmall); + this.termToAttributes.put(ComputeOpenStackPlugin.SMALL_FLAVOR_TERM , attributesToValueSmall); Map attributesToValueMedium = new HashMap(); attributesToValueMedium.put(CORE_ATTRIBUTE_OCCI, "2"); attributesToValueMedium.put(MEMORY_ATTRIBUTE_OCCI, "2520"); attributesToValueMedium.put(SPEED_ATTRIBUTE_OCCI, "0"); - this.termToAttributes.put(ComputeOpenStackPlugin.FLAVOR_MEDIUM_TERM, attributesToValueMedium); + this.termToAttributes.put(ComputeOpenStackPlugin.MEDIUM_FLAVOR_TERM, attributesToValueMedium); Map attributesToValueLarge = new HashMap(); attributesToValueLarge.put(CORE_ATTRIBUTE_OCCI, "3"); attributesToValueLarge.put(MEMORY_ATTRIBUTE_OCCI, "3520"); attributesToValueLarge.put(SPEED_ATTRIBUTE_OCCI, "0"); - this.termToAttributes.put(ComputeOpenStackPlugin.FLAVOR_LARGE_TERM, attributesToValueLarge); + this.termToAttributes.put(ComputeOpenStackPlugin.LARGE_FLAVOR_TERM, attributesToValueLarge); Map attributesToValueUbuntu = new HashMap(); attributesToValueUbuntu.put(ARCHITECTURE_ATTRIBUTE_OCCI, "64"); - this.termToAttributes.put(ComputeOpenStackPlugin.IMAGE_UBUNTU_64_TERM, attributesToValueUbuntu); + this.termToAttributes.put(ComputeOpenStackPlugin.CIRROS_IMAGE_TERM, attributesToValueUbuntu); } @Override diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java index 5df20488..82c10f72 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java @@ -26,12 +26,13 @@ public class RequestHelper { public static final String CONTENT_TYPE_OCCI = "text/occi"; public static final String URI_FOGBOW_REQUEST = "http://localhost:8182/request"; public static final String USER_MOCK = "user_mock"; - private final int PORT_ENDPOINT = 8182; + public static final int ENDPOINT_PORT = 8182; + public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { component = new Component(); - component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); + component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); OCCIApplication application = new OCCIApplication(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 5d51f00f..095662b5 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -21,17 +21,16 @@ public class TestComputeOpenStack { - private final String FIRST_EXPECTED_INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - private final String FIFTH_EXPECTED_INSTANCE_ID = "hla256kh-43ar-67ww-ao90-fa8d456fce9f"; - private final String FOURTH_EXPECTED_INSTANCE_ID = "qwuif8ad-19a3-4afg-1l77-tred90crei0q"; - private final String THIRD_EXPECTED_INSTANCE_ID = "cg2563ee-503c-6abr-54gl-ba8d12hf0pof"; - private final String SECOND_EXPECTED_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; + private final String FIRST_INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + private final String FIFTH_INSTANCE_ID = "hla256kh-43ar-67ww-ao90-fa8d456fce9f"; + private final String FOURTH_INSTANCE_ID = "qwuif8ad-19a3-4afg-1l77-tred90crei0q"; + private final String THIRD_INSTANCE_ID = "cg2563ee-503c-6abr-54gl-ba8d12hf0pof"; + private final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; private final String COMPUTE_END_POINT = "http://localhost:" + PluginHelper.PORT_ENDPOINT + ComputeApplication.TARGET; - private final String PREFIX_RESPONSE_LOCATION = HeaderUtils.X_OCCI_LOCATION - + COMPUTE_END_POINT + "/"; + private final String LOCATION_INSTANCE_PREFIX = HeaderUtils.X_OCCI_LOCATION + COMPUTE_END_POINT + + "/"; - private ComputeOpenStackPlugin computeOpenStack; private PluginHelper pluginHelper; List expectedInstanceIds; @@ -42,11 +41,11 @@ public void setUp() throws Exception { // five first generated instance ids expectedInstanceIds = new ArrayList(); - expectedInstanceIds.add(FIRST_EXPECTED_INSTANCE_ID); - expectedInstanceIds.add(SECOND_EXPECTED_INSTANCE_ID); - expectedInstanceIds.add(THIRD_EXPECTED_INSTANCE_ID); - expectedInstanceIds.add(FOURTH_EXPECTED_INSTANCE_ID); - expectedInstanceIds.add(FIFTH_EXPECTED_INSTANCE_ID); + expectedInstanceIds.add(FIRST_INSTANCE_ID); + expectedInstanceIds.add(SECOND_INSTANCE_ID); + expectedInstanceIds.add(THIRD_INSTANCE_ID); + expectedInstanceIds.add(FOURTH_INSTANCE_ID); + expectedInstanceIds.add(FIFTH_INSTANCE_ID); pluginHelper = new PluginHelper(); pluginHelper.initializeComputeComponent(expectedInstanceIds); @@ -62,23 +61,23 @@ public void testRequestAValidInstance() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + FIRST_EXPECTED_INSTANCE_ID, + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, - FIRST_EXPECTED_INSTANCE_ID); - - Assert.assertEquals(1, - Integer.parseInt(getAttValueFromDetails(instanceDetails, ComputeApplication.CORE_ATTRIBUTE_OCCI))); - Assert.assertEquals(2, - Integer.parseInt(getAttValueFromDetails(instanceDetails, ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); + FIRST_INSTANCE_ID); + + Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instanceDetails, + ComputeApplication.CORE_ATTRIBUTE_OCCI))); + Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instanceDetails, + ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instanceDetails, ComputeApplication.ARCHITECTURE_ATTRIBUTE_OCCI))); - Assert.assertEquals("server-" + FIRST_EXPECTED_INSTANCE_ID, + Assert.assertEquals("server-" + FIRST_INSTANCE_ID, getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } @@ -88,7 +87,7 @@ private String getAttValueFromDetails(String instanceDetails, String attName) { String line = st.nextToken(); if (line.contains(OCCIHeaders.X_OCCI_ATTRIBUTE) && line.contains(attName)) { StringTokenizer st2 = new StringTokenizer(line, "="); - st2.nextToken(); // attName + st2.nextToken(); // attName return st2.nextToken().replaceAll("\"", ""); } } @@ -107,11 +106,12 @@ public void testRequestWithoutOSCateory() { @Test public void testRequestWithoutSizeCateory() { List categories = new ArrayList(); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + FIRST_EXPECTED_INSTANCE_ID, computeOpenStack.requestInstance( - PluginHelper.AUTH_TOKEN, categories, new HashMap())); + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + new HashMap())); } @Test(expected = OCCIException.class) @@ -119,7 +119,7 @@ public void testNotSupportedOCCICoreAtt() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Map xOCCIAtt = new HashMap(); @@ -133,7 +133,7 @@ public void testNotSupportedOCCIMemAtt() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Map xOCCIAtt = new HashMap(); @@ -147,7 +147,7 @@ public void testNotSupportedOCCIArchAtt() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Map xOCCIAtt = new HashMap(); @@ -161,7 +161,7 @@ public void testNotSupportedOCCISpeedAtt() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Map xOCCIAtt = new HashMap(); @@ -175,17 +175,17 @@ public void testSupportedOCCIAtt() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + FIRST_EXPECTED_INSTANCE_ID, + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, - FIRST_EXPECTED_INSTANCE_ID); + FIRST_INSTANCE_ID); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } @@ -195,18 +195,18 @@ public void testMoreSupportedOCCIAtts() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); xOCCIAtt.put("occi.compute.state", "inactive"); - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + FIRST_EXPECTED_INSTANCE_ID, + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, - FIRST_EXPECTED_INSTANCE_ID); + FIRST_INSTANCE_ID); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); Assert.assertEquals("inactive", @@ -215,167 +215,161 @@ public void testMoreSupportedOCCIAtts() { @Test public void testGetAllInstanceIds() { - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + List instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); // requesting one default instance List categories = new ArrayList(); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + FIRST_EXPECTED_INSTANCE_ID, computeOpenStack.requestInstance( - PluginHelper.AUTH_TOKEN, categories, new HashMap())); + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + new HashMap())); // check getting all instance ids - List instanceIds = getInstanceLocations(computeOpenStack + instanceLocations = getInstanceLocations(computeOpenStack .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); - Assert.assertEquals(1, instanceIds.size()); - Assert.assertEquals(COMPUTE_END_POINT + "/" + FIRST_EXPECTED_INSTANCE_ID, instanceIds.get(0)); + Assert.assertEquals(1, instanceLocations.size()); + Assert.assertEquals(COMPUTE_END_POINT + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); } @Test public void testGetAllManyInstanceIds() { - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + List instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); // requesting default instance List categories = new ArrayList(); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + instanceId, computeOpenStack.requestInstance( - PluginHelper.AUTH_TOKEN, categories, new HashMap())); + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + instanceId, computeOpenStack + .requestInstance(PluginHelper.AUTH_TOKEN, categories, + new HashMap())); } // check getting all instance ids - List instanceIds = getInstanceLocations(computeOpenStack + instanceLocations = getInstanceLocations(computeOpenStack .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); - Assert.assertEquals(expectedInstanceIds.size(), instanceIds.size()); - System.out.println(instanceIds); + Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); for (String expectedId : expectedInstanceIds) { - System.out.println(COMPUTE_END_POINT + expectedId); - Assert.assertTrue(instanceIds.contains(COMPUTE_END_POINT + "/" + expectedId)); + Assert.assertTrue(instanceLocations.contains(COMPUTE_END_POINT + "/" + expectedId)); } } private List getInstanceLocations(String instancesFromUser) { - if(instancesFromUser.contains(HeaderUtils.X_OCCI_LOCATION)){ + if (instancesFromUser.contains(HeaderUtils.X_OCCI_LOCATION)) { String[] tokens = instancesFromUser.split("\n"); List locations = new ArrayList(); for (int i = 0; i < tokens.length; i++) { String[] lineTokens = tokens[i].split("Location:"); locations.add(lineTokens[1].trim()); } - return locations; + return locations; } return new ArrayList(); } @Test public void testGetInstanceDetails() { - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + List instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); // requesting one default instance List categories = new ArrayList(); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + FIRST_EXPECTED_INSTANCE_ID, computeOpenStack.requestInstance( - PluginHelper.AUTH_TOKEN, categories, new HashMap())); + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + new HashMap())); // check instance details - Assert.assertEquals( - 1, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(1, instanceLocations.size()); String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, - FIRST_EXPECTED_INSTANCE_ID); - Assert.assertEquals(FIRST_EXPECTED_INSTANCE_ID, + FIRST_INSTANCE_ID); + Assert.assertEquals(FIRST_INSTANCE_ID, getAttValueFromDetails(instanceDetails, ComputeApplication.ID_CORE_ATTRIBUTE_OCCI)); - Assert.assertEquals(1, - Integer.parseInt(getAttValueFromDetails(instanceDetails, ComputeApplication.CORE_ATTRIBUTE_OCCI))); - Assert.assertEquals(2, - Integer.parseInt(getAttValueFromDetails(instanceDetails, ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); + Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instanceDetails, + ComputeApplication.CORE_ATTRIBUTE_OCCI))); + Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instanceDetails, + ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instanceDetails, ComputeApplication.ARCHITECTURE_ATTRIBUTE_OCCI))); - Assert.assertEquals("server-" + FIRST_EXPECTED_INSTANCE_ID, + Assert.assertEquals("server-" + FIRST_INSTANCE_ID, getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } @Test public void testDeleteAllInstancesEmpty() { - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + List instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); + computeOpenStack.removeAllInstances(PluginHelper.AUTH_TOKEN); - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); } @Test public void testDeleteAllManyInstances() { - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + List instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); // requesting default instances List categories = new ArrayList(); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + instanceId, computeOpenStack.requestInstance( - PluginHelper.AUTH_TOKEN, categories, new HashMap())); + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + instanceId, computeOpenStack + .requestInstance(PluginHelper.AUTH_TOKEN, categories, + new HashMap())); } // check number of instances - List instanceIds = getInstanceLocations(computeOpenStack + instanceLocations = getInstanceLocations(computeOpenStack .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); - Assert.assertEquals(expectedInstanceIds.size(), instanceIds.size()); + Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); // removing all instances computeOpenStack.removeAllInstances(PluginHelper.AUTH_TOKEN); - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); } @Test public void testDeleteOneInstance() { - Assert.assertEquals( - 0, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + List instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(0, instanceLocations.size()); // requesting default instances List categories = new ArrayList(); - categories.add(new Category(RequestConstants.UBUNTU64_TERM, + categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(PREFIX_RESPONSE_LOCATION + instanceId, computeOpenStack.requestInstance( - PluginHelper.AUTH_TOKEN, categories, new HashMap())); + Assert.assertEquals(LOCATION_INSTANCE_PREFIX + instanceId, computeOpenStack + .requestInstance(PluginHelper.AUTH_TOKEN, categories, + new HashMap())); } // check number of instances - List instanceIds = getInstanceLocations(computeOpenStack + instanceLocations = getInstanceLocations(computeOpenStack .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); - Assert.assertEquals(expectedInstanceIds.size(), instanceIds.size()); + Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); // removing one instances - computeOpenStack.removeInstance(PluginHelper.AUTH_TOKEN, FIRST_EXPECTED_INSTANCE_ID); - Assert.assertEquals( - expectedInstanceIds.size() - 1, - getInstanceLocations(computeOpenStack.getInstancesFromUser(PluginHelper.AUTH_TOKEN)) - .size()); + computeOpenStack.removeInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); + instanceLocations = getInstanceLocations(computeOpenStack + .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(expectedInstanceIds.size() - 1, instanceLocations.size()); } } From 6e6f4e55b8b87390cd7543affbc2ce145139954e Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 16 Apr 2014 12:39:29 -0300 Subject: [PATCH 002/185] Implementing IdentityOpenStackPLugin and tests --- .../manager/occi/core/OCCIHeaders.java | 3 + .../manager/occi/plugins/IdentityPlugin.java | 2 + .../openstack/IdentityOpenStackPlugin.java | 61 ++++++++++++++-- .../occi/model/KeystoneApplication.java | 72 ++++++++++++++++++- .../manager/occi/model/PluginHelper.java | 5 +- .../occi/plugins/TestIdentityOpenStack.java | 30 ++++++-- 6 files changed, 158 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java index dcdc1eef..6307e82f 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java @@ -16,4 +16,7 @@ public class OCCIHeaders { public static final String SCHEME_CATEGORY = "scheme"; public static final String CLASS_CATEGORY = "class"; public static final String OCCI_CONTENT_TYPE = "text/occi"; + public static final String ACCEPT = "Accept"; + public static final String JSON_CONTENT_TYPE = "application/json"; + public static final String JSON_ACCEPT = "application/json"; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java index 2821752d..e0ff34e9 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java @@ -5,4 +5,6 @@ public interface IdentityPlugin { public boolean isValidToken(String token); public String getUser(String token); + + public String getToken(String username, String password); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java index 5e082eff..8f72ef5f 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java @@ -5,7 +5,10 @@ import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -17,16 +20,18 @@ public class IdentityOpenStackPlugin implements IdentityPlugin { - private String keystoneEndPoint; + private String keystoneEndPointTokens; + private String keystoneEndPointAuthToken; - public IdentityOpenStackPlugin(String endPoint) { - this.keystoneEndPoint = endPoint; + public IdentityOpenStackPlugin(String endPointTokens, String endPointAuthToken) { + this.keystoneEndPointTokens = endPointTokens; + this.keystoneEndPointAuthToken = endPointAuthToken; } public boolean isValidToken(String authToken) { try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.keystoneEndPoint); + HttpGet httpGet = new HttpGet(this.keystoneEndPointTokens); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -45,7 +50,7 @@ public boolean isValidToken(String authToken) { public String getUser(String authToken) { try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.keystoneEndPoint); + HttpGet httpGet = new HttpGet(this.keystoneEndPointTokens); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -64,6 +69,38 @@ public String getUser(String authToken) { } } + @Override + public String getToken(String username, String password) { + try { + HttpClient httpClient = new DefaultHttpClient(); + HttpPost httpPost = new HttpPost(this.keystoneEndPointAuthToken); + + httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); + httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); + + JSONObject rootCredentials = new JSONObject(); + rootCredentials.put("username", username); + rootCredentials.put("password", password); + JSONObject rootAuth = new JSONObject(); + rootAuth.put("passwordCredentials", rootCredentials); + JSONObject rootMain = new JSONObject(); + rootMain.put("auth", rootAuth); + + httpPost.setEntity(new StringEntity(rootMain.toString(), HTTP.UTF_8)); + HttpResponse response = httpClient.execute(httpPost); + String responseStr = EntityUtils.toString(response.getEntity(), + HTTP.UTF_8); + + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } + + return getTokenFromJson(responseStr); + } catch (Exception e) { + throw new OCCIException(ErrorType.BAD_REQUEST, ""); + } + } + private String getUserNameUserFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); @@ -71,6 +108,18 @@ private String getUserNameUserFromJson(String responseStr) { } catch (JSONException e) { return null; } - + } + + private String getTokenFromJson(String responseStr) { + try { + JSONObject root = new JSONObject(responseStr); + return root.getJSONObject("access").getJSONObject("token").getString("id"); + } catch (JSONException e) { + return null; + } + } + + public void setEnd(String end){ + this.keystoneEndPointAuthToken = end; } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java index 30b96d20..5f3e6d64 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.occi.model; +import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -11,25 +12,41 @@ import org.json.JSONObject; import org.restlet.Application; import org.restlet.Restlet; +import org.restlet.data.MediaType; import org.restlet.engine.adapter.HttpRequest; +import org.restlet.representation.Representation; +import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; +import org.restlet.resource.Post; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; public class KeystoneApplication extends Application { + public static String TARGET_TOKENS = "/v3/auth/tokens/"; + public static String TARGET_AUTH_TOKEN = "/v2.0/tokens"; + private Map tokenToUser; - public static String TARGET = "/v3/auth/tokens/"; + private String usernameAdmin; + private String passwordAdmin; + private String defaultToken; public KeystoneApplication() { this.tokenToUser = new HashMap(); } + public KeystoneApplication(String usernameAdmin, String passwordAdmin) { + this.tokenToUser = new HashMap(); + this.usernameAdmin = usernameAdmin; + this.passwordAdmin = passwordAdmin; + } + @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); - router.attach(TARGET, KeystoneServer.class); + router.attach(TARGET_TOKENS, KeystoneServer.class); + router.attach(TARGET_AUTH_TOKEN, KeystoneServer.class); return router; } @@ -39,6 +56,7 @@ public String getUserFromToken(String token){ public void putTokenAndUser(String authToken, String user){ this.tokenToUser.put(authToken, user); + this.defaultToken = authToken; } public void checkUserByToken(String token){ @@ -47,6 +65,16 @@ public void checkUserByToken(String token){ throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } } + + public void authenticationCheck(String username, String password) { + if(!this.usernameAdmin.equals(username) || !this.passwordAdmin.equals(password)){ + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } + } + + public String getDefaultToken(){ + return this.defaultToken; + } public static class KeystoneServer extends ServerResource { @@ -59,7 +87,47 @@ public String fetch() { String user = keyStoneApplication.getUserFromToken(token); return mountJSONObject(token, user); } + + @Post + public Representation post(Representation entity) { + KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); + HttpRequest req = (HttpRequest) getRequest(); + String jsonCredentials = ""; + try { + jsonCredentials = entity.getText(); + } catch (IOException e) {} + + String username = getUserFeatureCredentials(jsonCredentials, "username"); + String password = getUserFeatureCredentials(jsonCredentials, "password"); + keyStoneApplication.authenticationCheck(username, password); + + return new StringRepresentation(mountJSONResponseAuthenticateToken(keyStoneApplication.getDefaultToken()), MediaType.TEXT_ALL); + } + private String mountJSONResponseAuthenticateToken(String token){ + try { + JSONObject rootIdTOken = new JSONObject(); + rootIdTOken.put("id", token); + JSONObject rootToken = new JSONObject(); + rootToken.put("token", rootIdTOken); + JSONObject rootAccess = new JSONObject(); + rootAccess.put("access", rootToken); + return rootAccess.toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + return null; + } + + private String getUserFeatureCredentials(String jsonCredentials, String feature){ + try { + JSONObject root = new JSONObject(jsonCredentials); + return root.getJSONObject("auth").getJSONObject("passwordCredentials").getString(feature).toString(); + } catch (JSONException e) { + return null; + } + } + private String mountJSONObject(String token, String user) { try { JSONObject nameObject = new JSONObject(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java index 3a0f8996..950e3dfa 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java @@ -13,6 +13,7 @@ public class PluginHelper { public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; public static final String USERNAME = "admin"; + public static final String PASSWORD = "reverse"; public static final int PORT_ENDPOINT = 8182; @@ -24,9 +25,9 @@ public void initializeKeystoneComponent() throws Exception { this.component = new Component(); this.component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); - KeystoneApplication keystoneApplication = new KeystoneApplication(); + KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME, PASSWORD); keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME); - + this.component.getDefaultHost().attach(keystoneApplication); this.component.start(); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index dbf62619..ad6ad555 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -11,15 +11,18 @@ public class TestIdentityOpenStack { + private final String KEYSTONE_END_POINT_TOKENS = "http://localhost:" + + PluginHelper.PORT_ENDPOINT + KeystoneApplication.TARGET_TOKENS; + private final String KEYSTONE_END_POINT_AUTH_TOKEN = "http://localhost:" + + PluginHelper.PORT_ENDPOINT + KeystoneApplication.TARGET_AUTH_TOKEN; + private IdentityOpenStackPlugin identityOpenStack; private PluginHelper pluginHelper; - private final String KEYSTONE_END_POINT = "http://localhost:" + PluginHelper.PORT_ENDPOINT - + KeystoneApplication.TARGET; - @Before public void setUp() throws Exception { - this.identityOpenStack = new IdentityOpenStackPlugin(KEYSTONE_END_POINT); + this.identityOpenStack = new IdentityOpenStackPlugin(KEYSTONE_END_POINT_TOKENS, + KEYSTONE_END_POINT_AUTH_TOKEN); this.pluginHelper = new PluginHelper(); this.pluginHelper.initializeKeystoneComponent(); } @@ -49,4 +52,21 @@ public void testGetNameUserFromToken() { public void testGetNameUserFromTokenInvalid() { this.identityOpenStack.getUser("invalid_token"); } -} + + @Test + public void testGetToken() { + String token = this.identityOpenStack + .getToken(PluginHelper.USERNAME, PluginHelper.PASSWORD); + Assert.assertEquals(PluginHelper.AUTH_TOKEN, token); + } + + @Test(expected = OCCIException.class) + public void testGetTokenWrongUsername() { + this.identityOpenStack.getToken("wrong", PluginHelper.USERNAME); + } + + @Test(expected = OCCIException.class) + public void testGetTokenWrongPassword() { + this.identityOpenStack.getToken(PluginHelper.PASSWORD, "wrong"); + } +} \ No newline at end of file From 4ed45db4220358cfed3a90ae848a192863a81faf Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 16 Apr 2014 14:35:34 -0300 Subject: [PATCH 003/185] Refatoring IdentityOPenstack --- .../openstack/IdentityOpenStackPlugin.java | 57 ++++++---- .../occi/model/KeystoneApplication.java | 103 ++++++++++-------- .../manager/occi/model/PluginHelper.java | 13 ++- .../occi/plugins/TestIdentityOpenStack.java | 16 +-- 4 files changed, 103 insertions(+), 86 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java index 8f72ef5f..0e237799 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java @@ -10,16 +10,24 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; -import org.fogbowcloud.manager.occi.core.ErrorType; -import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.json.JSONException; import org.json.JSONObject; +import org.restlet.resource.ResourceException; public class IdentityOpenStackPlugin implements IdentityPlugin { + public static final String USERNAME_KEYSTONE = "username"; + public static final String PASSWORD_KEYSTONE = "password"; + public static final String PASSWORD_CREDENTIALS_KEYSTONE = "passwordCredentials"; + public static final String AUTH_KEYSTONE = "auth"; + public static final String TOKEN_KEYSTONE = "token"; + public static final String ID_KEYSTONE = "id"; + public static final String ACCESS_KEYSTONE = "Access"; + public static final String USER_KEYSTONE = "user"; + public static final String NAME_KEYSTONE = "name"; + private String keystoneEndPointTokens; private String keystoneEndPointAuthToken; @@ -58,14 +66,14 @@ public String getUser(String authToken) { String.valueOf(Charsets.UTF_8)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + throw new ResourceException(HttpStatus.SC_NOT_FOUND); } return getUserNameUserFromJson(responseStr); } catch (Exception e) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + throw new ResourceException(HttpStatus.SC_BAD_REQUEST); } } @@ -74,52 +82,53 @@ public String getToken(String username, String password) { try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(this.keystoneEndPointAuthToken); - + httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); - + JSONObject rootCredentials = new JSONObject(); - rootCredentials.put("username", username); - rootCredentials.put("password", password); + rootCredentials.put(USERNAME_KEYSTONE, username); + rootCredentials.put(PASSWORD_KEYSTONE, password); JSONObject rootAuth = new JSONObject(); - rootAuth.put("passwordCredentials", rootCredentials); + rootAuth.put(PASSWORD_CREDENTIALS_KEYSTONE, rootCredentials); JSONObject rootMain = new JSONObject(); - rootMain.put("auth", rootAuth); - + rootMain.put(AUTH_KEYSTONE, rootAuth); httpPost.setEntity(new StringEntity(rootMain.toString(), HTTP.UTF_8)); + HttpResponse response = httpClient.execute(httpPost); - String responseStr = EntityUtils.toString(response.getEntity(), - HTTP.UTF_8); + String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); + } return getTokenFromJson(responseStr); } catch (Exception e) { - throw new OCCIException(ErrorType.BAD_REQUEST, ""); + throw new ResourceException(HttpStatus.SC_BAD_REQUEST); } } - + private String getUserNameUserFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - return root.getJSONObject("token").getJSONObject("user").getString("name"); + return root.getJSONObject(TOKEN_KEYSTONE) + .getJSONObject(USER_KEYSTONE).getString(NAME_KEYSTONE); } catch (JSONException e) { return null; } } - + private String getTokenFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - return root.getJSONObject("access").getJSONObject("token").getString("id"); + return root.getJSONObject(ACCESS_KEYSTONE) + .getJSONObject(TOKEN_KEYSTONE).getString(ID_KEYSTONE); } catch (JSONException e) { return null; } } - - public void setEnd(String end){ + + public void setEnd(String end) { this.keystoneEndPointAuthToken = end; } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java index 5f3e6d64..9b3f4f10 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java @@ -4,10 +4,9 @@ import java.util.HashMap; import java.util.Map; -import org.fogbowcloud.manager.occi.core.ErrorType; -import org.fogbowcloud.manager.occi.core.OCCIException; +import org.apache.http.HttpStatus; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Application; @@ -18,6 +17,7 @@ import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.Post; +import org.restlet.resource.ResourceException; import org.restlet.resource.ServerResource; import org.restlet.routing.Router; @@ -26,22 +26,23 @@ public class KeystoneApplication extends Application { public static String TARGET_TOKENS = "/v3/auth/tokens/"; public static String TARGET_AUTH_TOKEN = "/v2.0/tokens"; - private Map tokenToUser; - + private Map tokenToUser; + private String usernameAdmin; private String passwordAdmin; private String defaultToken; - + public KeystoneApplication() { this.tokenToUser = new HashMap(); } - - public KeystoneApplication(String usernameAdmin, String passwordAdmin) { + + public KeystoneApplication(String usernameAdmin, String passwordAdmin, String defaultToken) { this.tokenToUser = new HashMap(); this.usernameAdmin = usernameAdmin; this.passwordAdmin = passwordAdmin; + this.defaultToken = defaultToken; } - + @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); @@ -49,30 +50,29 @@ public Restlet createInboundRoot() { router.attach(TARGET_AUTH_TOKEN, KeystoneServer.class); return router; } - - public String getUserFromToken(String token){ + + public String getUserFromToken(String token) { return this.tokenToUser.get(token); } - - public void putTokenAndUser(String authToken, String user){ + + public void putTokenAndUser(String authToken, String user) { this.tokenToUser.put(authToken, user); - this.defaultToken = authToken; } - - public void checkUserByToken(String token){ + + public void checkUserByToken(String token) { String user = this.tokenToUser.get(token); - if(user == null || user.equals("")){ - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + if (user == null || user.equals("")) { + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } - + public void authenticationCheck(String username, String password) { - if(!this.usernameAdmin.equals(username) || !this.passwordAdmin.equals(password)){ - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + if (!this.usernameAdmin.equals(username) || !this.passwordAdmin.equals(password)) { + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } - - public String getDefaultToken(){ + + public String getDefaultToken() { return this.defaultToken; } @@ -85,57 +85,64 @@ public String fetch() { String token = req.getHeaders().getValues(OCCIHeaders.X_AUTH_TOKEN); keyStoneApplication.checkUserByToken(token); String user = keyStoneApplication.getUserFromToken(token); - return mountJSONObject(token, user); + return mountJSONResponseUserPerToken(token, user); } - + @Post public Representation post(Representation entity) { KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); - HttpRequest req = (HttpRequest) getRequest(); + String jsonCredentials = ""; try { - jsonCredentials = entity.getText(); - } catch (IOException e) {} - - String username = getUserFeatureCredentials(jsonCredentials, "username"); - String password = getUserFeatureCredentials(jsonCredentials, "password"); + jsonCredentials = entity.getText(); + } catch (IOException e) { + } + + String username = getUserFeatureCredentials(jsonCredentials, + IdentityOpenStackPlugin.USERNAME_KEYSTONE); + String password = getUserFeatureCredentials(jsonCredentials, + IdentityOpenStackPlugin.PASSWORD_KEYSTONE); keyStoneApplication.authenticationCheck(username, password); - - return new StringRepresentation(mountJSONResponseAuthenticateToken(keyStoneApplication.getDefaultToken()), MediaType.TEXT_ALL); + + return new StringRepresentation( + mountJSONResponseAuthenticateToken(keyStoneApplication.getDefaultToken()), + MediaType.TEXT_ALL); } - - private String mountJSONResponseAuthenticateToken(String token){ + + private String mountJSONResponseAuthenticateToken(String token) { try { JSONObject rootIdTOken = new JSONObject(); - rootIdTOken.put("id", token); + rootIdTOken.put(IdentityOpenStackPlugin.ID_KEYSTONE, token); JSONObject rootToken = new JSONObject(); - rootToken.put("token", rootIdTOken); + rootToken.put(IdentityOpenStackPlugin.TOKEN_KEYSTONE, rootIdTOken); JSONObject rootAccess = new JSONObject(); - rootAccess.put("access", rootToken); + rootAccess.put(IdentityOpenStackPlugin.ACCESS_KEYSTONE, rootToken); return rootAccess.toString(); } catch (JSONException e) { e.printStackTrace(); - } + } return null; } - - private String getUserFeatureCredentials(String jsonCredentials, String feature){ + + private String getUserFeatureCredentials(String jsonCredentials, String feature) { try { JSONObject root = new JSONObject(jsonCredentials); - return root.getJSONObject("auth").getJSONObject("passwordCredentials").getString(feature).toString(); + return root.getJSONObject(IdentityOpenStackPlugin.AUTH_KEYSTONE) + .getJSONObject(IdentityOpenStackPlugin.PASSWORD_CREDENTIALS_KEYSTONE) + .getString(feature).toString(); } catch (JSONException e) { return null; } } - - private String mountJSONObject(String token, String user) { + + private String mountJSONResponseUserPerToken(String token, String user) { try { JSONObject nameObject = new JSONObject(); - nameObject.put("name", user); - JSONObject tokenObject = new JSONObject(); - tokenObject.put("user", nameObject); + nameObject.put(IdentityOpenStackPlugin.NAME_KEYSTONE, user); + JSONObject tokenObject = new JSONObject(); + tokenObject.put(IdentityOpenStackPlugin.USER_KEYSTONE, nameObject); JSONObject accessObject = new JSONObject(); - accessObject.put("token", tokenObject); + accessObject.put(IdentityOpenStackPlugin.TOKEN_KEYSTONE, tokenObject); return accessObject.toString(); } catch (JSONException e) { } diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java index 950e3dfa..098b574c 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java @@ -12,8 +12,8 @@ public class PluginHelper { private Component component; public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; - public static final String USERNAME = "admin"; - public static final String PASSWORD = "reverse"; + public static final String USERNAME_FOGBOW = "admin"; + public static final String PASSWORD_FOGBOW = "reverse"; public static final int PORT_ENDPOINT = 8182; @@ -25,9 +25,10 @@ public void initializeKeystoneComponent() throws Exception { this.component = new Component(); this.component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); - KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME, PASSWORD); - keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME); - + KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW, + AUTH_TOKEN); + keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); + this.component.getDefaultHost().attach(keystoneApplication); this.component.start(); } @@ -44,7 +45,7 @@ public void initializeComputeComponent(List expectedInstanceIds) throws expectedInstanceIds.get(1), expectedInstanceIds.get(2), expectedInstanceIds.get(3), expectedInstanceIds.get(4)); computeApplication.setIdGenerator(idGenerator); - computeApplication.putTokenAndUser(AUTH_TOKEN, USERNAME); + computeApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); this.component.getDefaultHost().attach(computeApplication); this.component.start(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index ad6ad555..86a885dd 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -1,6 +1,5 @@ package org.fogbowcloud.manager.occi.plugins; -import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.model.KeystoneApplication; import org.fogbowcloud.manager.occi.model.PluginHelper; import org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin; @@ -8,6 +7,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.restlet.resource.ResourceException; public class TestIdentityOpenStack { @@ -44,11 +44,11 @@ public void testInvalidToken() { @Test public void testGetNameUserFromToken() { - Assert.assertEquals(PluginHelper.USERNAME, + Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, this.identityOpenStack.getUser(PluginHelper.AUTH_TOKEN)); } - @Test(expected = OCCIException.class) + @Test(expected = ResourceException.class) public void testGetNameUserFromTokenInvalid() { this.identityOpenStack.getUser("invalid_token"); } @@ -56,17 +56,17 @@ public void testGetNameUserFromTokenInvalid() { @Test public void testGetToken() { String token = this.identityOpenStack - .getToken(PluginHelper.USERNAME, PluginHelper.PASSWORD); + .getToken(PluginHelper.USERNAME_FOGBOW, PluginHelper.PASSWORD_FOGBOW); Assert.assertEquals(PluginHelper.AUTH_TOKEN, token); } - @Test(expected = OCCIException.class) + @Test(expected = ResourceException.class) public void testGetTokenWrongUsername() { - this.identityOpenStack.getToken("wrong", PluginHelper.USERNAME); + this.identityOpenStack.getToken("wrong", PluginHelper.USERNAME_FOGBOW); } - @Test(expected = OCCIException.class) + @Test(expected = ResourceException.class) public void testGetTokenWrongPassword() { - this.identityOpenStack.getToken(PluginHelper.PASSWORD, "wrong"); + this.identityOpenStack.getToken(PluginHelper.PASSWORD_FOGBOW, "wrong"); } } \ No newline at end of file From 952720f71ad29a9049a4267dc679a1811701f22d Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 16 Apr 2014 17:31:16 -0300 Subject: [PATCH 004/185] Implementing ComputeServerResource and tests --- .../manager/occi/ComputeServerResource.java | 50 ++++++ .../openstack/ComputeOpenStackPlugin.java | 21 +-- .../manager/occi/TestDeleteCompute.java | 63 ++++++++ .../manager/occi/TestGetCompute.java | 149 ++++++++++++++++++ .../manager/occi/model/RequestHelper.java | 2 +- 5 files changed, 275 insertions(+), 10 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java create mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java create mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java diff --git a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java new file mode 100644 index 00000000..2763bc1d --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java @@ -0,0 +1,50 @@ +package org.fogbowcloud.manager.occi; + +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.restlet.engine.adapter.HttpRequest; +import org.restlet.resource.Delete; +import org.restlet.resource.Get; +import org.restlet.resource.Post; +import org.restlet.resource.ServerResource; + +public class ComputeServerResource extends ServerResource{ + + @Get + public String fetch() { + OCCIApplication application = (OCCIApplication) getApplication(); + HttpRequest req = (HttpRequest) getRequest(); + String userToken = HeaderUtils.getAuthToken(req.getHeaders()); + String idVM = (String) getRequestAttributes().get("vmid"); + + if (idVM == null) { + //TODO implemet +// return application.getAllInstacesVM; + } + //TODO implemet +// return application.getSpecificInstanceVm(idVM); + + return null; + } + + @Delete + public String remove() { + OCCIApplication application = (OCCIApplication) getApplication(); + HttpRequest req = (HttpRequest) getRequest(); + String userToken = HeaderUtils.getAuthToken(req.getHeaders()); + String idVM = (String) getRequestAttributes().get("vmid"); + + if (idVM == null) { + //TODO implemet +// return application.removeAllInstacesVM; + } + //TODO implemet +// return application.removeSpecificInstanceVm(idVM); + + return null; + } + + @Post + public String post() { + return null; + } +} diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java index 3d135350..3a765357 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java @@ -48,15 +48,18 @@ public ComputeOpenStackPlugin(String computeEndPoint) { this.computeEndPoint = computeEndPoint; fogTermToOpensStackCategory = new HashMap(); - //FIXME this code have to load this configuration from a conf file - fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, new Category(SMALL_FLAVOR_TERM, - "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS)); - fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, new Category(MEDIUM_FLAVOR_TERM, - "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS)); - fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, new Category(LARGE_FLAVOR_TERM, - "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS)); - fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category(CIRROS_IMAGE_TERM, - OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); + // FIXME this code have to load this configuration from a conf file + fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, new Category( + SMALL_FLAVOR_TERM, "http://schemas.openstack.org/template/resource#", + OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, new Category( + MEDIUM_FLAVOR_TERM, "http://schemas.openstack.org/template/resource#", + OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, new Category( + LARGE_FLAVOR_TERM, "http://schemas.openstack.org/template/resource#", + OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category( + CIRROS_IMAGE_TERM, OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); } @Override diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java new file mode 100644 index 00000000..f63c76c4 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -0,0 +1,63 @@ +package org.fogbowcloud.manager.occi; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.model.RequestHelper; +import org.fogbowcloud.manager.occi.plugins.ComputePlugin; +import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestDeleteCompute { + + //TODO rename + RequestHelper requestHelper; + + @Before + public void setup() throws Exception { + this.requestHelper = new RequestHelper(); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); + Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + + this.requestHelper.initializeComponent(computePlugin, identityPlugin); + } + + @After + public void tearDown() throws Exception{ + this.requestHelper.stopComponent(); + } + + + @Ignore + @Test(expected = OCCIException.class) + public void TestWrongAccessToken() throws Exception{ + HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpDelete); + } + + @Ignore + @Test(expected = OCCIException.class) + public void TestInvalidVM() throws Exception{ + HttpDelete get = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); + get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + } + + +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java new file mode 100644 index 00000000..4751f3f4 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -0,0 +1,149 @@ +package org.fogbowcloud.manager.occi; + +import java.util.List; + +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.model.RequestHelper; +import org.fogbowcloud.manager.occi.plugins.ComputePlugin; +import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.request.RequestAttribute; +import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestGetCompute { + + //TODO rename + RequestHelper requestHelper; + + @Before + public void setup() throws Exception { + this.requestHelper = new RequestHelper(); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); + Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + + this.requestHelper.initializeComponent(computePlugin, identityPlugin); + } + + @After + public void tearDown() throws Exception{ + this.requestHelper.stopComponent(); + } + + @Ignore + @Test + public void TestGetComputeEmpty() throws Exception{ + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Ignore + @Test + public void TestGetComputeOneVM() throws Exception{ + //Post /request + HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + Category category = new Category(RequestConstants.TERM, + RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); + httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpPost); + List requestIDs = RequestHelper.getRequestLocations(response); + + Assert.assertEquals(1, requestIDs.size()); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + + //Get /compute/ + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + client = new DefaultHttpClient(); + response = client.execute(httpGet); + + Assert.assertEquals(1, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Ignore + @Test + public void TestGetComputeManyVMs() throws Exception{ + //Post /request + HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + Category category = new Category(RequestConstants.TERM, + RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); + httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); + httpPost.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, + RequestAttribute.INSTANCE_COUNT.getValue() + " = 3"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpPost); + List requestIDs = RequestHelper.getRequestLocations(response); + + Assert.assertEquals(3, requestIDs.size()); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + + //Get /compute/ + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + client = new DefaultHttpClient(); + response = client.execute(httpGet); + + Assert.assertEquals(3, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Ignore + @Test(expected = OCCIException.class) + public void TestWrongContentType() throws Exception{ + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + } + + @Ignore + @Test(expected = OCCIException.class) + public void TestWrongAccessToken() throws Exception{ + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + } + + @Ignore + @Test(expected = OCCIException.class) + public void TestInvalidVM() throws Exception{ + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java index 82c10f72..c626656a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java @@ -25,6 +25,7 @@ public class RequestHelper { public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; public static final String CONTENT_TYPE_OCCI = "text/occi"; public static final String URI_FOGBOW_REQUEST = "http://localhost:8182/request"; + public static final String URI_FOGBOW_COMPUTE = "http://localhost:8182/compute/"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; @@ -35,7 +36,6 @@ public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin iden component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); OCCIApplication application = new OCCIApplication(); - application.setComputePlugin(computePlugin); application.setIdentityPlugin(identityPlugin); From 709f715baff814cac2ed41f1699572eee9fe1b1c Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 16 Apr 2014 17:32:35 -0300 Subject: [PATCH 005/185] Implement request state submitting and updating --- .../manager/occi/OCCIApplication.java | 111 +++++++++++++----- .../manager/occi/RequestServerResource.java | 10 +- .../manager/occi/request/Request.java | 14 ++- .../manager/occi/request/RequestState.java | 20 +++- .../manager/occi/request/RequestsBox.java | 67 +++++++++++ .../manager/occi/TestOCCIApplication.java | 79 ++++++++----- 6 files changed, 231 insertions(+), 70 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index a2117e60..18896c12 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -1,8 +1,12 @@ package org.fogbowcloud.manager.occi; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; +import java.util.Timer; +import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -17,6 +21,7 @@ import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestState; +import org.fogbowcloud.manager.occi.request.RequestsBox; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; @@ -25,14 +30,62 @@ public class OCCIApplication extends Application { private IdentityPlugin identityPlugin; private ComputePlugin computePlugin; - private Map> userToRequestIds; + private Map userToRequestIds; private Map requestIdToRequest; + private final Timer timer = new Timer(); + protected static final long PERIOD = 50; private static final Logger LOGGER = Logger.getLogger(OCCIApplication.class); public OCCIApplication() { - this.userToRequestIds = new ConcurrentHashMap>(); + this.userToRequestIds = new ConcurrentHashMap(); this.requestIdToRequest = new ConcurrentHashMap(); + submitRequests(); + } + + private void submitRequests() { + timer.schedule(new TimerTask() { + @Override + public void run() { + checkAndSubmitOpenRequests(); + } + }, 0, PERIOD); + } + + private void checkAndSubmitOpenRequests() { + Iterator> iter = userToRequestIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + String user = entry.getKey(); + RequestsBox requestBoxes = entry.getValue(); + List openIds = new ArrayList(); + openIds.addAll(requestBoxes.getOpenIds()); + + for (String requestId : openIds) { + Request request = requestIdToRequest.get(requestId); + // TODO before submit request we have to check + try { + submitLocalRequest(request); + userToRequestIds.get(user).openToFulfilled(request.getId()); + } catch (OCCIException e) { + if (e.getStatus().equals(ErrorType.BAD_REQUEST) + && e.getMessage().contains( + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + submitRemoteRequest(request); // FIXME submit more than + // one at same time + } else { + // TODO set state to fail? + updateStateToFailed(user, request); + throw e; + } + } + } + } + } + + private void updateStateToFailed(String user, Request request) { + userToRequestIds.get(user).openToFailed(request.getId()); + requestIdToRequest.get(request.getId()).setState(RequestState.FAILED); } @Override @@ -65,55 +118,53 @@ public Request getRequestDetails(String authToken, String requestId) { return requestIdToRequest.get(requestId); } - public Request newRequest(String authToken, List categories, + public List newRequests(String authToken, List categories, Map xOCCIAtt) { checkUserToken(authToken); String user = getIdentityPlugin().getUser(authToken); if (userToRequestIds.get(user) == null) { - userToRequestIds.put(user, new ArrayList()); + userToRequestIds.put(user, new RequestsBox()); } - String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, "", RequestState.OPEN, categories, xOCCIAtt); + Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT + .getValue())); + LOGGER.info("Request " + instanceCount + " instances"); - userToRequestIds.get(user).add(request.getId()); - requestIdToRequest.put(request.getId(), request); + List currentRequests = new ArrayList(); + for (int i = 0; i < instanceCount; i++) { + String requestId = String.valueOf(UUID.randomUUID()); + Request request = new Request(requestId, authToken, "", RequestState.OPEN, categories, + xOCCIAtt); + currentRequests.add(request); - try { - submitLocalRequest(authToken, request, categories, xOCCIAtt); - } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.BAD_REQUEST) - && e.getMessage().equals(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { - submitRemoteRequest(authToken, request, categories, xOCCIAtt); - } else { - throw e; - } + userToRequestIds.get(user).addOpen(request.getId()); + requestIdToRequest.put(request.getId(), request); } - return request; + return currentRequests; } - private void submitRemoteRequest(String authToken, Request request, List categories, - Map xOCCIAtt) { + private void submitRemoteRequest(Request request) { // TODO Auto-generated method stub - + } - private void submitLocalRequest(String authToken, Request request, List categories, - Map xOCCIAtt) { + private void submitLocalRequest(Request request) { // Removing all xOCCI Attribute specific to request type + Map xOCCIAtt = request.getxOCCIAtt(); for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } - String instanceLocation = computePlugin.requestInstance(authToken, categories, xOCCIAtt); + String instanceLocation = computePlugin.requestInstance(request.getAuthToken(), + request.getCategories(), xOCCIAtt); instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); - updateRequestState(request, instanceLocation); + updateStateToFulfilled(request.getId(), instanceLocation); } - private void updateRequestState(Request request, String instanceLocation) { - requestIdToRequest.get(request.getId()).setInstanceId(instanceLocation); - requestIdToRequest.get(request.getId()).setState(RequestState.FULFILLED); + private void updateStateToFulfilled(String requestId, String instanceLocation) { + requestIdToRequest.get(requestId).setInstanceId(instanceLocation); + requestIdToRequest.get(requestId).setState(RequestState.FULFILLED); } public List getRequestsFromUser(String authToken) { @@ -122,7 +173,7 @@ public List getRequestsFromUser(String authToken) { List requests = new ArrayList(); if (userToRequestIds.get(user) != null) { - for (String requestId : userToRequestIds.get(user)) { + for (String requestId : userToRequestIds.get(user).getAllRequestIds()) { requests.add(requestIdToRequest.get(requestId)); } } @@ -134,7 +185,7 @@ public void removeAllRequests(String authToken) { String user = getIdentityPlugin().getUser(authToken); if (userToRequestIds.get(user) != null) { - for (String requestId : userToRequestIds.get(user)) { + for (String requestId : userToRequestIds.get(user).getAllRequestIds()) { requestIdToRequest.remove(requestId); } userToRequestIds.remove(user); diff --git a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java index 7618ed10..012692ad 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java @@ -1,6 +1,5 @@ package org.fogbowcloud.manager.occi; -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -75,15 +74,8 @@ public String post() { xOCCIAtt = normalizeXOCCIAtt(xOCCIAtt); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); - Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT - .getValue())); - LOGGER.info("Request " + instanceCount + " instances"); - - List currentRequests = new ArrayList(); - for (int i = 0; i < instanceCount; i++) { - currentRequests.add(application.newRequest(authToken, categories, xOCCIAtt)); - } + List currentRequests = application.newRequests(authToken, categories, xOCCIAtt); return HeaderUtils.generateResponseId(currentRequests, req); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index bc90aa6a..068e65f9 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -8,14 +8,16 @@ public class Request { private String id; + private String authToken; private String instanceId; private RequestState state; private List categories; private Map xOCCIAtt; - public Request(String id, String instanceId, RequestState state, + public Request(String id, String authToken, String instanceId, RequestState state, List categories, Map xOCCIAtt) { this.id = id; + this.authToken = authToken; setInstanceId(instanceId); setState(state); this.categories = categories; @@ -53,4 +55,14 @@ public String getAttValue(String attributeName){ public String toHttpMessageFormat() { return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; } + + + public String getAuthToken() { + return this.authToken; + } + + + public Map getxOCCIAtt() { + return this.xOCCIAtt; + } } \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java index c0d55fb7..2c4d83bb 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java @@ -1,14 +1,30 @@ package org.fogbowcloud.manager.occi.request; public enum RequestState { - + + /** + * Open: The request is not fulfilled. + * + * Failed: The request failed because bad parameters were specified. + * + * Fulfilled: The request is currently active (fulfilled) and has an + * associated Instance. + * + * Canceled: The request is canceled because the request went past its + * expiration date. + * + * Closed: The request either completed (a Instance was launched and + * subsequently was interrupted or terminated), or was not fulfilled within + * the period specified. + */ OPEN("open"), FAILED("failed"), FULFILLED("fulfilled"), CANCELED("canceled"), CLOSED("closed"); private String value; + private RequestState(String value) { this.value = value; } - + public String getValue() { return this.value; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java new file mode 100644 index 00000000..3faaf2be --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java @@ -0,0 +1,67 @@ +package org.fogbowcloud.manager.occi.request; + +import java.util.ArrayList; +import java.util.List; + +public class RequestsBox { + + private List open; + private List fulfilled; + private List failed; + private List canceled; + private List closed; + + public RequestsBox() { + // TODO concurrency problems? + open = new ArrayList(); + fulfilled = new ArrayList(); + failed = new ArrayList(); + canceled = new ArrayList(); + closed = new ArrayList(); + } + + public void addOpen(String requestId) { + open.add(requestId); + } + + public List getAllRequestIds() { + List allRequestIds = new ArrayList(); + allRequestIds.addAll(open); + allRequestIds.addAll(fulfilled); + allRequestIds.addAll(failed); + allRequestIds.addAll(canceled); + allRequestIds.addAll(closed); + return allRequestIds; + } + + public void remove(String requestId) { + open.remove(requestId); + fulfilled.remove(requestId); + failed.remove(requestId); + canceled.remove(requestId); + closed.remove(requestId); + } + + public boolean contains(String requestId) { + if (open.contains(requestId) || fulfilled.contains(requestId) + || fulfilled.contains(requestId) || failed.contains(requestId) + || canceled.contains(requestId) || closed.contains(requestId)) { + return true; + } + return false; + } + + public void openToFulfilled(String requestId) { + open.remove(requestId); + fulfilled.add(requestId); + } + + public List getOpenIds() { + return open; + } + + public void openToFailed(String requestId) { + open.remove(requestId); + failed.add(requestId); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index c626b100..70c67868 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -12,6 +12,8 @@ import org.fogbowcloud.manager.occi.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestAttribute; +import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.junit.Assert; import org.junit.Before; @@ -27,9 +29,16 @@ public class TestOCCIApplication { private String expectedInstanceId = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "") .trim(); + private Map xOCCIAtt; + @Before public void setUp() { - this.occiApplication = new OCCIApplication(); + occiApplication = new OCCIApplication(); + + // default instance count value is 1 + xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( @@ -46,17 +55,34 @@ public void setUp() { } @Test - public void testGetRequestDetails() { - this.occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), - new HashMap()); - occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), - new HashMap()); - List requests = occiApplication.getRequestsFromUser(RequestHelper.USER_MOCK); + public void testGetRequestDetails() throws InterruptedException { + occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + Assert.assertEquals(1, requests.size()); + String requestId = requests.get(0).getId(); + Request requestDetails = occiApplication.getRequestDetails(RequestHelper.ACCESS_TOKEN, + requestId); + + Assert.assertEquals(requestId, requestDetails.getId()); + Assert.assertEquals("", requestDetails.getInstanceId()); + Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); + } + + @Test + public void testGetRequestDetailsAfterPeriod() throws InterruptedException { + occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); Request requestDetails = occiApplication.getRequestDetails(RequestHelper.ACCESS_TOKEN, requestId); + Assert.assertEquals(requestId, requestDetails.getId()); + Assert.assertEquals("", requestDetails.getInstanceId()); + Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); + + Thread.sleep(OCCIApplication.PERIOD); + Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertEquals(expectedInstanceId, requestDetails.getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requestDetails.getState()); @@ -64,8 +90,8 @@ public void testGetRequestDetails() { @Test public void testResquestUser() { - this.occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), - new HashMap()); + this.occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); @@ -74,28 +100,26 @@ public void testResquestUser() { @Test public void testManyResquestUser() { - int valueRequest = 10; - for (int i = 0; i < valueRequest; i++) { - this.occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), - new HashMap()); - } + int numberOfInstances = 10; + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); + this.occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(valueRequest, requestsFromUser.size()); + Assert.assertEquals(numberOfInstances, requestsFromUser.size()); } @Test public void testRemoveAllRequest() { - int numberOfRequests = 10; - for (int i = 0; i < numberOfRequests; i++) { - occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), - new HashMap()); - } + int numberOfInstances = 10; + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); + occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(numberOfRequests, requestsFromUser.size()); + Assert.assertEquals(numberOfInstances, requestsFromUser.size()); occiApplication.removeAllRequests(RequestHelper.ACCESS_TOKEN); requestsFromUser = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); @@ -105,19 +129,18 @@ public void testRemoveAllRequest() { @Test public void testRemoveSpecificRequest() { - int numberOfRequests = 10; - for (int i = 0; i < numberOfRequests; i++) { - occiApplication.newRequest(RequestHelper.ACCESS_TOKEN, new ArrayList(), - new HashMap()); - } + int numberOfInstances = 10; + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); + occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(numberOfRequests, requestsFromUser.size()); + Assert.assertEquals(numberOfInstances, requestsFromUser.size()); occiApplication.removeRequest(RequestHelper.ACCESS_TOKEN, requestsFromUser.get(1).getId()); requestsFromUser = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); - Assert.assertEquals(numberOfRequests - 1, requestsFromUser.size()); + Assert.assertEquals(numberOfInstances - 1, requestsFromUser.size()); } } From 0f4d341ef88a741ad279da818ae6dbbca76d4527 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sat, 19 Apr 2014 18:55:38 +0200 Subject: [PATCH 006/185] Refactoring request storage. --- .../manager/occi/ComputeServerResource.java | 14 +++ .../manager/occi/OCCIApplication.java | 101 +++++------------- .../manager/occi/RequestServerResource.java | 20 +++- .../manager/occi/core/HeaderUtils.java | 26 ----- .../occi/request/RequestRepository.java | 80 ++++++++++++++ .../manager/occi/request/RequestsBox.java | 67 ------------ .../manager/occi/TestOCCIApplication.java | 13 +-- .../{core => }/TestRequestServerResource.java | 6 +- .../occi/model/ComputeApplication.java | 16 ++- 9 files changed, 164 insertions(+), 179 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java delete mode 100644 src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java rename src/test/java/org/fogbowcloud/manager/occi/{core => }/TestRequestServerResource.java (95%) diff --git a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java index 2763bc1d..7fee47a0 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.occi; +import java.util.List; + import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Delete; @@ -47,4 +49,16 @@ public String remove() { public String post() { return null; } + + protected static String generateResponse(List instances, HttpRequest req) { + String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); + String response = ""; + for (String location : instances) { + response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + location + "\n"; + } + if (response.equals("")) { + response = "Empty"; + } + return response; + } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 18896c12..ef53d719 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -1,14 +1,11 @@ package org.fogbowcloud.manager.occi; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import org.fogbowcloud.manager.occi.core.Category; @@ -20,8 +17,8 @@ import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; +import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; -import org.fogbowcloud.manager.occi.request.RequestsBox; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; @@ -30,16 +27,15 @@ public class OCCIApplication extends Application { private IdentityPlugin identityPlugin; private ComputePlugin computePlugin; - private Map userToRequestIds; - private Map requestIdToRequest; + + private RequestRepository requestRepository = new RequestRepository(); + private final Timer timer = new Timer(); protected static final long PERIOD = 50; private static final Logger LOGGER = Logger.getLogger(OCCIApplication.class); public OCCIApplication() { - this.userToRequestIds = new ConcurrentHashMap(); - this.requestIdToRequest = new ConcurrentHashMap(); submitRequests(); } @@ -53,41 +49,26 @@ public void run() { } private void checkAndSubmitOpenRequests() { - Iterator> iter = userToRequestIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - String user = entry.getKey(); - RequestsBox requestBoxes = entry.getValue(); - List openIds = new ArrayList(); - openIds.addAll(requestBoxes.getOpenIds()); - - for (String requestId : openIds) { - Request request = requestIdToRequest.get(requestId); - // TODO before submit request we have to check - try { - submitLocalRequest(request); - userToRequestIds.get(user).openToFulfilled(request.getId()); - } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.BAD_REQUEST) - && e.getMessage().contains( - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { - submitRemoteRequest(request); // FIXME submit more than - // one at same time - } else { - // TODO set state to fail? - updateStateToFailed(user, request); - throw e; - } + for (Request request : requestRepository.get(RequestState.OPEN)) { + // TODO before submit request we have to check + try { + submitLocalRequest(request); + request.setState(RequestState.FULFILLED); + } catch (OCCIException e) { + if (e.getStatus().equals(ErrorType.BAD_REQUEST) + && e.getMessage().contains( + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + submitRemoteRequest(request); // FIXME submit more than + // one at same time + } else { + // TODO set state to fail? + request.setState(RequestState.FAILED); +// throw e; } } } } - private void updateStateToFailed(String user, Request request) { - userToRequestIds.get(user).openToFailed(request.getId()); - requestIdToRequest.get(request.getId()).setState(RequestState.FAILED); - } - @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); @@ -115,19 +96,15 @@ public IdentityPlugin getIdentityPlugin() { public Request getRequestDetails(String authToken, String requestId) { checkUserToken(authToken); checkRequestId(authToken, requestId); - return requestIdToRequest.get(requestId); + return requestRepository.get(requestId); } - public List newRequests(String authToken, List categories, + public List createRequests(String authToken, List categories, Map xOCCIAtt) { checkUserToken(authToken); String user = getIdentityPlugin().getUser(authToken); - if (userToRequestIds.get(user) == null) { - userToRequestIds.put(user, new RequestsBox()); - } - Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT .getValue())); LOGGER.info("Request " + instanceCount + " instances"); @@ -139,8 +116,7 @@ public List newRequests(String authToken, List categories, xOCCIAtt); currentRequests.add(request); - userToRequestIds.get(user).addOpen(request.getId()); - requestIdToRequest.put(request.getId(), request); + requestRepository.addRequest(user, request); } return currentRequests; } @@ -159,52 +135,31 @@ private void submitLocalRequest(Request request) { String instanceLocation = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), xOCCIAtt); instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); - updateStateToFulfilled(request.getId(), instanceLocation); - } - - private void updateStateToFulfilled(String requestId, String instanceLocation) { - requestIdToRequest.get(requestId).setInstanceId(instanceLocation); - requestIdToRequest.get(requestId).setState(RequestState.FULFILLED); + request.setInstanceId(instanceLocation); + request.setState(RequestState.FULFILLED); } public List getRequestsFromUser(String authToken) { checkUserToken(authToken); String user = getIdentityPlugin().getUser(authToken); - - List requests = new ArrayList(); - if (userToRequestIds.get(user) != null) { - for (String requestId : userToRequestIds.get(user).getAllRequestIds()) { - requests.add(requestIdToRequest.get(requestId)); - } - } - return requests; + return requestRepository.getByUser(user); } public void removeAllRequests(String authToken) { checkUserToken(authToken); String user = getIdentityPlugin().getUser(authToken); - - if (userToRequestIds.get(user) != null) { - for (String requestId : userToRequestIds.get(user).getAllRequestIds()) { - requestIdToRequest.remove(requestId); - } - userToRequestIds.remove(user); - } + requestRepository.removeByUser(user); } public void removeRequest(String authToken, String requestId) { checkUserToken(authToken); checkRequestId(authToken, requestId); - String user = getIdentityPlugin().getUser(authToken); - - userToRequestIds.get(user).remove(requestId); - requestIdToRequest.remove(requestId); + requestRepository.remove(requestId); } private void checkRequestId(String authToken, String requestId) { String user = getIdentityPlugin().getUser(authToken); - - if (userToRequestIds.get(user) == null || !userToRequestIds.get(user).contains(requestId)) { + if (requestRepository.get(user, requestId) == null) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java index 012692ad..7f5e235d 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java @@ -35,7 +35,7 @@ public String fetch() { if (requestId == null) { LOGGER.info("Getting all requests of token :" + userToken); - return HeaderUtils.generateResponseId(application.getRequestsFromUser(userToken), req); + return generateResponse(application.getRequestsFromUser(userToken), req); } LOGGER.info("Getting request(" + requestId + ") of token :" + userToken); @@ -75,8 +75,8 @@ public String post() { String authToken = HeaderUtils.getAuthToken(req.getHeaders()); - List currentRequests = application.newRequests(authToken, categories, xOCCIAtt); - return HeaderUtils.generateResponseId(currentRequests, req); + List currentRequests = application.createRequests(authToken, categories, xOCCIAtt); + return generateResponse(currentRequests, req); } public static Map normalizeXOCCIAtt(Map xOCCIAtt) { @@ -110,7 +110,7 @@ public static Map normalizeXOCCIAtt(Map xOCCIAtt return defOCCIAtt; } - public static void checkRequestType(String enumString) { + protected static void checkRequestType(String enumString) { for (int i = 0; i < RequestType.values().length; i++) { if (enumString.equals(RequestType.values()[i].getValue())) { return; @@ -118,4 +118,16 @@ public static void checkRequestType(String enumString) { } throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } + + protected static String generateResponse(List requests, HttpRequest req) { + String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); + String response = ""; + for (Request request : requests) { + response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + request.getId() + "\n"; + } + if (response.equals("")) { + response = "Empty"; + } + return response; + } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java b/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java index 3ec471da..28a7d2a3 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java @@ -8,8 +8,6 @@ import java.util.List; import java.util.Map; -import org.fogbowcloud.manager.occi.request.Request; -import org.restlet.engine.adapter.HttpRequest; import org.restlet.engine.header.Header; import org.restlet.util.Series; @@ -17,30 +15,6 @@ public class HeaderUtils { public static final String X_OCCI_LOCATION = "X-OCCI-Location: "; - public static String generateResponseId(List requests, HttpRequest req) { - String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); - String response = ""; - for (Request request : requests) { - response += X_OCCI_LOCATION + requestEndpoint + "/" + request.getId() + "\n"; - } - if (response.equals("")) { - response = "Empty"; - } - return response; - } - - public static String generateResponseInstanceLocations(List instances, HttpRequest req) { - String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); - String response = ""; - for (String location : instances) { - response += X_OCCI_LOCATION + requestEndpoint + "/" + location + "\n"; - } - if (response.equals("")) { - response = "Empty"; - } - return response; - } - public static void checkOCCIContentType(Series
headers) { String contentType = headers.getValues(OCCIHeaders.CONTENT_TYPE); if (!contentType.equals(OCCIHeaders.OCCI_CONTENT_TYPE)) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java new file mode 100644 index 00000000..306034ba --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -0,0 +1,80 @@ +package org.fogbowcloud.manager.occi.request; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class RequestRepository { + + private Map> requests = new HashMap>(); + + public void addRequest(String user, Request request) { + List userRequests = requests.get(user); + if (userRequests == null) { + userRequests = new LinkedList(); + requests.put(user, userRequests); + } + userRequests.add(request); + } + + public List get(RequestState state) { + List requestInState = new LinkedList(); + for (List userRequests : requests.values()) { + for (Request request : userRequests) { + if (request.getState().equals(state)) { + requestInState.add(request); + } + } + } + return requestInState; + } + + public Request get(String requestId) { + for (List userRequests : requests.values()) { + for (Request request : userRequests) { + if (request.getId().equals(requestId)) { + return request; + } + } + } + return null; + } + + public Request get(String user, String requestId) { + List userRequests = requests.get(user); + if (userRequests == null) { + return null; + } + for (Request request : userRequests) { + if (request.getId().equals(requestId)) { + return request; + } + } + return null; + } + + public List getByUser(String user) { + List userRequests = requests.get(user); + return userRequests == null ? new LinkedList() + : new LinkedList(userRequests); + } + + public void removeByUser(String user) { + requests.remove(user); + } + + public void remove(String requestId) { + for (List userRequests : requests.values()) { + Iterator iterator = userRequests.iterator(); + while (iterator.hasNext()) { + Request request = (Request) iterator.next(); + if (request.getId().equals(requestId)) { + iterator.remove(); + return; + } + } + } + } +} diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java deleted file mode 100644 index 3faaf2be..00000000 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestsBox.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.fogbowcloud.manager.occi.request; - -import java.util.ArrayList; -import java.util.List; - -public class RequestsBox { - - private List open; - private List fulfilled; - private List failed; - private List canceled; - private List closed; - - public RequestsBox() { - // TODO concurrency problems? - open = new ArrayList(); - fulfilled = new ArrayList(); - failed = new ArrayList(); - canceled = new ArrayList(); - closed = new ArrayList(); - } - - public void addOpen(String requestId) { - open.add(requestId); - } - - public List getAllRequestIds() { - List allRequestIds = new ArrayList(); - allRequestIds.addAll(open); - allRequestIds.addAll(fulfilled); - allRequestIds.addAll(failed); - allRequestIds.addAll(canceled); - allRequestIds.addAll(closed); - return allRequestIds; - } - - public void remove(String requestId) { - open.remove(requestId); - fulfilled.remove(requestId); - failed.remove(requestId); - canceled.remove(requestId); - closed.remove(requestId); - } - - public boolean contains(String requestId) { - if (open.contains(requestId) || fulfilled.contains(requestId) - || fulfilled.contains(requestId) || failed.contains(requestId) - || canceled.contains(requestId) || closed.contains(requestId)) { - return true; - } - return false; - } - - public void openToFulfilled(String requestId) { - open.remove(requestId); - fulfilled.add(requestId); - } - - public List getOpenIds() { - return open; - } - - public void openToFailed(String requestId) { - open.remove(requestId); - failed.add(requestId); - } -} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 70c67868..955ab637 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -31,6 +31,7 @@ public class TestOCCIApplication { private Map xOCCIAtt; + @SuppressWarnings("unchecked") @Before public void setUp() { occiApplication = new OCCIApplication(); @@ -56,7 +57,7 @@ public void setUp() { @Test public void testGetRequestDetails() throws InterruptedException { - occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); @@ -70,7 +71,7 @@ public void testGetRequestDetails() throws InterruptedException { @Test public void testGetRequestDetailsAfterPeriod() throws InterruptedException { - occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); @@ -90,7 +91,7 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { @Test public void testResquestUser() { - this.occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + this.occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); @@ -102,7 +103,7 @@ public void testResquestUser() { public void testManyResquestUser() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - this.occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + this.occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); @@ -114,7 +115,7 @@ public void testManyResquestUser() { public void testRemoveAllRequest() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); @@ -131,7 +132,7 @@ public void testRemoveAllRequest() { public void testRemoveSpecificRequest() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - occiApplication.newRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestRequestServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestRequestServerResource.java similarity index 95% rename from src/test/java/org/fogbowcloud/manager/occi/core/TestRequestServerResource.java rename to src/test/java/org/fogbowcloud/manager/occi/TestRequestServerResource.java index 7e2d669f..bbbf109a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestRequestServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestRequestServerResource.java @@ -1,8 +1,12 @@ -package org.fogbowcloud.manager.occi.core; +package org.fogbowcloud.manager.occi; import java.util.Map; import org.fogbowcloud.manager.occi.RequestServerResource; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.Assert; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java index 6ff8bbbf..7f167c8e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java @@ -35,7 +35,7 @@ public class ComputeApplication extends Application { private Map> userToInstanceId; private Map instanceIdToDetails; - private static InstanceIdGenerator idGenerator; + private InstanceIdGenerator idGenerator; private Map keystoneTokenToUser; private Map> termToAttributes; @@ -224,12 +224,24 @@ public String fetch() { if (instanceId == null) { LOGGER.info("Getting all instance ids from token :" + userToken); - return HeaderUtils.generateResponseInstanceLocations( + return generateResponse( computeApplication.getAllInstanceIds(userToken), req); } LOGGER.info("Getting request(" + instanceId + ") of token :" + userToken); return computeApplication.getInstanceDetails(userToken, instanceId); } + + private static String generateResponse(List instances, HttpRequest req) { + String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); + String response = ""; + for (String location : instances) { + response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + location + "\n"; + } + if (response.equals("")) { + response = "Empty"; + } + return response; + } @Post public String post() { From cfd1da43a0bb81f616b44310d94ebaa751ce6c69 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sun, 20 Apr 2014 04:44:32 +0200 Subject: [PATCH 007/185] should only fetch resource info once --- .../fogbowcloud/manager/xmpp/ManagerXmppComponent.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 5881c961..c098659d 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -7,6 +7,7 @@ import org.fogbowcloud.manager.occi.plugins.ComputePlugin; import org.fogbowcloud.manager.xmpp.core.ManagerFacade; import org.fogbowcloud.manager.xmpp.core.ManagerModel; +import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; import org.jamppa.component.XMPPComponent; import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; @@ -44,10 +45,11 @@ public void iAmAlive(String authToken) { iq.setFrom(getJID()); Element statusEl = iq.getElement() .addElement("query", IAMALIVE_NAMESPACE).addElement("status"); - statusEl.addElement("cpu-idle").setText(plugin.getResourcesInfo(authToken).getCpuIdle()); - statusEl.addElement("cpu-inuse").setText(plugin.getResourcesInfo(authToken).getCpuInUse()); - statusEl.addElement("mem-idle").setText(plugin.getResourcesInfo(authToken).getMemIdle()); - statusEl.addElement("mem-inuse").setText(plugin.getResourcesInfo(authToken).getMemInUse()); + ResourcesInfo resourcesInfo = plugin.getResourcesInfo(authToken); + statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); + statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); + statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); + statusEl.addElement("mem-inuse").setText(resourcesInfo.getMemInUse()); this.syncSendPacket(iq); } From 50e8c29cdfb4454820ed0432d7a69b573c1bcef4 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sun, 20 Apr 2014 06:08:22 +0200 Subject: [PATCH 008/185] More refactoring. Reading conf from properties file. --- manager.conf.example | 13 ++++ .../java/org/fogbowcloud/manager/Main.java | 41 ++++++++++-- .../openstack/ComputeOpenStackPlugin.java | 62 +++++++++---------- .../openstack/IdentityOpenStackPlugin.java | 24 ++++--- .../manager/xmpp/core/ManagerFacade.java | 1 + .../occi/model/ComputeApplication.java | 10 ++- .../occi/plugins/TestComputeOpenStack.java | 31 ++++++---- .../occi/plugins/TestIdentityOpenStack.java | 14 ++--- 8 files changed, 128 insertions(+), 68 deletions(-) create mode 100644 manager.conf.example diff --git a/manager.conf.example b/manager.conf.example new file mode 100644 index 00000000..80da6c72 --- /dev/null +++ b/manager.conf.example @@ -0,0 +1,13 @@ +xmpp_jid=manager.test.com +xmpp_password=password +xmpp_host=127.0.0.1 +xmpp_port=5347 + +compute_class=org.fogbowcloud.manager.occi.plugins.openstack.ComputeOpenStackPlugin +compute_openstack_url=http://localhost:8182 +compute_openstack_flavor_small=m1-small +compute_openstack_flavor_medium=m1-medium +compute_openstack_flavor_large=m1-large + +identity_class=org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin +identity_openstack_url=http://localhost:5000 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 3f800a00..303edcea 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -1,15 +1,48 @@ package org.fogbowcloud.manager; +import java.io.FileInputStream; +import java.util.Properties; + import org.fogbowcloud.manager.occi.OCCIApplication; +import org.fogbowcloud.manager.occi.plugins.ComputePlugin; +import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; +import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.restlet.Component; import org.restlet.data.Protocol; public class Main { public static void main(String[] args) throws Exception { - Component component = new Component(); - component.getServers().add(Protocol.HTTP, 8182); - component.getDefaultHost().attach(new OCCIApplication()); - component.start(); + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(args[0]); + properties.load(input); + + ComputePlugin computePlugin = (ComputePlugin) createInstance( + "compute_class", properties); + IdentityPlugin identityPlugin = (IdentityPlugin) createInstance( + "identity_class", properties); + + ManagerXmppComponent xmpp = new ManagerXmppComponent(properties.getProperty("xmpp_jid"), + properties.getProperty("xmpp_password"), + properties.getProperty("xmpp_host"), + Integer.parseInt(properties.getProperty("xmpp_port")), + computePlugin); + xmpp.connect(); + xmpp.process(false); + + OCCIApplication application = new OCCIApplication(); + application.setComputePlugin(computePlugin); + application.setIdentityPlugin(identityPlugin); + + Component http = new Component(); + http.getServers().add(Protocol.HTTP, 8182); + http.getDefaultHost().attach(application); + http.start(); + } + + private static Object createInstance(String propName, Properties properties) + throws Exception { + return Class.forName(properties.getProperty(propName)) + .getConstructor(Properties.class).newInstance(properties); } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java index 3a765357..5c03a769 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java @@ -6,6 +6,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; import org.apache.commons.codec.Charsets; import org.apache.http.HttpException; @@ -29,39 +30,36 @@ public class ComputeOpenStackPlugin implements ComputePlugin { - public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; - private String computeEndPoint; private static final Logger LOGGER = Logger.getLogger(ComputeOpenStackPlugin.class); - - private final String TERM_COMPUTE = "compute"; - private final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; - private final String CLASS_COMPUTE = "kind"; - - public static final String SMALL_FLAVOR_TERM = "m1-small"; - public static final String MEDIUM_FLAVOR_TERM = "m1-medium"; - public static final String LARGE_FLAVOR_TERM = "m1-large"; + private static final String TERM_COMPUTE = "compute"; + private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; + private static final String CLASS_COMPUTE = "kind"; + private static final String COMPUTE_ENDPOINT = "/compute"; + + public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; public static final String CIRROS_IMAGE_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; - private Map fogTermToOpensStackCategory; - - public ComputeOpenStackPlugin(String computeEndPoint) { - this.computeEndPoint = computeEndPoint; - fogTermToOpensStackCategory = new HashMap(); - - // FIXME this code have to load this configuration from a conf file - fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, new Category( - SMALL_FLAVOR_TERM, "http://schemas.openstack.org/template/resource#", - OCCIHeaders.MIXIN_CLASS)); - fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, new Category( - MEDIUM_FLAVOR_TERM, "http://schemas.openstack.org/template/resource#", - OCCIHeaders.MIXIN_CLASS)); - fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, new Category( - LARGE_FLAVOR_TERM, "http://schemas.openstack.org/template/resource#", - OCCIHeaders.MIXIN_CLASS)); + private String computeEndpoint; + private Map fogTermToOpensStackCategory = new HashMap(); + + public ComputeOpenStackPlugin(Properties properties) { + this.computeEndpoint = properties.getProperty("compute_openstack_url") + COMPUTE_ENDPOINT; + fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory( + "compute_openstack_flavor_small", properties)); + fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, createFlavorCategory( + "compute_openstack_flavor_medium", properties)); + fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, createFlavorCategory( + "compute_openstack_flavor_large", properties)); fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category( CIRROS_IMAGE_TERM, OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); } - + + private static Category createFlavorCategory(String flavorPropName, Properties properties) { + return new Category(properties.getProperty(flavorPropName), + "http://schemas.openstack.org/template/resource#", + OCCIHeaders.MIXIN_CLASS); + } + @Override public String requestInstance(String authToken, List categories, Map xOCCIAtt) { @@ -81,7 +79,7 @@ public String requestInstance(String authToken, List categories, HttpClient httpCLient = new DefaultHttpClient(); HttpPost httpPost; try { - httpPost = new HttpPost(computeEndPoint); + httpPost = new HttpPost(computeEndpoint); httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); for (Category category : openStackCategories) { @@ -114,7 +112,7 @@ public String getInstanceDetails(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { - httpGet = new HttpGet(computeEndPoint + "/" + instanceId); + httpGet = new HttpGet(computeEndpoint + "/" + instanceId); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -138,7 +136,7 @@ public String getInstancesFromUser(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { - httpGet = new HttpGet(computeEndPoint); + httpGet = new HttpGet(computeEndpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -160,7 +158,7 @@ public String removeAllInstances(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeEndPoint); + httpDelete = new HttpDelete(computeEndpoint); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpDelete); @@ -183,7 +181,7 @@ public String removeInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeEndPoint + "/" + instanceId); + httpDelete = new HttpDelete(computeEndpoint + "/" + instanceId); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpDelete); diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java index 0e237799..e2d6f87d 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.occi.plugins.openstack; +import java.util.Properties; + import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -28,18 +30,22 @@ public class IdentityOpenStackPlugin implements IdentityPlugin { public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; - private String keystoneEndPointTokens; - private String keystoneEndPointAuthToken; + private static String V3_ENDPOINT_PATH = "/v3/auth/tokens/"; + private static String V2_ENDPOINT_PATH = "/v2.0/tokens"; + + private String v2Endpoint; + private String v3Endpoint; - public IdentityOpenStackPlugin(String endPointTokens, String endPointAuthToken) { - this.keystoneEndPointTokens = endPointTokens; - this.keystoneEndPointAuthToken = endPointAuthToken; + public IdentityOpenStackPlugin(Properties properties) { + String keystoneUrl = properties.getProperty("identity_openstack_url"); + this.v3Endpoint = keystoneUrl + V3_ENDPOINT_PATH; + this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } public boolean isValidToken(String authToken) { try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.keystoneEndPointTokens); + HttpGet httpGet = new HttpGet(this.v2Endpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -58,7 +64,7 @@ public boolean isValidToken(String authToken) { public String getUser(String authToken) { try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.keystoneEndPointTokens); + HttpGet httpGet = new HttpGet(this.v2Endpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -81,7 +87,7 @@ public String getUser(String authToken) { public String getToken(String username, String password) { try { HttpClient httpClient = new DefaultHttpClient(); - HttpPost httpPost = new HttpPost(this.keystoneEndPointAuthToken); + HttpPost httpPost = new HttpPost(this.v3Endpoint); httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); @@ -129,6 +135,6 @@ private String getTokenFromJson(String responseStr) { } public void setEnd(String end) { - this.keystoneEndPointAuthToken = end; + this.v3Endpoint = end; } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java index 028768a0..bede1a4f 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java @@ -10,6 +10,7 @@ public class ManagerFacade { private ManagerModel managerModel; + public ManagerFacade(ManagerModel managerModel) { if (managerModel == null) throw new IllegalArgumentException(); this.managerModel = managerModel; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java index 7f167c8e..aaa1a867 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java @@ -33,6 +33,10 @@ public class ComputeApplication extends Application { public static final String HOSTNAME_ATTRIBUTE_OCCI = "occi.compute.hostname"; public static final String ID_CORE_ATTRIBUTE_OCCI = "occi.core.id"; + public static final String SMALL_FLAVOR_TERM = "m1-small"; + public static final String MEDIUM_FLAVOR_TERM = "m1-medium"; + public static final String LARGE_FLAVOR_TERM = "m1-large"; + private Map> userToInstanceId; private Map instanceIdToDetails; private InstanceIdGenerator idGenerator; @@ -55,19 +59,19 @@ private void normalizeDefaultAttributes() { attributesToValueSmall.put(CORE_ATTRIBUTE_OCCI, "1"); attributesToValueSmall.put(MEMORY_ATTRIBUTE_OCCI, "2"); attributesToValueSmall.put(SPEED_ATTRIBUTE_OCCI, "0"); - this.termToAttributes.put(ComputeOpenStackPlugin.SMALL_FLAVOR_TERM , attributesToValueSmall); + this.termToAttributes.put(SMALL_FLAVOR_TERM , attributesToValueSmall); Map attributesToValueMedium = new HashMap(); attributesToValueMedium.put(CORE_ATTRIBUTE_OCCI, "2"); attributesToValueMedium.put(MEMORY_ATTRIBUTE_OCCI, "2520"); attributesToValueMedium.put(SPEED_ATTRIBUTE_OCCI, "0"); - this.termToAttributes.put(ComputeOpenStackPlugin.MEDIUM_FLAVOR_TERM, attributesToValueMedium); + this.termToAttributes.put(MEDIUM_FLAVOR_TERM, attributesToValueMedium); Map attributesToValueLarge = new HashMap(); attributesToValueLarge.put(CORE_ATTRIBUTE_OCCI, "3"); attributesToValueLarge.put(MEMORY_ATTRIBUTE_OCCI, "3520"); attributesToValueLarge.put(SPEED_ATTRIBUTE_OCCI, "0"); - this.termToAttributes.put(ComputeOpenStackPlugin.LARGE_FLAVOR_TERM, attributesToValueLarge); + this.termToAttributes.put(LARGE_FLAVOR_TERM, attributesToValueLarge); Map attributesToValueUbuntu = new HashMap(); attributesToValueUbuntu.put(ARCHITECTURE_ATTRIBUTE_OCCI, "64"); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 095662b5..10aaf581 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -4,6 +4,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.StringTokenizer; import org.fogbowcloud.manager.occi.core.Category; @@ -21,15 +22,15 @@ public class TestComputeOpenStack { - private final String FIRST_INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - private final String FIFTH_INSTANCE_ID = "hla256kh-43ar-67ww-ao90-fa8d456fce9f"; - private final String FOURTH_INSTANCE_ID = "qwuif8ad-19a3-4afg-1l77-tred90crei0q"; - private final String THIRD_INSTANCE_ID = "cg2563ee-503c-6abr-54gl-ba8d12hf0pof"; - private final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; - private final String COMPUTE_END_POINT = "http://localhost:" + PluginHelper.PORT_ENDPOINT - + ComputeApplication.TARGET; - private final String LOCATION_INSTANCE_PREFIX = HeaderUtils.X_OCCI_LOCATION + COMPUTE_END_POINT - + "/"; + private static final String FIRST_INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + private static final String FIFTH_INSTANCE_ID = "hla256kh-43ar-67ww-ao90-fa8d456fce9f"; + private static final String FOURTH_INSTANCE_ID = "qwuif8ad-19a3-4afg-1l77-tred90crei0q"; + private static final String THIRD_INSTANCE_ID = "cg2563ee-503c-6abr-54gl-ba8d12hf0pof"; + private static final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; + + private static final String URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; + private static final String LOCATION_INSTANCE_PREFIX = HeaderUtils.X_OCCI_LOCATION + + URL + ComputeApplication.TARGET + "/"; private ComputeOpenStackPlugin computeOpenStack; private PluginHelper pluginHelper; @@ -37,7 +38,13 @@ public class TestComputeOpenStack { @Before public void setUp() throws Exception { - computeOpenStack = new ComputeOpenStackPlugin(COMPUTE_END_POINT); + Properties properties = new Properties(); + properties.put("compute_openstack_url", URL); + properties.put("compute_openstack_flavor_small", ComputeApplication.SMALL_FLAVOR_TERM); + properties.put("compute_openstack_flavor_medium", ComputeApplication.MEDIUM_FLAVOR_TERM); + properties.put("compute_openstack_flavor_large", ComputeApplication.MEDIUM_FLAVOR_TERM); + + computeOpenStack = new ComputeOpenStackPlugin(properties); // five first generated instance ids expectedInstanceIds = new ArrayList(); @@ -231,7 +238,7 @@ public void testGetAllInstanceIds() { instanceLocations = getInstanceLocations(computeOpenStack .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(1, instanceLocations.size()); - Assert.assertEquals(COMPUTE_END_POINT + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); + Assert.assertEquals(URL + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); } @Test @@ -256,7 +263,7 @@ public void testGetAllManyInstanceIds() { .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); for (String expectedId : expectedInstanceIds) { - Assert.assertTrue(instanceLocations.contains(COMPUTE_END_POINT + "/" + expectedId)); + Assert.assertTrue(instanceLocations.contains(URL + "/" + expectedId)); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 86a885dd..b1adb4c0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.occi.plugins; -import org.fogbowcloud.manager.occi.model.KeystoneApplication; +import java.util.Properties; + import org.fogbowcloud.manager.occi.model.PluginHelper; import org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin; import org.junit.After; @@ -11,18 +12,15 @@ public class TestIdentityOpenStack { - private final String KEYSTONE_END_POINT_TOKENS = "http://localhost:" - + PluginHelper.PORT_ENDPOINT + KeystoneApplication.TARGET_TOKENS; - private final String KEYSTONE_END_POINT_AUTH_TOKEN = "http://localhost:" - + PluginHelper.PORT_ENDPOINT + KeystoneApplication.TARGET_AUTH_TOKEN; - + private final String KEYSTONE_URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; private IdentityOpenStackPlugin identityOpenStack; private PluginHelper pluginHelper; @Before public void setUp() throws Exception { - this.identityOpenStack = new IdentityOpenStackPlugin(KEYSTONE_END_POINT_TOKENS, - KEYSTONE_END_POINT_AUTH_TOKEN); + Properties properties = new Properties(); + properties.put("identity_openstack_url", KEYSTONE_URL); + this.identityOpenStack = new IdentityOpenStackPlugin(properties); this.pluginHelper = new PluginHelper(); this.pluginHelper.initializeKeystoneComponent(); } From d93dfb4fd87d8377be89d8d0cd269d7149812485 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sun, 20 Apr 2014 06:10:59 +0200 Subject: [PATCH 009/185] Removing compilation warnings, i.e. unused variables --- .../org/fogbowcloud/manager/occi/TestDeleteCompute.java | 5 ++--- .../org/fogbowcloud/manager/occi/TestDeleteRequest.java | 1 + .../java/org/fogbowcloud/manager/occi/TestGetCompute.java | 6 +++--- .../java/org/fogbowcloud/manager/occi/TestGetRequest.java | 1 + .../java/org/fogbowcloud/manager/occi/TestPostRequest.java | 4 +--- 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index f63c76c4..e91647dd 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -1,6 +1,5 @@ package org.fogbowcloud.manager.occi; -import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.DefaultHttpClient; @@ -46,7 +45,7 @@ public void TestWrongAccessToken() throws Exception{ httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpDelete); + client.execute(httpDelete); } @Ignore @@ -56,7 +55,7 @@ public void TestInvalidVM() throws Exception{ get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); get.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(get); + client.execute(get); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index edd74e20..4e7c9aa9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -30,6 +30,7 @@ public class TestDeleteRequest { RequestHelper requestHelper; + @SuppressWarnings("unchecked") @Before public void setup() throws Exception { this.requestHelper = new RequestHelper(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 4751f3f4..3dc9b54e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -124,7 +124,7 @@ public void TestWrongContentType() throws Exception{ httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); + client.execute(httpGet); } @Ignore @@ -134,7 +134,7 @@ public void TestWrongAccessToken() throws Exception{ httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); + client.execute(httpGet); } @Ignore @@ -144,6 +144,6 @@ public void TestInvalidVM() throws Exception{ httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); + client.execute(httpGet); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index f5993070..3cf49588 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -37,6 +37,7 @@ public class TestGetRequest { private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + RequestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + @SuppressWarnings("unchecked") @Before public void setup() throws Exception { this.requestHelper = new RequestHelper(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index 1d35e188..a9b1ca59 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -8,12 +8,9 @@ import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; -import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.message.BasicStatusLine; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.RequestHelper; @@ -31,6 +28,7 @@ public class TestPostRequest { private RequestHelper requestHelper; + @SuppressWarnings("unchecked") @Before public void setup() throws Exception { this.requestHelper = new RequestHelper(); From 6a878cf8426aa4cd5c932793434d7038e9f3c88c Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 21 Apr 2014 06:07:16 +0200 Subject: [PATCH 010/185] Renaming and moving classes. --- manager.conf.example | 4 +- .../java/org/fogbowcloud/manager/Main.java | 4 +- .../manager/core/model/ManagerItem.java | 48 +++++++++++++++++++ .../core => core/model}/ManagerModel.java | 2 +- .../core => core/model}/ResourcesInfo.java | 2 +- .../{occi => core}/plugins/ComputePlugin.java | 4 +- .../plugins/IdentityPlugin.java | 2 +- .../openstack/OpenStackComputePlugin.java} | 12 ++--- .../openstack/OpenStackIdentityPlugin.java} | 8 ++-- .../manager/occi/OCCIApplication.java | 4 +- .../manager/xmpp/ManagerXmppComponent.java | 6 +-- .../manager/xmpp/core/ManagerFacade.java | 3 ++ .../manager/xmpp/core/ManagerItem.java | 47 ------------------ .../manager/occi/TestDeleteCompute.java | 4 +- .../manager/occi/TestDeleteRequest.java | 4 +- .../manager/occi/TestGetCompute.java | 4 +- .../manager/occi/TestGetRequest.java | 4 +- .../manager/occi/TestOCCIApplication.java | 4 +- .../manager/occi/TestPostRequest.java | 4 +- .../occi/model/ComputeApplication.java | 6 +-- .../occi/model/KeystoneApplication.java | 22 ++++----- .../manager/occi/model/RequestHelper.java | 4 +- .../occi/plugins/TestComputeOpenStack.java | 6 +-- .../occi/plugins/TestIdentityOpenStack.java | 6 +-- .../manager/xmpp/TestManagerFacade.java | 4 +- .../manager/xmpp/TestManagerItem.java | 4 +- .../manager/xmpp/TestManagerModel.java | 6 +-- .../manager/xmpp/model/ManagerTestHelper.java | 4 +- .../xmpp/model/RendezvousItemCopy.java | 2 +- 29 files changed, 119 insertions(+), 115 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java rename src/main/java/org/fogbowcloud/manager/{xmpp/core => core/model}/ManagerModel.java (89%) rename src/main/java/org/fogbowcloud/manager/{xmpp/core => core/model}/ResourcesInfo.java (97%) rename src/main/java/org/fogbowcloud/manager/{occi => core}/plugins/ComputePlugin.java (80%) rename src/main/java/org/fogbowcloud/manager/{occi => core}/plugins/IdentityPlugin.java (79%) rename src/main/java/org/fogbowcloud/manager/{occi/plugins/openstack/ComputeOpenStackPlugin.java => core/plugins/openstack/OpenStackComputePlugin.java} (95%) rename src/main/java/org/fogbowcloud/manager/{occi/plugins/openstack/IdentityOpenStackPlugin.java => core/plugins/openstack/OpenStackIdentityPlugin.java} (95%) delete mode 100644 src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerItem.java diff --git a/manager.conf.example b/manager.conf.example index 80da6c72..18575df7 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -3,11 +3,11 @@ xmpp_password=password xmpp_host=127.0.0.1 xmpp_port=5347 -compute_class=org.fogbowcloud.manager.occi.plugins.openstack.ComputeOpenStackPlugin +compute_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackComputePlugin compute_openstack_url=http://localhost:8182 compute_openstack_flavor_small=m1-small compute_openstack_flavor_medium=m1-medium compute_openstack_flavor_large=m1-large -identity_class=org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin +identity_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackIdentityPlugin identity_openstack_url=http://localhost:5000 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 303edcea..031666ee 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -3,9 +3,9 @@ import java.io.FileInputStream; import java.util.Properties; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.restlet.Component; import org.restlet.data.Protocol; diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java b/src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java new file mode 100644 index 00000000..27598898 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java @@ -0,0 +1,48 @@ +package org.fogbowcloud.manager.core.model; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; + +public class ManagerItem { + + public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + + private long lastTime; + private ResourcesInfo resourcesInfo; + + public ManagerItem(ResourcesInfo resourcesInfo) { + if (resourcesInfo == null) { + throw new IllegalArgumentException(); + } + lastTime = new DateUtils().currentTimeMillis(); + this.resourcesInfo = resourcesInfo; + } + + public ResourcesInfo getResourcesInfo() { + return resourcesInfo; + } + + public long getLastTime() { + return lastTime; + } + + public String getFormattedTime() { + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + return dateFormatISO8601.format(new Date(lastTime)); + } + + /** + * This method was implemented just for unit test. + * + * @param lastTime + */ + public void setLastTime(long lastTime) { + this.lastTime = lastTime; + } +} \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerModel.java b/src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java similarity index 89% rename from src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerModel.java rename to src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java index edca372b..0b880212 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerModel.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.xmpp.core; +package org.fogbowcloud.manager.core.model; import java.util.LinkedList; import java.util.List; diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java similarity index 97% rename from src/main/java/org/fogbowcloud/manager/xmpp/core/ResourcesInfo.java rename to src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index c435764e..018318ac 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.xmpp.core; +package org.fogbowcloud.manager.core.model; public class ResourcesInfo { diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java similarity index 80% rename from src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java rename to src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java index fc63f076..6cf9fa3e 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java @@ -1,10 +1,10 @@ -package org.fogbowcloud.manager.occi.plugins; +package org.fogbowcloud.manager.core.plugins; import java.util.List; import java.util.Map; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; public interface ComputePlugin { diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java similarity index 79% rename from src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java rename to src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index e0ff34e9..7bf2582b 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.plugins; +package org.fogbowcloud.manager.core.plugins; public interface IdentityPlugin { diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java similarity index 95% rename from src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java rename to src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 5c03a769..25f35c03 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/ComputeOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.plugins.openstack; +package org.fogbowcloud.manager.core.plugins.openstack; import java.io.IOException; import java.net.URISyntaxException; @@ -19,18 +19,18 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.request.RequestConstants; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; -public class ComputeOpenStackPlugin implements ComputePlugin { +public class OpenStackComputePlugin implements ComputePlugin { - private static final Logger LOGGER = Logger.getLogger(ComputeOpenStackPlugin.class); + private static final Logger LOGGER = Logger.getLogger(OpenStackComputePlugin.class); private static final String TERM_COMPUTE = "compute"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; private static final String CLASS_COMPUTE = "kind"; @@ -42,7 +42,7 @@ public class ComputeOpenStackPlugin implements ComputePlugin { private String computeEndpoint; private Map fogTermToOpensStackCategory = new HashMap(); - public ComputeOpenStackPlugin(Properties properties) { + public OpenStackComputePlugin(Properties properties) { this.computeEndpoint = properties.getProperty("compute_openstack_url") + COMPUTE_ENDPOINT; fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory( "compute_openstack_flavor_small", properties)); diff --git a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java similarity index 95% rename from src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java rename to src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index e2d6f87d..b5a40b43 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/plugins/openstack/IdentityOpenStackPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.plugins.openstack; +package org.fogbowcloud.manager.core.plugins.openstack; import java.util.Properties; @@ -12,13 +12,13 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.json.JSONException; import org.json.JSONObject; import org.restlet.resource.ResourceException; -public class IdentityOpenStackPlugin implements IdentityPlugin { +public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String USERNAME_KEYSTONE = "username"; public static final String PASSWORD_KEYSTONE = "password"; @@ -36,7 +36,7 @@ public class IdentityOpenStackPlugin implements IdentityPlugin { private String v2Endpoint; private String v3Endpoint; - public IdentityOpenStackPlugin(Properties properties) { + public OpenStackIdentityPlugin(Properties properties) { String keystoneUrl = properties.getProperty("identity_openstack_url"); this.v3Endpoint = keystoneUrl + V3_ENDPOINT_PATH; this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index ef53d719..5f9c5a29 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -8,13 +8,13 @@ import java.util.UUID; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index c098659d..efede0a7 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -4,10 +4,10 @@ import java.util.TimerTask; import org.dom4j.Element; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.model.ManagerModel; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.xmpp.core.ManagerFacade; -import org.fogbowcloud.manager.xmpp.core.ManagerModel; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; import org.jamppa.component.XMPPComponent; import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java index bede1a4f..b0b10f4d 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java @@ -5,6 +5,9 @@ import org.dom4j.Attribute; import org.dom4j.Element; +import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.ManagerModel; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.xmpp.packet.IQ; public class ManagerFacade { diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerItem.java b/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerItem.java deleted file mode 100644 index 54b4db7f..00000000 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerItem.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.fogbowcloud.manager.xmpp.core; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; - -public class ManagerItem { - - public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private long lastTime; - private ResourcesInfo resourcesInfo; - - public ManagerItem(ResourcesInfo resourcesInfo) { - if (resourcesInfo == null) { - throw new IllegalArgumentException(); - } - lastTime = new DateUtils().currentTimeMillis(); - this.resourcesInfo = resourcesInfo; - } - - public ResourcesInfo getResourcesInfo() { - return resourcesInfo; - } - - public long getLastTime() { - return lastTime; - } - - public String getFormattedTime() { - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - return dateFormatISO8601.format(new Date(lastTime)); - } - - /** - * This method was implemented just for unit test. - * - * @param lastTime - */ - public void setLastTime(long lastTime){ - this.lastTime = lastTime; - } -} \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index e91647dd..0908092d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -3,11 +3,11 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.RequestHelper; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.junit.After; import org.junit.Before; import org.junit.Ignore; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index 4e7c9aa9..390f5053 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -13,11 +13,11 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.RequestHelper; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.After; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 3dc9b54e..0cbd1454 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -8,12 +8,12 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.RequestHelper; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.After; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 3cf49588..a87b7a5b 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -15,13 +15,13 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.ComputeApplication; import org.fogbowcloud.manager.occi.model.RequestHelper; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 955ab637..bddd5144 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -5,12 +5,12 @@ import java.util.List; import java.util.Map; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.model.ComputeApplication; import org.fogbowcloud.manager.occi.model.RequestHelper; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index a9b1ca59..cc54f28f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -11,11 +11,11 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.RequestHelper; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.After; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java index aaa1a867..67ad4215 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java @@ -7,13 +7,13 @@ import java.util.UUID; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.plugins.openstack.ComputeOpenStackPlugin; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.engine.adapter.HttpRequest; @@ -75,7 +75,7 @@ private void normalizeDefaultAttributes() { Map attributesToValueUbuntu = new HashMap(); attributesToValueUbuntu.put(ARCHITECTURE_ATTRIBUTE_OCCI, "64"); - this.termToAttributes.put(ComputeOpenStackPlugin.CIRROS_IMAGE_TERM, attributesToValueUbuntu); + this.termToAttributes.put(OpenStackComputePlugin.CIRROS_IMAGE_TERM, attributesToValueUbuntu); } @Override @@ -155,7 +155,7 @@ public String newInstance(String authToken, List categories, private void checkRules(List categories, Map xOCCIAtt) { boolean OSFound = false; for (Category category : categories) { - if (category.getScheme().equals(ComputeOpenStackPlugin.OS_SCHEME)) { + if (category.getScheme().equals(OpenStackComputePlugin.OS_SCHEME)) { OSFound = true; break; } diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java index 9b3f4f10..f408bbb0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java @@ -5,8 +5,8 @@ import java.util.Map; import org.apache.http.HttpStatus; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Application; @@ -99,9 +99,9 @@ public Representation post(Representation entity) { } String username = getUserFeatureCredentials(jsonCredentials, - IdentityOpenStackPlugin.USERNAME_KEYSTONE); + OpenStackIdentityPlugin.USERNAME_KEYSTONE); String password = getUserFeatureCredentials(jsonCredentials, - IdentityOpenStackPlugin.PASSWORD_KEYSTONE); + OpenStackIdentityPlugin.PASSWORD_KEYSTONE); keyStoneApplication.authenticationCheck(username, password); return new StringRepresentation( @@ -112,11 +112,11 @@ public Representation post(Representation entity) { private String mountJSONResponseAuthenticateToken(String token) { try { JSONObject rootIdTOken = new JSONObject(); - rootIdTOken.put(IdentityOpenStackPlugin.ID_KEYSTONE, token); + rootIdTOken.put(OpenStackIdentityPlugin.ID_KEYSTONE, token); JSONObject rootToken = new JSONObject(); - rootToken.put(IdentityOpenStackPlugin.TOKEN_KEYSTONE, rootIdTOken); + rootToken.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdTOken); JSONObject rootAccess = new JSONObject(); - rootAccess.put(IdentityOpenStackPlugin.ACCESS_KEYSTONE, rootToken); + rootAccess.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, rootToken); return rootAccess.toString(); } catch (JSONException e) { e.printStackTrace(); @@ -127,8 +127,8 @@ private String mountJSONResponseAuthenticateToken(String token) { private String getUserFeatureCredentials(String jsonCredentials, String feature) { try { JSONObject root = new JSONObject(jsonCredentials); - return root.getJSONObject(IdentityOpenStackPlugin.AUTH_KEYSTONE) - .getJSONObject(IdentityOpenStackPlugin.PASSWORD_CREDENTIALS_KEYSTONE) + return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) + .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS_KEYSTONE) .getString(feature).toString(); } catch (JSONException e) { return null; @@ -138,11 +138,11 @@ private String getUserFeatureCredentials(String jsonCredentials, String feature) private String mountJSONResponseUserPerToken(String token, String user) { try { JSONObject nameObject = new JSONObject(); - nameObject.put(IdentityOpenStackPlugin.NAME_KEYSTONE, user); + nameObject.put(OpenStackIdentityPlugin.NAME_KEYSTONE, user); JSONObject tokenObject = new JSONObject(); - tokenObject.put(IdentityOpenStackPlugin.USER_KEYSTONE, nameObject); + tokenObject.put(OpenStackIdentityPlugin.USER_KEYSTONE, nameObject); JSONObject accessObject = new JSONObject(); - accessObject.put(IdentityOpenStackPlugin.TOKEN_KEYSTONE, tokenObject); + accessObject.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, tokenObject); return accessObject.toString(); } catch (JSONException e) { } diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java index c626656a..ea19cef3 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java @@ -11,10 +11,10 @@ import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; -import org.fogbowcloud.manager.occi.plugins.IdentityPlugin; import org.restlet.Component; import org.restlet.data.Protocol; diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 10aaf581..a13e97af 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -7,13 +7,13 @@ import java.util.Properties; import java.util.StringTokenizer; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.model.ComputeApplication; import org.fogbowcloud.manager.occi.model.PluginHelper; -import org.fogbowcloud.manager.occi.plugins.openstack.ComputeOpenStackPlugin; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.After; import org.junit.Assert; @@ -32,7 +32,7 @@ public class TestComputeOpenStack { private static final String LOCATION_INSTANCE_PREFIX = HeaderUtils.X_OCCI_LOCATION + URL + ComputeApplication.TARGET + "/"; - private ComputeOpenStackPlugin computeOpenStack; + private OpenStackComputePlugin computeOpenStack; private PluginHelper pluginHelper; List expectedInstanceIds; @@ -44,7 +44,7 @@ public void setUp() throws Exception { properties.put("compute_openstack_flavor_medium", ComputeApplication.MEDIUM_FLAVOR_TERM); properties.put("compute_openstack_flavor_large", ComputeApplication.MEDIUM_FLAVOR_TERM); - computeOpenStack = new ComputeOpenStackPlugin(properties); + computeOpenStack = new OpenStackComputePlugin(properties); // five first generated instance ids expectedInstanceIds = new ArrayList(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index b1adb4c0..668a5ee1 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -2,8 +2,8 @@ import java.util.Properties; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.model.PluginHelper; -import org.fogbowcloud.manager.occi.plugins.openstack.IdentityOpenStackPlugin; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -13,14 +13,14 @@ public class TestIdentityOpenStack { private final String KEYSTONE_URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; - private IdentityOpenStackPlugin identityOpenStack; + private OpenStackIdentityPlugin identityOpenStack; private PluginHelper pluginHelper; @Before public void setUp() throws Exception { Properties properties = new Properties(); properties.put("identity_openstack_url", KEYSTONE_URL); - this.identityOpenStack = new IdentityOpenStackPlugin(properties); + this.identityOpenStack = new OpenStackIdentityPlugin(properties); this.pluginHelper = new PluginHelper(); this.pluginHelper.initializeKeystoneComponent(); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java index ba316f74..2db9f2a2 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java @@ -3,9 +3,9 @@ import java.util.ArrayList; import java.util.List; +import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.ManagerModel; import org.fogbowcloud.manager.xmpp.core.ManagerFacade; -import org.fogbowcloud.manager.xmpp.core.ManagerItem; -import org.fogbowcloud.manager.xmpp.core.ManagerModel; import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; import org.fogbowcloud.manager.xmpp.model.RendezvousItemCopy; import org.junit.Assert; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java index e22dc39d..8847d175 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java @@ -4,8 +4,8 @@ import java.text.SimpleDateFormat; import java.util.Date; -import org.fogbowcloud.manager.xmpp.core.ManagerItem; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; +import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java index b6412b29..cf18346a 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java @@ -3,9 +3,9 @@ import java.util.LinkedList; import java.util.List; -import org.fogbowcloud.manager.xmpp.core.ManagerItem; -import org.fogbowcloud.manager.xmpp.core.ManagerModel; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; +import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.ManagerModel; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java index 710f10f9..565c98ea 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java @@ -6,9 +6,9 @@ import org.dom4j.Attribute; import org.dom4j.Element; -import org.fogbowcloud.manager.occi.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; import org.jamppa.client.XMPPClient; import org.jamppa.client.plugin.xep0077.XEP0077; import org.jivesoftware.smack.XMPPException; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java b/src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java index 5c56545a..1f8f08db 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java @@ -5,7 +5,7 @@ import java.util.Locale; import java.util.TimeZone; -import org.fogbowcloud.manager.xmpp.core.ResourcesInfo; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class RendezvousItemCopy { From 427e4a0a61b62b8d319a165397ed161a1a8438bb Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 22 Apr 2014 14:49:37 -0300 Subject: [PATCH 011/185] Implementing ComputeServerResource --- .../manager/core/plugins/ComputePlugin.java | 4 ++ .../manager/occi/ComputeServerResource.java | 21 ++++------ .../manager/occi/OCCIApplication.java | 32 +++++++++++++++- .../manager/occi/TestGetCompute.java | 38 ++++++++++++++++--- .../manager/occi/model/PluginHelper.java | 2 +- .../manager/occi/model/RequestHelper.java | 7 ++-- 6 files changed, 80 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java index 6cf9fa3e..c455d63b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java @@ -15,4 +15,8 @@ public interface ComputePlugin { public ResourcesInfo getResourcesInfo (String authToken); public String removeInstance(String authToken, String instanceId); + + public String getInstanceDetails(String authToken, String instanceId); + + public String removeAllInstances(String authToken); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java index 7fee47a0..6d8e2d94 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java @@ -15,34 +15,27 @@ public class ComputeServerResource extends ServerResource{ public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); - String userToken = HeaderUtils.getAuthToken(req.getHeaders()); +// HeaderUtils.checkOCCIContentType(req.getHeaders()); + String authToken = HeaderUtils.getAuthToken(req.getHeaders()); String idVM = (String) getRequestAttributes().get("vmid"); if (idVM == null) { - //TODO implemet -// return application.getAllInstacesVM; + application.getAllVMFromUser(authToken); } - //TODO implemet -// return application.getSpecificInstanceVm(idVM); - - return null; + return application.getSpecificVMDetails(authToken, idVM); } @Delete public String remove() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); - String userToken = HeaderUtils.getAuthToken(req.getHeaders()); + String authToken = HeaderUtils.getAuthToken(req.getHeaders()); String idVM = (String) getRequestAttributes().get("vmid"); if (idVM == null) { - //TODO implemet -// return application.removeAllInstacesVM; + return application.removeAllVMFromUser(authToken); } - //TODO implemet -// return application.removeSpecificInstanceVm(idVM); - - return null; + return application.removeSpecificInstanceVm(authToken, idVM); } @Post diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 5f9c5a29..2cf32f6b 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -74,6 +74,8 @@ public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/request", RequestServerResource.class); router.attach("/request/{requestid}", RequestServerResource.class); + router.attach("/compute/", ComputeServerResource.class); + router.attach("/compute/{vmid}", ComputeServerResource.class); return router; } @@ -169,4 +171,32 @@ private void checkUserToken(String authToken) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } } -} + + public String getAllVMFromUser(String authToken) { + checkUserToken(authToken); + //TODO check other manager + + return this.computePlugin.getInstancesFromUser(authToken); + } + + public String getSpecificVMDetails(String authToken, String idVM) { + checkUserToken(authToken); + //TODO check other manager + + return this.computePlugin.getInstanceDetails(authToken, idVM); + } + + public String removeAllVMFromUser(String authToken) { + checkUserToken(authToken); + //TODO check other manager + + return this.computePlugin.removeAllInstances(authToken); + } + + public String removeSpecificInstanceVm(String authToken, String idVM) { + checkUserToken(authToken); + //TODO check other manager + + return this.computePlugin.removeInstance(authToken, idVM); + } +} \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 0cbd1454..55528df3 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -8,6 +8,8 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.protocol.HTTP; +import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -64,17 +66,13 @@ public void TestGetComputeEmpty() throws Exception{ public void TestGetComputeOneVM() throws Exception{ //Post /request HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpClient client = new DefaultHttpClient(); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpPost); - List requestIDs = RequestHelper.getRequestLocations(response); - - Assert.assertEquals(1, requestIDs.size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); //Get /compute/ HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); @@ -117,6 +115,36 @@ public void TestGetComputeManyVMs() throws Exception{ Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } + @Ignore + @Test + public void TestGetComputeDetailsSpecificVM() throws Exception{ + //Post /request + HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpClient client = new DefaultHttpClient(); + Category category = new Category(RequestConstants.TERM, + RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); + httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); + HttpResponse response = client.execute(httpPost); + + String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); + String idVm = responseStr.replace("X-OCCI-Location: http://localhost:8182/request/", "").trim(); + + //Get /compute/$VM + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + idVm); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + client = new DefaultHttpClient(); + response = client.execute(httpGet); + responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); + System.out.println(responseStr); + + + Assert.assertEquals(1, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + @Ignore @Test(expected = OCCIException.class) public void TestWrongContentType() throws Exception{ diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java index 098b574c..1ba57477 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java @@ -54,4 +54,4 @@ public void initializeComputeComponent(List expectedInstanceIds) throws public void disconnectComponent() throws Exception { this.component.stop(); } -} +} \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java index ea19cef3..0c191f5f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java @@ -14,7 +14,10 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; +import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.request.Request; +import org.mockito.Mockito; import org.restlet.Component; import org.restlet.data.Protocol; @@ -28,10 +31,8 @@ public class RequestHelper { public static final String URI_FOGBOW_COMPUTE = "http://localhost:8182/compute/"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; - - public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) - throws Exception { + public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); From 4e015ae741804cb06eac14f9cee52b2e9127ce5e Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 22 Apr 2014 20:55:10 +0200 Subject: [PATCH 012/185] wow refactor --- .../java/org/fogbowcloud/manager/Main.java | 21 +- .../manager/core/ManagerFacade.java | 237 ++++++++++++++++++ .../manager/core/plugins/ComputePlugin.java | 11 +- .../openstack/OpenStackComputePlugin.java | 20 +- .../manager/occi/ComputeServerResource.java | 15 +- .../manager/occi/OCCIApplication.java | 176 ++----------- .../manager/occi/RequestServerResource.java | 6 +- .../manager/occi/request/Instance.java | 5 + .../manager/xmpp/ManagerXmppComponent.java | 22 +- .../manager/xmpp/core/ManagerFacade.java | 50 ---- .../manager/occi/TestOCCIApplication.java | 4 +- .../occi/plugins/TestComputeOpenStack.java | 40 +-- .../manager/xmpp/TestManagerFacade.java | 2 +- 13 files changed, 327 insertions(+), 282 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java create mode 100644 src/main/java/org/fogbowcloud/manager/occi/request/Instance.java delete mode 100644 src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 031666ee..b824fc62 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -3,8 +3,7 @@ import java.io.FileInputStream; import java.util.Properties; -import org.fogbowcloud.manager.core.plugins.ComputePlugin; -import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.restlet.Component; @@ -17,22 +16,17 @@ public static void main(String[] args) throws Exception { FileInputStream input = new FileInputStream(args[0]); properties.load(input); - ComputePlugin computePlugin = (ComputePlugin) createInstance( - "compute_class", properties); - IdentityPlugin identityPlugin = (IdentityPlugin) createInstance( - "identity_class", properties); - + ManagerFacade facade = new ManagerFacade(properties); + ManagerXmppComponent xmpp = new ManagerXmppComponent(properties.getProperty("xmpp_jid"), properties.getProperty("xmpp_password"), properties.getProperty("xmpp_host"), Integer.parseInt(properties.getProperty("xmpp_port")), - computePlugin); + facade); xmpp.connect(); xmpp.process(false); - OCCIApplication application = new OCCIApplication(); - application.setComputePlugin(computePlugin); - application.setIdentityPlugin(identityPlugin); + OCCIApplication application = new OCCIApplication(facade); Component http = new Component(); http.getServers().add(Protocol.HTTP, 8182); @@ -40,9 +34,4 @@ public static void main(String[] args) throws Exception { http.start(); } - private static Object createInstance(String propName, Properties properties) - throws Exception { - return Class.forName(properties.getProperty(propName)) - .getConstructor(Properties.class).newInstance(properties); - } } diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java new file mode 100644 index 00000000..8775a8e7 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -0,0 +1,237 @@ +package org.fogbowcloud.manager.core; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Timer; +import java.util.TimerTask; +import java.util.UUID; + +import org.apache.log4j.Logger; +import org.dom4j.Attribute; +import org.dom4j.Element; +import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.request.Instance; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestAttribute; +import org.fogbowcloud.manager.occi.request.RequestRepository; +import org.fogbowcloud.manager.occi.request.RequestState; +import org.xmpp.packet.IQ; + +public class ManagerFacade { + + private static final Logger LOGGER = Logger.getLogger(ManagerFacade.class); + protected static final long PERIOD = 50; + + private final Timer timer = new Timer(); + private List members = new LinkedList(); + private RequestRepository requests = new RequestRepository(); + + private ComputePlugin computePlugin; + private IdentityPlugin identityPlugin; + private Properties properties; + + public ManagerFacade(Properties properties) throws Exception { + this.properties = properties; + this.computePlugin = (ComputePlugin) createInstance( + "compute_class", properties); + this.identityPlugin = (IdentityPlugin) createInstance( + "identity_class", properties); + } + + private static Object createInstance(String propName, Properties properties) + throws Exception { + return Class.forName(properties.getProperty(propName)) + .getConstructor(Properties.class).newInstance(properties); + } + + @SuppressWarnings("unchecked") + public ArrayList getItemsFromIQ( + IQ responseFromWhoIsAliveIQ) { + Element queryElement = responseFromWhoIsAliveIQ.getElement().element( + "query"); + Iterator itemIterator = queryElement.elementIterator("item"); + ArrayList aliveItems = new ArrayList(); + + while (itemIterator.hasNext()) { + Element itemEl = (Element) itemIterator.next(); + Attribute id = itemEl.attribute("id"); + Element statusEl = itemEl.element("status"); + String cpuIdle = statusEl.element("cpu-idle").getText(); + String cpuInUse = statusEl.element("cpu-inuse").getText(); + String memIdle = statusEl.element("mem-idle").getText(); + String memInUse = statusEl.element("mem-inuse").getText(); + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, + cpuInUse, memIdle, memInUse); + ManagerItem item = new ManagerItem(resources); + aliveItems.add(item); + } + updateMembers(aliveItems); + return aliveItems; + } + + public void updateMembers(List members) { + if (members == null) { + throw new IllegalArgumentException(); + } + this.members = members; + } + + public List getMembers() { + return members; + } + + public ResourcesInfo getResourcesInfo() { + String token = identityPlugin.getToken(properties.getProperty("federation.user.name"), + properties.getProperty("federation.user.password")); + return computePlugin.getResourcesInfo(token); + } + + public String getUser(String authToken) { + return identityPlugin.getUser(authToken); + } + + public List getRequestsFromUser(String authToken) { + checkUserToken(authToken); + String user = getUser(authToken); + return requests.getByUser(user); + } + + private void checkUserToken(String authToken) { + if (!identityPlugin.isValidToken(authToken)) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } + } + + public void removeAllRequests(String authToken) { + checkUserToken(authToken); + String user = identityPlugin.getUser(authToken); + requests.removeByUser(user); + } + + public void removeRequest(String authToken, String requestId) { + checkUserToken(authToken); + checkRequestId(authToken, requestId); + requests.remove(requestId); + } + + private void checkRequestId(String authToken, String requestId) { + String user = identityPlugin.getUser(authToken); + if (requests.get(user, requestId) == null) { + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } + } + + public List getInstances(String authToken) { + checkUserToken(authToken); + //TODO check other manager + + return this.computePlugin.getInstances(authToken); + } + + public Instance getInstance(String authToken, String instanceId) { + checkUserToken(authToken); + //TODO check other manager + + return this.computePlugin.getInstance(authToken, instanceId); + } + + public void removeInstances(String authToken) { + checkUserToken(authToken); + //TODO check other manager + + this.computePlugin.removeInstances(authToken); + } + + public void removeInstance(String authToken, String instanceId) { + checkUserToken(authToken); + //TODO check other manager + + this.computePlugin.removeInstance(authToken, instanceId); + } + + public Request getRequest(String authToken, String requestId) { + checkUserToken(authToken); + checkRequestId(authToken, requestId); + return requests.get(requestId); + } + + public List createRequests(String authToken, List categories, + Map xOCCIAtt) { + checkUserToken(authToken); + String user = getUser(authToken); + + Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT + .getValue())); + LOGGER.info("Request " + instanceCount + " instances"); + + List currentRequests = new ArrayList(); + for (int i = 0; i < instanceCount; i++) { + String requestId = String.valueOf(UUID.randomUUID()); + Request request = new Request(requestId, authToken, "", RequestState.OPEN, categories, + xOCCIAtt); + currentRequests.add(request); + requests.addRequest(user, request); + } + return currentRequests; + } + + private void submitRemoteRequest(Request request) { + // TODO Auto-generated method stub + + } + + private void submitLocalRequest(Request request) { + // Removing all xOCCI Attribute specific to request type + Map xOCCIAtt = request.getxOCCIAtt(); + for (String keyAttributes : RequestAttribute.getValues()) { + xOCCIAtt.remove(keyAttributes); + } + String instanceLocation = computePlugin.requestInstance(request.getAuthToken(), + request.getCategories(), xOCCIAtt); + instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); + request.setInstanceId(instanceLocation); + request.setState(RequestState.FULFILLED); + } + + private void submitRequests() { + timer.schedule(new TimerTask() { + @Override + public void run() { + checkAndSubmitOpenRequests(); + } + }, 0, PERIOD); + } + + private void checkAndSubmitOpenRequests() { + for (Request request : requests.get(RequestState.OPEN)) { + // TODO before submit request we have to check + try { + submitLocalRequest(request); + request.setState(RequestState.FULFILLED); + } catch (OCCIException e) { + if (e.getStatus().equals(ErrorType.BAD_REQUEST) + && e.getMessage().contains( + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + submitRemoteRequest(request); // FIXME submit more than + // one at same time + } else { + // TODO set state to fail? + request.setState(RequestState.FAILED); +// throw e; + } + } + } + } +} diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java index c455d63b..b1c65c5d 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java @@ -5,18 +5,19 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.request.Instance; public interface ComputePlugin { public String requestInstance(String authToken,List categories, Map xOCCIAtt); - public String getInstancesFromUser(String authToken); + public List getInstances(String authToken); - public ResourcesInfo getResourcesInfo (String authToken); + public Instance getInstance(String authToken, String instanceId); - public String removeInstance(String authToken, String instanceId); + public void removeInstance(String authToken, String instanceId); - public String getInstanceDetails(String authToken, String instanceId); + public void removeInstances(String authToken); - public String removeAllInstances(String authToken); + public ResourcesInfo getResourcesInfo (String authToken); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 25f35c03..fc1dace0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -26,6 +26,7 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.request.Instance; import org.fogbowcloud.manager.occi.request.RequestConstants; public class OpenStackComputePlugin implements ComputePlugin { @@ -108,7 +109,7 @@ public String requestInstance(String authToken, List categories, return null; } - public String getInstanceDetails(String authToken, String instanceId) { + public Instance getInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { @@ -121,7 +122,8 @@ public String getInstanceDetails(String authToken, String instanceId) { } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } - return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); +// return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); + return null; } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { @@ -132,7 +134,7 @@ public String getInstanceDetails(String authToken, String instanceId) { return null; } - public String getInstancesFromUser(String authToken) { + public List getInstances(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { @@ -143,7 +145,8 @@ public String getInstancesFromUser(String authToken) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } - return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); +// return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); + return null; } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { @@ -154,18 +157,16 @@ public String getInstancesFromUser(String authToken) { return null; } - public String removeAllInstances(String authToken) { + public void removeInstances(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { httpDelete = new HttpDelete(computeEndpoint); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpDelete); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } - return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { @@ -173,11 +174,10 @@ public String removeAllInstances(String authToken) { } catch (IOException e) { LOGGER.error(e); } - return null; } @Override - public String removeInstance(String authToken, String instanceId) { + public void removeInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { @@ -190,7 +190,6 @@ public String removeInstance(String authToken, String instanceId) { } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } - return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { @@ -198,7 +197,6 @@ public String removeInstance(String authToken, String instanceId) { } catch (IOException e) { LOGGER.error(e); } - return null; } @Override diff --git a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java index 6d8e2d94..ba39c4a1 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java @@ -17,12 +17,13 @@ public String fetch() { HttpRequest req = (HttpRequest) getRequest(); // HeaderUtils.checkOCCIContentType(req.getHeaders()); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); - String idVM = (String) getRequestAttributes().get("vmid"); + String idVM = (String) getRequestAttributes().get("instanceId"); if (idVM == null) { - application.getAllVMFromUser(authToken); + application.getInstances(authToken); } - return application.getSpecificVMDetails(authToken, idVM); +// return application.getInstance(authToken, idVM); + return null; } @Delete @@ -30,12 +31,14 @@ public String remove() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); - String idVM = (String) getRequestAttributes().get("vmid"); + String idVM = (String) getRequestAttributes().get("instanceId"); if (idVM == null) { - return application.removeAllVMFromUser(authToken); +// return application.removeInstances(authToken); + return null; } - return application.removeSpecificInstanceVm(authToken, idVM); +// return application.removeInstance(authToken, idVM); + return null; } @Post diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 2cf32f6b..7fc094a8 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -1,202 +1,68 @@ package org.fogbowcloud.manager.occi; -import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import org.apache.log4j.Logger; -import org.fogbowcloud.manager.core.plugins.ComputePlugin; -import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.occi.core.ErrorType; -import org.fogbowcloud.manager.occi.core.HeaderUtils; -import org.fogbowcloud.manager.occi.core.OCCIException; -import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.request.Instance; import org.fogbowcloud.manager.occi.request.Request; -import org.fogbowcloud.manager.occi.request.RequestAttribute; -import org.fogbowcloud.manager.occi.request.RequestRepository; -import org.fogbowcloud.manager.occi.request.RequestState; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; public class OCCIApplication extends Application { - private IdentityPlugin identityPlugin; - private ComputePlugin computePlugin; - - private RequestRepository requestRepository = new RequestRepository(); - - private final Timer timer = new Timer(); - protected static final long PERIOD = 50; + private ManagerFacade managerFacade; - private static final Logger LOGGER = Logger.getLogger(OCCIApplication.class); - - public OCCIApplication() { - submitRequests(); - } - - private void submitRequests() { - timer.schedule(new TimerTask() { - @Override - public void run() { - checkAndSubmitOpenRequests(); - } - }, 0, PERIOD); - } - - private void checkAndSubmitOpenRequests() { - for (Request request : requestRepository.get(RequestState.OPEN)) { - // TODO before submit request we have to check - try { - submitLocalRequest(request); - request.setState(RequestState.FULFILLED); - } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.BAD_REQUEST) - && e.getMessage().contains( - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { - submitRemoteRequest(request); // FIXME submit more than - // one at same time - } else { - // TODO set state to fail? - request.setState(RequestState.FAILED); -// throw e; - } - } - } + public OCCIApplication(ManagerFacade facade) { + this.managerFacade = facade; } @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach("/request", RequestServerResource.class); - router.attach("/request/{requestid}", RequestServerResource.class); + router.attach("/request/{requestId}", RequestServerResource.class); router.attach("/compute/", ComputeServerResource.class); - router.attach("/compute/{vmid}", ComputeServerResource.class); + router.attach("/compute/{instanceId}", ComputeServerResource.class); return router; } - public void setComputePlugin(ComputePlugin computePlugin) { - this.computePlugin = computePlugin; - } - - public ComputePlugin getComputePlugin() { - return computePlugin; - } - - public void setIdentityPlugin(IdentityPlugin identityPlugin) { - this.identityPlugin = identityPlugin; - } - - public IdentityPlugin getIdentityPlugin() { - return identityPlugin; - } - - public Request getRequestDetails(String authToken, String requestId) { - checkUserToken(authToken); - checkRequestId(authToken, requestId); - return requestRepository.get(requestId); + public Request getRequest(String authToken, String requestId) { + return managerFacade.getRequest(authToken, requestId); } public List createRequests(String authToken, List categories, Map xOCCIAtt) { - checkUserToken(authToken); - - String user = getIdentityPlugin().getUser(authToken); - - Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT - .getValue())); - LOGGER.info("Request " + instanceCount + " instances"); - - List currentRequests = new ArrayList(); - for (int i = 0; i < instanceCount; i++) { - String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, authToken, "", RequestState.OPEN, categories, - xOCCIAtt); - currentRequests.add(request); - - requestRepository.addRequest(user, request); - } - return currentRequests; - } - - private void submitRemoteRequest(Request request) { - // TODO Auto-generated method stub - - } - - private void submitLocalRequest(Request request) { - // Removing all xOCCI Attribute specific to request type - Map xOCCIAtt = request.getxOCCIAtt(); - for (String keyAttributes : RequestAttribute.getValues()) { - xOCCIAtt.remove(keyAttributes); - } - String instanceLocation = computePlugin.requestInstance(request.getAuthToken(), - request.getCategories(), xOCCIAtt); - instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); - request.setInstanceId(instanceLocation); - request.setState(RequestState.FULFILLED); + return managerFacade.createRequests(authToken, categories, xOCCIAtt); } public List getRequestsFromUser(String authToken) { - checkUserToken(authToken); - String user = getIdentityPlugin().getUser(authToken); - return requestRepository.getByUser(user); + return managerFacade.getRequestsFromUser(authToken); } public void removeAllRequests(String authToken) { - checkUserToken(authToken); - String user = getIdentityPlugin().getUser(authToken); - requestRepository.removeByUser(user); + managerFacade.removeAllRequests(authToken); } public void removeRequest(String authToken, String requestId) { - checkUserToken(authToken); - checkRequestId(authToken, requestId); - requestRepository.remove(requestId); - } - - private void checkRequestId(String authToken, String requestId) { - String user = getIdentityPlugin().getUser(authToken); - if (requestRepository.get(user, requestId) == null) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); - } - } - - private void checkUserToken(String authToken) { - if (!identityPlugin.isValidToken(authToken)) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } + managerFacade.removeRequest(authToken, requestId); } - public String getAllVMFromUser(String authToken) { - checkUserToken(authToken); - //TODO check other manager - - return this.computePlugin.getInstancesFromUser(authToken); + public List getInstances(String authToken) { + return managerFacade.getInstances(authToken); } - public String getSpecificVMDetails(String authToken, String idVM) { - checkUserToken(authToken); - //TODO check other manager - - return this.computePlugin.getInstanceDetails(authToken, idVM); + public Instance getInstance(String authToken, String instanceId) { + return managerFacade.getInstance(authToken, instanceId); } - public String removeAllVMFromUser(String authToken) { - checkUserToken(authToken); - //TODO check other manager - - return this.computePlugin.removeAllInstances(authToken); + public void removeInstances(String authToken) { + managerFacade.removeInstances(authToken); } - public String removeSpecificInstanceVm(String authToken, String idVM) { - checkUserToken(authToken); - //TODO check other manager - - return this.computePlugin.removeInstance(authToken, idVM); + public void removeInstance(String authToken, String instanceId) { + managerFacade.removeInstance(authToken, instanceId); } } \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java index 7f5e235d..ebbffb59 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java @@ -31,7 +31,7 @@ public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String userToken = HeaderUtils.getAuthToken(req.getHeaders()); - String requestId = (String) getRequestAttributes().get("requestid"); + String requestId = (String) getRequestAttributes().get("requestId"); if (requestId == null) { LOGGER.info("Getting all requests of token :" + userToken); @@ -39,7 +39,7 @@ public String fetch() { } LOGGER.info("Getting request(" + requestId + ") of token :" + userToken); - Request request = application.getRequestDetails(userToken, requestId); + Request request = application.getRequest(userToken, requestId); return request.toHttpMessageFormat(); } @@ -48,7 +48,7 @@ public String remove() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String userToken = HeaderUtils.getAuthToken(req.getHeaders()); - String requestId = (String) getRequestAttributes().get("requestid"); + String requestId = (String) getRequestAttributes().get("requestId"); if (requestId == null) { LOGGER.info("Removing all requests of token :" + userToken); diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java new file mode 100644 index 00000000..19554171 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java @@ -0,0 +1,5 @@ +package org.fogbowcloud.manager.occi.request; + +public class Instance { + +} diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index efede0a7..bd4e2fd5 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -4,10 +4,8 @@ import java.util.TimerTask; import org.dom4j.Element; -import org.fogbowcloud.manager.core.model.ManagerModel; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.fogbowcloud.manager.core.plugins.ComputePlugin; -import org.fogbowcloud.manager.xmpp.core.ManagerFacade; import org.jamppa.component.XMPPComponent; import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; @@ -21,13 +19,11 @@ public class ManagerXmppComponent extends XMPPComponent { private ManagerFacade managerFacade; private final Timer timer = new Timer(); private String rendezvousAddress; - private ComputePlugin plugin; public ManagerXmppComponent(String jid, String password, String server, - int port, ComputePlugin plugin) { + int port, ManagerFacade managerFacade) { super(jid, password, server, port); - managerFacade = new ManagerFacade(new ManagerModel()); - this.plugin = plugin; + this.managerFacade = managerFacade; } @Override @@ -35,17 +31,17 @@ public void connect() throws ComponentException { super.connect(); } - public void init(String authToken) { - callIamAlive(authToken); + public void init() { + callIamAlive(); } - public void iAmAlive(String authToken) { + public void iAmAlive() { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); iq.setFrom(getJID()); Element statusEl = iq.getElement() .addElement("query", IAMALIVE_NAMESPACE).addElement("status"); - ResourcesInfo resourcesInfo = plugin.getResourcesInfo(authToken); + ResourcesInfo resourcesInfo = managerFacade.getResourcesInfo(); statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); @@ -62,11 +58,11 @@ public void whoIsalive() { managerFacade.getItemsFromIQ(response); } - private void callIamAlive(final String authToken) { + private void callIamAlive() { timer.schedule(new TimerTask() { @Override public void run() { - iAmAlive(authToken); + iAmAlive(); whoIsalive(); } }, 0, PERIOD); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java deleted file mode 100644 index b0b10f4d..00000000 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/ManagerFacade.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.fogbowcloud.manager.xmpp.core; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.dom4j.Attribute; -import org.dom4j.Element; -import org.fogbowcloud.manager.core.model.ManagerItem; -import org.fogbowcloud.manager.core.model.ManagerModel; -import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.xmpp.packet.IQ; - -public class ManagerFacade { - - private ManagerModel managerModel; - - public ManagerFacade(ManagerModel managerModel) { - if (managerModel == null) throw new IllegalArgumentException(); - this.managerModel = managerModel; - } - - @SuppressWarnings("unchecked") - public ArrayList getItemsFromIQ( - IQ responseFromWhoIsAliveIQ) { - Element queryElement = responseFromWhoIsAliveIQ.getElement().element( - "query"); - Iterator itemIterator = queryElement.elementIterator("item"); - ArrayList aliveItems = new ArrayList(); - - while (itemIterator.hasNext()) { - Element itemEl = (Element) itemIterator.next(); - Attribute id = itemEl.attribute("id"); - Element statusEl = itemEl.element("status"); - String cpuIdle = statusEl.element("cpu-idle").getText(); - String cpuInUse = statusEl.element("cpu-inuse").getText(); - String memIdle = statusEl.element("mem-idle").getText(); - String memInUse = statusEl.element("mem-inuse").getText(); - ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse); - ManagerItem item = new ManagerItem(resources); - aliveItems.add(item); - } - managerModel.update(aliveItems); - return aliveItems; - } - - public ManagerModel getManagerModel() { - return managerModel; - } -} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index bddd5144..14b4e5ca 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -61,7 +61,7 @@ public void testGetRequestDetails() throws InterruptedException { List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); - Request requestDetails = occiApplication.getRequestDetails(RequestHelper.ACCESS_TOKEN, + Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, requestId); Assert.assertEquals(requestId, requestDetails.getId()); @@ -75,7 +75,7 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); - Request requestDetails = occiApplication.getRequestDetails(RequestHelper.ACCESS_TOKEN, + Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, requestId); Assert.assertEquals(requestId, requestDetails.getId()); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index a13e97af..f6ae7dc0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -75,7 +75,7 @@ public void testRequestAValidInstance() { computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); - String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instanceDetails, @@ -191,7 +191,7 @@ public void testSupportedOCCIAtt() { Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); - String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); @@ -212,7 +212,7 @@ public void testMoreSupportedOCCIAtts() { Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); - String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); @@ -223,7 +223,7 @@ public void testMoreSupportedOCCIAtts() { @Test public void testGetAllInstanceIds() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); // requesting one default instance @@ -236,7 +236,7 @@ public void testGetAllInstanceIds() { // check getting all instance ids instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(1, instanceLocations.size()); Assert.assertEquals(URL + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); } @@ -244,7 +244,7 @@ public void testGetAllInstanceIds() { @Test public void testGetAllManyInstanceIds() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); // requesting default instance @@ -260,7 +260,7 @@ public void testGetAllManyInstanceIds() { // check getting all instance ids instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); for (String expectedId : expectedInstanceIds) { Assert.assertTrue(instanceLocations.contains(URL + "/" + expectedId)); @@ -283,7 +283,7 @@ private List getInstanceLocations(String instancesFromUser) { @Test public void testGetInstanceDetails() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); // requesting one default instance @@ -296,9 +296,9 @@ public void testGetInstanceDetails() { // check instance details instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(1, instanceLocations.size()); - String instanceDetails = computeOpenStack.getInstanceDetails(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); Assert.assertEquals(FIRST_INSTANCE_ID, getAttValueFromDetails(instanceDetails, ComputeApplication.ID_CORE_ATTRIBUTE_OCCI)); @@ -315,19 +315,19 @@ public void testGetInstanceDetails() { @Test public void testDeleteAllInstancesEmpty() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); - computeOpenStack.removeAllInstances(PluginHelper.AUTH_TOKEN); + computeOpenStack.removeInstances(PluginHelper.AUTH_TOKEN); instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); } @Test public void testDeleteAllManyInstances() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); // requesting default instances @@ -342,20 +342,20 @@ public void testDeleteAllManyInstances() { // check number of instances instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); // removing all instances - computeOpenStack.removeAllInstances(PluginHelper.AUTH_TOKEN); + computeOpenStack.removeInstances(PluginHelper.AUTH_TOKEN); instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); } @Test public void testDeleteOneInstance() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(0, instanceLocations.size()); // requesting default instances @@ -370,13 +370,13 @@ public void testDeleteOneInstance() { // check number of instances instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); // removing one instances computeOpenStack.removeInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); instanceLocations = getInstanceLocations(computeOpenStack - .getInstancesFromUser(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size() - 1, instanceLocations.size()); } } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java index 2db9f2a2..b2bfe2f5 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java @@ -3,9 +3,9 @@ import java.util.ArrayList; import java.util.List; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.ManagerItem; import org.fogbowcloud.manager.core.model.ManagerModel; -import org.fogbowcloud.manager.xmpp.core.ManagerFacade; import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; import org.fogbowcloud.manager.xmpp.model.RendezvousItemCopy; import org.junit.Assert; From 7fe8668dcb7c91378407c9698cd9d24ce617f001 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 22 Apr 2014 16:29:03 -0300 Subject: [PATCH 013/185] Refactoring IdentityComputing (removing isValidToken) --- .../manager/core/ManagerFacade.java | 106 +++++++++--------- .../manager/core/plugins/IdentityPlugin.java | 2 - .../openstack/OpenStackIdentityPlugin.java | 19 ---- .../occi/plugins/TestIdentityOpenStack.java | 11 +- 4 files changed, 57 insertions(+), 81 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 8775a8e7..a660ad9c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -27,40 +27,36 @@ import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; +import org.restlet.resource.ResourceException; import org.xmpp.packet.IQ; public class ManagerFacade { - + private static final Logger LOGGER = Logger.getLogger(ManagerFacade.class); protected static final long PERIOD = 50; - + private final Timer timer = new Timer(); private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); - + private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; private Properties properties; - + public ManagerFacade(Properties properties) throws Exception { this.properties = properties; - this.computePlugin = (ComputePlugin) createInstance( - "compute_class", properties); - this.identityPlugin = (IdentityPlugin) createInstance( - "identity_class", properties); + this.computePlugin = (ComputePlugin) createInstance("compute_class", properties); + this.identityPlugin = (IdentityPlugin) createInstance("identity_class", properties); } - - private static Object createInstance(String propName, Properties properties) - throws Exception { - return Class.forName(properties.getProperty(propName)) - .getConstructor(Properties.class).newInstance(properties); + + private static Object createInstance(String propName, Properties properties) throws Exception { + return Class.forName(properties.getProperty(propName)).getConstructor(Properties.class) + .newInstance(properties); } @SuppressWarnings("unchecked") - public ArrayList getItemsFromIQ( - IQ responseFromWhoIsAliveIQ) { - Element queryElement = responseFromWhoIsAliveIQ.getElement().element( - "query"); + public ArrayList getItemsFromIQ(IQ responseFromWhoIsAliveIQ) { + Element queryElement = responseFromWhoIsAliveIQ.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); ArrayList aliveItems = new ArrayList(); @@ -72,8 +68,8 @@ public ArrayList getItemsFromIQ( String cpuInUse = statusEl.element("cpu-inuse").getText(); String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); - ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse); + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, cpuInUse, memIdle, + memInUse); ManagerItem item = new ManagerItem(resources); aliveItems.add(item); } @@ -91,85 +87,86 @@ public void updateMembers(List members) { public List getMembers() { return members; } - + public ResourcesInfo getResourcesInfo() { - String token = identityPlugin.getToken(properties.getProperty("federation.user.name"), + String token = identityPlugin.getToken(properties.getProperty("federation.user.name"), properties.getProperty("federation.user.password")); return computePlugin.getResourcesInfo(token); } public String getUser(String authToken) { - return identityPlugin.getUser(authToken); + try { + return identityPlugin.getUser(authToken); + } catch (ResourceException e) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } } public List getRequestsFromUser(String authToken) { - checkUserToken(authToken); String user = getUser(authToken); return requests.getByUser(user); } - - private void checkUserToken(String authToken) { - if (!identityPlugin.isValidToken(authToken)) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } - } public void removeAllRequests(String authToken) { - checkUserToken(authToken); - String user = identityPlugin.getUser(authToken); + String user = getUser(authToken); requests.removeByUser(user); } public void removeRequest(String authToken, String requestId) { - checkUserToken(authToken); checkRequestId(authToken, requestId); requests.remove(requestId); } - + private void checkRequestId(String authToken, String requestId) { - String user = identityPlugin.getUser(authToken); + String user = getUser(authToken); if (requests.get(user, requestId) == null) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } } - + public List getInstances(String authToken) { - checkUserToken(authToken); - //TODO check other manager - + // TODO check other manager + return this.computePlugin.getInstances(authToken); } public Instance getInstance(String authToken, String instanceId) { - checkUserToken(authToken); - //TODO check other manager - + // TODO check other manager + checkInstanceId(authToken, instanceId); return this.computePlugin.getInstance(authToken, instanceId); } public void removeInstances(String authToken) { - checkUserToken(authToken); - //TODO check other manager - + // TODO check other manager + this.computePlugin.removeInstances(authToken); } public void removeInstance(String authToken, String instanceId) { - checkUserToken(authToken); - //TODO check other manager - + // TODO check other manager + + checkInstanceId(authToken, instanceId); this.computePlugin.removeInstance(authToken, instanceId); } - + + private void checkInstanceId(String authToken, String instanceId) { + String user = getUser(authToken); + List userRequests = requests.getByUser(user); + for (Request request : userRequests) { + if (instanceId.equals(request.getInstanceId())) { + return; + } + } + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } + public Request getRequest(String authToken, String requestId) { - checkUserToken(authToken); checkRequestId(authToken, requestId); return requests.get(requestId); } - + public List createRequests(String authToken, List categories, Map xOCCIAtt) { - checkUserToken(authToken); String user = getUser(authToken); Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT @@ -204,7 +201,7 @@ private void submitLocalRequest(Request request) { request.setInstanceId(instanceLocation); request.setState(RequestState.FULFILLED); } - + private void submitRequests() { timer.schedule(new TimerTask() { @Override @@ -222,14 +219,13 @@ private void checkAndSubmitOpenRequests() { request.setState(RequestState.FULFILLED); } catch (OCCIException e) { if (e.getStatus().equals(ErrorType.BAD_REQUEST) - && e.getMessage().contains( - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { submitRemoteRequest(request); // FIXME submit more than // one at same time } else { // TODO set state to fail? request.setState(RequestState.FAILED); -// throw e; + // throw e; } } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index 7bf2582b..34527985 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -2,8 +2,6 @@ public interface IdentityPlugin { - public boolean isValidToken(String token); - public String getUser(String token); public String getToken(String username, String password); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index b5a40b43..27ccfec5 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -42,25 +42,6 @@ public OpenStackIdentityPlugin(Properties properties) { this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } - public boolean isValidToken(String authToken) { - try { - HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.v2Endpoint); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); - HttpResponse response = httpCLient.execute(httpGet); - - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED - || response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - return false; - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - public String getUser(String authToken) { try { HttpClient httpCLient = new DefaultHttpClient(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 668a5ee1..c3bc62c2 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -32,12 +32,13 @@ public void tearDown() throws Exception { @Test public void testValidToken() { - Assert.assertTrue(this.identityOpenStack.isValidToken(PluginHelper.AUTH_TOKEN)); + Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, + this.identityOpenStack.getUser(PluginHelper.AUTH_TOKEN)); } - @Test + @Test(expected = ResourceException.class) public void testInvalidToken() { - Assert.assertFalse(identityOpenStack.isValidToken("Invalid Token")); + identityOpenStack.getUser("Invalid Token"); } @Test @@ -53,8 +54,8 @@ public void testGetNameUserFromTokenInvalid() { @Test public void testGetToken() { - String token = this.identityOpenStack - .getToken(PluginHelper.USERNAME_FOGBOW, PluginHelper.PASSWORD_FOGBOW); + String token = this.identityOpenStack.getToken(PluginHelper.USERNAME_FOGBOW, + PluginHelper.PASSWORD_FOGBOW); Assert.assertEquals(PluginHelper.AUTH_TOKEN, token); } From e5ad7c83355ffe0a6e2b117cd5fa6986ac61082d Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 22 Apr 2014 21:42:42 +0200 Subject: [PATCH 014/185] Fixing XMPP tests. Refactoring plugins creation to Main. --- .../java/org/fogbowcloud/manager/Main.java | 16 ++++++ .../manager/core/ManagerFacade.java | 46 ++++------------ .../manager/core/plugins/ComputePlugin.java | 2 +- .../manager/xmpp/ManagerXmppComponent.java | 32 +++++++++++- .../manager/xmpp/TestManagerComponent.java | 15 +++--- .../manager/xmpp/TestManagerFacade.java | 52 +++++++------------ .../manager/xmpp/model/ManagerTestHelper.java | 26 +++++++--- 7 files changed, 103 insertions(+), 86 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index b824fc62..3e2ed2d2 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -4,6 +4,8 @@ import java.util.Properties; import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.restlet.Component; @@ -16,7 +18,14 @@ public static void main(String[] args) throws Exception { FileInputStream input = new FileInputStream(args[0]); properties.load(input); + ComputePlugin computePlugin = (ComputePlugin) createInstance( + "compute_class", properties); + IdentityPlugin identityPlugin = (IdentityPlugin) createInstance( + "identity_class", properties); + ManagerFacade facade = new ManagerFacade(properties); + facade.setComputePlugin(computePlugin); + facade.setIdentityPlugin(identityPlugin); ManagerXmppComponent xmpp = new ManagerXmppComponent(properties.getProperty("xmpp_jid"), properties.getProperty("xmpp_password"), @@ -33,5 +42,12 @@ public static void main(String[] args) throws Exception { http.getDefaultHost().attach(application); http.start(); } + + private static Object createInstance(String propName, Properties properties) + throws Exception { + return Class.forName(properties.getProperty(propName)) + .getConstructor(Properties.class).newInstance(properties); + } + } diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 8775a8e7..c46e7f54 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -1,7 +1,6 @@ package org.fogbowcloud.manager.core; import java.util.ArrayList; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -11,8 +10,6 @@ import java.util.UUID; import org.apache.log4j.Logger; -import org.dom4j.Attribute; -import org.dom4j.Element; import org.fogbowcloud.manager.core.model.ManagerItem; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -27,7 +24,6 @@ import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; -import org.xmpp.packet.IQ; public class ManagerFacade { @@ -44,41 +40,17 @@ public class ManagerFacade { public ManagerFacade(Properties properties) throws Exception { this.properties = properties; - this.computePlugin = (ComputePlugin) createInstance( - "compute_class", properties); - this.identityPlugin = (IdentityPlugin) createInstance( - "identity_class", properties); + if (properties == null) { + throw new IllegalArgumentException(); + } } - private static Object createInstance(String propName, Properties properties) - throws Exception { - return Class.forName(properties.getProperty(propName)) - .getConstructor(Properties.class).newInstance(properties); - } - - @SuppressWarnings("unchecked") - public ArrayList getItemsFromIQ( - IQ responseFromWhoIsAliveIQ) { - Element queryElement = responseFromWhoIsAliveIQ.getElement().element( - "query"); - Iterator itemIterator = queryElement.elementIterator("item"); - ArrayList aliveItems = new ArrayList(); - - while (itemIterator.hasNext()) { - Element itemEl = (Element) itemIterator.next(); - Attribute id = itemEl.attribute("id"); - Element statusEl = itemEl.element("status"); - String cpuIdle = statusEl.element("cpu-idle").getText(); - String cpuInUse = statusEl.element("cpu-inuse").getText(); - String memIdle = statusEl.element("mem-idle").getText(); - String memInUse = statusEl.element("mem-inuse").getText(); - ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse); - ManagerItem item = new ManagerItem(resources); - aliveItems.add(item); - } - updateMembers(aliveItems); - return aliveItems; + public void setComputePlugin(ComputePlugin computePlugin) { + this.computePlugin = computePlugin; + } + + public void setIdentityPlugin(IdentityPlugin identityPlugin) { + this.identityPlugin = identityPlugin; } public void updateMembers(List members) { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java index b1c65c5d..e0fe05e5 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java @@ -19,5 +19,5 @@ public interface ComputePlugin { public void removeInstances(String authToken); - public ResourcesInfo getResourcesInfo (String authToken); + public ResourcesInfo getResourcesInfo(String authToken); } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index bd4e2fd5..08afe749 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -1,10 +1,14 @@ package org.fogbowcloud.manager.xmpp; +import java.util.ArrayList; +import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; +import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.model.ManagerItem; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.jamppa.component.XMPPComponent; import org.xmpp.component.ComponentException; @@ -55,7 +59,33 @@ public void whoIsalive() { iq.setFrom(getJID()); iq.getElement().addElement("query", WHOISALIVE_NAMESPACE); IQ response = (IQ) this.syncSendPacket(iq); - managerFacade.getItemsFromIQ(response); + + ArrayList members = getMembersFromIQ(response); + managerFacade.updateMembers(members); + } + + @SuppressWarnings("unchecked") + private static ArrayList getMembersFromIQ( + IQ responseFromWhoIsAliveIQ) { + Element queryElement = responseFromWhoIsAliveIQ.getElement().element( + "query"); + Iterator itemIterator = queryElement.elementIterator("item"); + ArrayList aliveItems = new ArrayList(); + + while (itemIterator.hasNext()) { + Element itemEl = (Element) itemIterator.next(); + Attribute id = itemEl.attribute("id"); + Element statusEl = itemEl.element("status"); + String cpuIdle = statusEl.element("cpu-idle").getText(); + String cpuInUse = statusEl.element("cpu-inuse").getText(); + String memIdle = statusEl.element("mem-idle").getText(); + String memInUse = statusEl.element("mem-inuse").getText(); + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, + cpuInUse, memIdle, memInUse); + ManagerItem item = new ManagerItem(resources); + aliveItems.add(item); + } + return aliveItems; } private void callIamAlive() { diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java index e0d4219f..2ec9272d 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java @@ -64,7 +64,7 @@ public boolean accept(Packet packet) { } }, callback); - managerXmppComponent.iAmAlive(ManagerTestHelper.AUTH_TOKEN); + managerXmppComponent.iAmAlive(); Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); Element element = packet.getElement().element("query"); @@ -86,8 +86,7 @@ public boolean accept(Packet packet) { } @Test - public void testWhoIsAlive() throws XMPPException, InterruptedException, - ComponentException { + public void testWhoIsAlive() throws Exception { managerXmppComponent = managerTestHelper .initializeXMPPManagerComponent(false); final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); @@ -129,13 +128,12 @@ public boolean accept(Packet packet) { ManagerTestHelper.WHOISALIVE_NAMESPACE); Assert.assertEquals(1, managerXmppComponent.getManagerFacade() - .getManagerModel().getMembers().size()); + .getMembers().size()); xmppClient.disconnect(); } @Test - public void testCallIAmAlive() throws XMPPException, InterruptedException, - ComponentException { + public void testCallIAmAlive() throws Exception { final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); final Semaphore semaphore = new Semaphore(0); @@ -195,8 +193,7 @@ public boolean accept(Packet packet) { } @Test - public void testCallWhoIsAlive() throws XMPPException, - InterruptedException, ComponentException { + public void testCallWhoIsAlive() throws Exception { final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); final Semaphore semaphore = new Semaphore(0); final PacketListener callbackWhoIsAlive = new PacketListener() { @@ -231,7 +228,7 @@ public boolean accept(Packet packet) { .initializeXMPPManagerComponent(true); Assert.assertTrue(semaphore.tryAcquire(20000, TimeUnit.MILLISECONDS)); Assert.assertEquals(1, managerXmppComponent.getManagerFacade() - .getManagerModel().getMembers().size()); + .getMembers().size()); xmppClient.disconnect(); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java index b2bfe2f5..f92da73b 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java @@ -1,78 +1,66 @@ package org.fogbowcloud.manager.xmpp; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; +import java.util.Properties; import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.ManagerItem; -import org.fogbowcloud.manager.core.model.ManagerModel; import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.model.RendezvousItemCopy; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.xmpp.packet.IQ; public class TestManagerFacade { - ManagerModel managerModel; ManagerFacade managerFacade; ManagerTestHelper managerTestHelper; @Before - public void setUp() { - managerModel = new ManagerModel(); - managerFacade = new ManagerFacade(managerModel); + public void setUp() throws Exception { + managerFacade = new ManagerFacade(new Properties()); managerTestHelper = new ManagerTestHelper(); } @Test(expected = IllegalArgumentException.class) - public void testConstructorException() { + public void testConstructorException() throws Exception { new ManagerFacade(null); } - @Test - public void testConstructor() { - ManagerFacade managerFacade2 = new ManagerFacade(managerModel); - Assert.assertEquals(managerModel, managerFacade2.getManagerModel()); - } - @Test public void testGet0ItemsFromIQ() { - IQ iq = managerTestHelper - .createWhoIsAliveResponse(new ArrayList(), new IQ()); - List members = managerFacade.getItemsFromIQ(iq); - Assert.assertEquals(0, members.size()); - Assert.assertEquals(0, managerFacade.getManagerModel().getMembers() - .size()); + managerFacade.updateMembers(new LinkedList()); + Assert.assertEquals(0, managerFacade.getMembers().size()); } @Test public void testGet1ItemFromIQ() { - ArrayList items = new ArrayList(); - items.add(new RendezvousItemCopy(managerTestHelper.getResources())); - IQ iq = managerTestHelper.createWhoIsAliveResponse(items, new IQ()); - List members = managerFacade.getItemsFromIQ(iq); + ManagerItem managerItem = new ManagerItem(managerTestHelper.getResources()); + List items = new LinkedList(); + items.add(managerItem); + managerFacade.updateMembers(items); + + List members = managerFacade.getMembers(); Assert.assertEquals(1, members.size()); Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); - Assert.assertEquals(1, managerFacade.getManagerModel().getMembers() - .size()); + Assert.assertEquals(1, managerFacade.getMembers().size()); } @Test public void testGetManyItemsFromIQ() { - ArrayList items = new ArrayList(); + ArrayList items = new ArrayList(); for (int i = 0; i < 10; i++) { - items.add(new RendezvousItemCopy(managerTestHelper.getResources())); + items.add(new ManagerItem(managerTestHelper.getResources())); } - IQ iq = managerTestHelper.createWhoIsAliveResponse(items, new IQ()); - List members = managerFacade.getItemsFromIQ(iq); + managerFacade.updateMembers(items); + + List members = managerFacade.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { Assert.assertEquals("abc", members.get(0).getResourcesInfo() .getId()); } - Assert.assertEquals(10, managerFacade.getManagerModel().getMembers() - .size()); + Assert.assertEquals(10, managerFacade.getMembers().size()); } } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java index 565c98ea..2a01c3c5 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java @@ -3,11 +3,14 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.Properties; import org.dom4j.Attribute; import org.dom4j.Element; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; import org.jamppa.client.plugin.xep0077.XEP0077; @@ -25,10 +28,10 @@ public class ManagerTestHelper { private static final String CLIENT_ADRESS = "client@test.com"; private static final String CLIENT_PASS = "password"; private static final String SMACK_ENDING = "/Smack"; + private static final String TOKEN = "token"; public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String MANAGER_COMPONENT_PASS = "password"; - public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; @@ -87,13 +90,24 @@ public XMPPClient createXMPPClient() throws XMPPException { } public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) - throws ComponentException { + throws Exception { + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + + Properties properties = new Properties(); + properties.put("federation.user.name", "fogbow"); + properties.put("federation.user.password", "fogbow"); + + ManagerFacade managerFacade = new ManagerFacade(properties); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setIdentityPlugin(identityPlugin); + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, - computePlugin); - Mockito.when(computePlugin.getResourcesInfo(AUTH_TOKEN)).thenReturn( - getResources()); + managerFacade); + Mockito.when(computePlugin.getResourcesInfo(TOKEN)).thenReturn(getResources()); + Mockito.when(identityPlugin.getToken("fogbow", "fogbow")).thenReturn(TOKEN); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -101,7 +115,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) managerXmppComponent.connect(); managerXmppComponent.process(); if (init) { - managerXmppComponent.init(AUTH_TOKEN); + managerXmppComponent.init(); } return managerXmppComponent; } From 6882e6bc4c454897061c8ddc33f71bad5006b0ae Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 22 Apr 2014 16:49:00 -0300 Subject: [PATCH 015/185] Refactoring OpenStackIdentityPlugin to throw OCCIException --- .../manager/core/ManagerFacade.java | 7 +--- .../openstack/OpenStackIdentityPlugin.java | 32 ++++++++++--------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 505fdafa..1f98d2dc 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -24,7 +24,6 @@ import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; -import org.restlet.resource.ResourceException; public class ManagerFacade { @@ -72,11 +71,7 @@ public ResourcesInfo getResourcesInfo() { } public String getUser(String authToken) { - try { - return identityPlugin.getUser(authToken); - } catch (ResourceException e) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } + return identityPlugin.getUser(authToken); } public List getRequestsFromUser(String authToken) { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 27ccfec5..75518efb 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -13,10 +13,12 @@ import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.json.JSONException; import org.json.JSONObject; -import org.restlet.resource.ResourceException; public class OpenStackIdentityPlugin implements IdentityPlugin { @@ -29,10 +31,10 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String ACCESS_KEYSTONE = "Access"; public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; - + private static String V3_ENDPOINT_PATH = "/v3/auth/tokens/"; private static String V2_ENDPOINT_PATH = "/v2.0/tokens"; - + private String v2Endpoint; private String v3Endpoint; @@ -53,14 +55,14 @@ public String getUser(String authToken) { String.valueOf(Charsets.UTF_8)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new ResourceException(HttpStatus.SC_NOT_FOUND); + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } return getUserNameUserFromJson(responseStr); } catch (Exception e) { - throw new ResourceException(HttpStatus.SC_BAD_REQUEST); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } } @@ -81,25 +83,25 @@ public String getToken(String username, String password) { JSONObject rootMain = new JSONObject(); rootMain.put(AUTH_KEYSTONE, rootAuth); httpPost.setEntity(new StringEntity(rootMain.toString(), HTTP.UTF_8)); - + HttpResponse response = httpClient.execute(httpPost); String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); - + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } - + return getTokenFromJson(responseStr); } catch (Exception e) { - throw new ResourceException(HttpStatus.SC_BAD_REQUEST); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } } private String getUserNameUserFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - return root.getJSONObject(TOKEN_KEYSTONE) - .getJSONObject(USER_KEYSTONE).getString(NAME_KEYSTONE); + return root.getJSONObject(TOKEN_KEYSTONE).getJSONObject(USER_KEYSTONE) + .getString(NAME_KEYSTONE); } catch (JSONException e) { return null; } @@ -108,8 +110,8 @@ private String getUserNameUserFromJson(String responseStr) { private String getTokenFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - return root.getJSONObject(ACCESS_KEYSTONE) - .getJSONObject(TOKEN_KEYSTONE).getString(ID_KEYSTONE); + return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) + .getString(ID_KEYSTONE); } catch (JSONException e) { return null; } From 776144aafd39b5e329d343308084456c6e855b8a Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 22 Apr 2014 22:12:08 +0200 Subject: [PATCH 016/185] Fixes most of the OCCI tests. --- .../fogbowcloud/manager/core/ManagerFacade.java | 6 +++--- .../manager/occi/TestDeleteCompute.java | 1 - .../manager/occi/TestDeleteRequest.java | 8 ++++++-- .../manager/occi/TestGetCompute.java | 1 - .../manager/occi/TestGetRequest.java | 8 ++++++-- .../manager/occi/TestOCCIApplication.java | 12 +++++++----- .../manager/occi/TestPostRequest.java | 8 ++++++-- .../manager/occi/model/RequestHelper.java | 17 +++++++++-------- 8 files changed, 37 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 1f98d2dc..dbdc1237 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -28,7 +28,7 @@ public class ManagerFacade { private static final Logger LOGGER = Logger.getLogger(ManagerFacade.class); - protected static final long PERIOD = 50; + public static final long SCHEDULER_PERIOD = 50; private final Timer timer = new Timer(); private List members = new LinkedList(); @@ -38,7 +38,7 @@ public class ManagerFacade { private IdentityPlugin identityPlugin; private Properties properties; - public ManagerFacade(Properties properties) throws Exception { + public ManagerFacade(Properties properties) { this.properties = properties; if (properties == null) { throw new IllegalArgumentException(); @@ -180,7 +180,7 @@ private void submitRequests() { public void run() { checkAndSubmitOpenRequests(); } - }, 0, PERIOD); + }, 0, SCHEDULER_PERIOD); } private void checkAndSubmitOpenRequests() { diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 0908092d..3ce312b2 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -26,7 +26,6 @@ public void setup() throws Exception { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); this.requestHelper.initializeComponent(computePlugin, identityPlugin); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index 390f5053..a97a4cd8 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -16,7 +16,10 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; @@ -40,8 +43,9 @@ public void setup() throws Exception { .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(RequestHelper.INVALID_TOKEN)).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); } @@ -201,7 +205,7 @@ public void testDeleteRequestNotFound() throws URISyntaxException, HttpException public void testDeleteWithInvalidToken() throws URISyntaxException, HttpException, IOException { HttpDelete delete = new HttpDelete(RequestHelper.URI_FOGBOW_REQUEST); delete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "invalid_token"); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.INVALID_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(delete); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 55528df3..09746d14 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -37,7 +37,6 @@ public void setup() throws Exception { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); this.requestHelper.initializeComponent(computePlugin, identityPlugin); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index a87b7a5b..53ae4844 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -18,8 +18,11 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.model.ComputeApplication; import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; @@ -48,9 +51,10 @@ public void setup() throws Exception { Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(RequestHelper.INVALID_TOKEN)).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); requestHelper.initializeComponent(computePlugin, identityPlugin); } @@ -83,7 +87,7 @@ public void testGetRequestPlainContent() throws URISyntaxException, HttpExceptio public void testGetRequestInvalidToken() throws URISyntaxException, HttpException, IOException { HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, "invalid_token"); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.INVALID_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 14b4e5ca..a5bc1a98 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -4,7 +4,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -34,7 +36,8 @@ public class TestOCCIApplication { @SuppressWarnings("unchecked") @Before public void setUp() { - occiApplication = new OCCIApplication(); + ManagerFacade managerFacade = new ManagerFacade(new Properties()); + occiApplication = new OCCIApplication(managerFacade); // default instance count value is 1 xOCCIAtt = new HashMap(); @@ -47,12 +50,11 @@ public void setUp() { Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( RequestHelper.USER_MOCK); - occiApplication.setIdentityPlugin(identityPlugin); - occiApplication.setComputePlugin(computePlugin); + managerFacade.setIdentityPlugin(identityPlugin); + managerFacade.setComputePlugin(computePlugin); } @Test @@ -82,7 +84,7 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { Assert.assertEquals("", requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); - Thread.sleep(OCCIApplication.PERIOD); + Thread.sleep(ManagerFacade.SCHEDULER_PERIOD); Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertEquals(expectedInstanceId, requestDetails.getInstanceId()); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index cc54f28f..177be89c 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -14,7 +14,10 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; @@ -38,8 +41,9 @@ public void setup() throws Exception { .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.isValidToken(RequestHelper.ACCESS_TOKEN)).thenReturn(true); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(RequestHelper.INVALID_TOKEN)).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); } @@ -166,7 +170,7 @@ public void testPostInvalidAcessTokenRequest() throws URISyntaxException, HttpEx Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, "invalid_acess_token"); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.INVALID_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java index 0c191f5f..99c94771 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java @@ -5,19 +5,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; import java.util.StringTokenizer; import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; -import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; -import org.fogbowcloud.manager.occi.request.Request; -import org.mockito.Mockito; import org.restlet.Component; import org.restlet.data.Protocol; @@ -26,21 +25,23 @@ public class RequestHelper { private Component component; public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; + public static final String INVALID_TOKEN = "invalid-token"; public static final String CONTENT_TYPE_OCCI = "text/occi"; public static final String URI_FOGBOW_REQUEST = "http://localhost:8182/request"; public static final String URI_FOGBOW_COMPUTE = "http://localhost:8182/compute/"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; + public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); - OCCIApplication application = new OCCIApplication(); - application.setComputePlugin(computePlugin); - application.setIdentityPlugin(identityPlugin); - - component.getDefaultHost().attach(application); + ManagerFacade facade = new ManagerFacade(new Properties()); + facade.setComputePlugin(computePlugin); + facade.setIdentityPlugin(identityPlugin); + + component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); } From 8bb76c1331f7574d80d9589b10d235889a5b40f0 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 22 Apr 2014 17:20:47 -0300 Subject: [PATCH 017/185] Implement throw OCCIException where we were only logging in OpenStackComputePlugin --- .../openstack/OpenStackComputePlugin.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index fc1dace0..49bc38cb 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -124,14 +124,16 @@ public Instance getInstance(String authToken, String instanceId) { } // return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); return null; - } catch (URISyntaxException e) { + } catch (URISyntaxException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (HttpException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (IOException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } - return null; } public List getInstances(String authToken) { @@ -149,12 +151,14 @@ public List getInstances(String authToken) { return null; } catch (URISyntaxException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (HttpException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (IOException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } - return null; } public void removeInstances(String authToken) { @@ -169,10 +173,13 @@ public void removeInstances(String authToken) { } } catch (URISyntaxException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (HttpException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (IOException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } } @@ -192,10 +199,13 @@ public void removeInstance(String authToken, String instanceId) { } } catch (URISyntaxException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (HttpException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (IOException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } } From 40867d509ce7fd358c2589eb77278b6f529da2b1 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 22 Apr 2014 17:45:14 -0300 Subject: [PATCH 018/185] Implementing Instace. Unfinished. --- .../manager/occi/request/Instance.java | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java index 19554171..74f00cd5 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java @@ -1,5 +1,114 @@ package org.fogbowcloud.manager.occi.request; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.Resource; + public class Instance { + private String PREFIX_DEFAULT_INSTANCE = "X-OCCI-Location: "; + + private String id; + private String details; + private List resources; + private Map attributes; + + public Instance() { + } + + public Instance parseIds(String textResponse) { + Instance instance = new Instance(); + instance.setId(textResponse.replace(PREFIX_DEFAULT_INSTANCE , "").trim()); + return instance; + } + + public Instance parseDetails(String textResponse) { + + String[] lines = textResponse.split("/n"); + for (String line : lines) { + + if (line.contains("Category:")) { + String[] BlockLine = line.split(";"); + + String[] blockValues; + String term = ""; + String scheme = ""; + String catClass = ""; + String title = ""; + String rel = ""; + String location = ""; + List attributes = new ArrayList(); + List actions = new ArrayList(); + + for (String block: BlockLine) { + + if(block.contains("Category:")) { + blockValues = block.split(":"); + term = blockValues[1].trim(); + }else if(block.contains("Link:")) { + //TODO create new class Link + } + else { + blockValues = block.split("="); + if (blockValues[0].contains("scheme")) { + scheme = blockValues[1].replace("\"", "").trim(); + }else if (blockValues[0].contains("class")) { + catClass = blockValues[1].replace("\"", "").trim(); + }else if (blockValues[0].contains("title")) { + title = blockValues[1].replace("\"", "").trim(); + }else if (blockValues[0].contains("rel")) { + rel = blockValues[1].replace("\"", "").trim(); + }else if (blockValues[0].contains("location")) { + location = blockValues[1].replace("\"", "").trim(); + }else if (blockValues[0].contains("attributes")) { + String[] attributesValues = blockValues[1].replace("\"", "").split(" "); + for (String attribute : attributesValues) { + attributes.add(attribute); + } + }else if (blockValues[0].contains("actions")) { + String[] attributesValues = blockValues[1].replace("\"", "").split(" "); + for (String action : attributesValues) { + actions.add(action); + } + } + } + } + Category category = new Category(term, scheme, catClass); + this.resources.add(new Resource(category, attributes, actions, location, title, rel)); +// new Resource(category, supportedAtt, actions, location, title, rel); + }else if (line.contains("Link:")){ + + }else if (line.contains("X-OCCI-Attribute:")){ + + } + } + + Instance instance = new Instance(); + instance.setDetails(textResponse); + return instance; + } + + public String toOCCIMassageFormatLocation(){ + return PREFIX_DEFAULT_INSTANCE + this.id; + } + + public String toOCCIMassageFormatDetails(){ + //TODO temporary + return this.details; + } + + public void setId(String id) { + this.id = id; + } + + public void setDetails(String details) { + this.details = details; + } + + public String getDetails(){ + return this.details; + } } From a5707d85665c8cc73ee1d4501b47fb8df36546a5 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 23 Apr 2014 06:40:04 +0200 Subject: [PATCH 019/185] Added first bits for federation requests. Moving stuff around. --- .../java/org/fogbowcloud/manager/Main.java | 1 + .../manager/core/FederationMemberPicker.java | 11 ++ .../manager/core/ManagerFacade.java | 108 +++++++++++++----- .../manager/core/RoundRobinMemberPicker.java | 17 +++ ...ManagerItem.java => FederationMember.java} | 4 +- .../manager/core/model/ManagerModel.java | 20 ---- .../manager/core/plugins/ComputePlugin.java | 2 +- .../openstack/OpenStackComputePlugin.java | 2 +- .../manager/occi/OCCIApplication.java | 4 +- .../{ => instance}/ComputeServerResource.java | 3 +- .../occi/{request => instance}/Instance.java | 2 +- .../{ => request}/RequestServerResource.java | 7 +- .../manager/xmpp/ManagerXmppComponent.java | 22 ++-- .../manager/occi/TestDeleteCompute.java | 2 +- .../manager/occi/TestDeleteRequest.java | 2 +- .../manager/occi/TestGetCompute.java | 2 +- .../manager/occi/TestGetRequest.java | 4 +- .../manager/occi/TestOCCIApplication.java | 4 +- .../manager/occi/TestPostRequest.java | 2 +- .../manager/occi/core/TestHeaderUtils.java | 2 +- .../occi/plugins/TestComputeOpenStack.java | 15 +-- .../occi/plugins/TestIdentityOpenStack.java | 2 +- .../TestRequestServerResource.java | 4 +- .../{model => util}/ComputeApplication.java | 2 +- .../{model => util}/KeystoneApplication.java | 2 +- .../occi/{model => util}/PluginHelper.java | 4 +- .../occi/{model => util}/RequestHelper.java | 2 +- ...gerItem.java => TestFederationMember.java} | 14 +-- .../manager/xmpp/TestManagerComponent.java | 4 +- .../manager/xmpp/TestManagerFacade.java | 18 +-- .../manager/xmpp/TestManagerModel.java | 67 ----------- .../{model => util}/ManagerTestHelper.java | 2 +- .../{model => util}/RendezvousItemCopy.java | 2 +- 33 files changed, 173 insertions(+), 186 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java create mode 100644 src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java rename src/main/java/org/fogbowcloud/manager/core/model/{ManagerItem.java => FederationMember.java} (92%) delete mode 100644 src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java rename src/main/java/org/fogbowcloud/manager/occi/{ => instance}/ComputeServerResource.java (94%) rename src/main/java/org/fogbowcloud/manager/occi/{request => instance}/Instance.java (98%) rename src/main/java/org/fogbowcloud/manager/occi/{ => request}/RequestServerResource.java (94%) rename src/test/java/org/fogbowcloud/manager/occi/{ => request}/TestRequestServerResource.java (97%) rename src/test/java/org/fogbowcloud/manager/occi/{model => util}/ComputeApplication.java (99%) rename src/test/java/org/fogbowcloud/manager/occi/{model => util}/KeystoneApplication.java (99%) rename src/test/java/org/fogbowcloud/manager/occi/{model => util}/PluginHelper.java (93%) rename src/test/java/org/fogbowcloud/manager/occi/{model => util}/RequestHelper.java (98%) rename src/test/java/org/fogbowcloud/manager/xmpp/{TestManagerItem.java => TestFederationMember.java} (83%) delete mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java rename src/test/java/org/fogbowcloud/manager/xmpp/{model => util}/ManagerTestHelper.java (99%) rename src/test/java/org/fogbowcloud/manager/xmpp/{model => util}/RendezvousItemCopy.java (96%) diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 3e2ed2d2..1dbdfdf9 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -34,6 +34,7 @@ public static void main(String[] args) throws Exception { facade); xmpp.connect(); xmpp.process(false); + facade.setPacketSender(xmpp); OCCIApplication application = new OCCIApplication(facade); diff --git a/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java new file mode 100644 index 00000000..697ac331 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java @@ -0,0 +1,11 @@ +package org.fogbowcloud.manager.core; + +import java.util.List; + +import org.fogbowcloud.manager.core.model.FederationMember; + +public interface FederationMemberPicker { + + public FederationMember pick(List members); + +} diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index dbdc1237..8c46a7eb 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -4,13 +4,15 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import org.apache.log4j.Logger; -import org.fogbowcloud.manager.core.model.ManagerItem; +import org.dom4j.Element; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; @@ -19,24 +21,31 @@ import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.request.Instance; +import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; +import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; +import org.jamppa.component.PacketSender; +import org.xmpp.packet.IQ; public class ManagerFacade { private static final Logger LOGGER = Logger.getLogger(ManagerFacade.class); - public static final long SCHEDULER_PERIOD = 50; + public static final long SCHEDULER_PERIOD = 30000; + private boolean scheduled = false; private final Timer timer = new Timer(); - private List members = new LinkedList(); + + private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); + private FederationMemberPicker memberPicker = new RoundRobinMemberPicker(); private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; private Properties properties; + private PacketSender packetSender; public ManagerFacade(Properties properties) { this.properties = properties; @@ -53,14 +62,14 @@ public void setIdentityPlugin(IdentityPlugin identityPlugin) { this.identityPlugin = identityPlugin; } - public void updateMembers(List members) { + public void updateMembers(List members) { if (members == null) { throw new IllegalArgumentException(); } this.members = members; } - public List getMembers() { + public List getMembers() { return members; } @@ -153,29 +162,73 @@ public List createRequests(String authToken, List categories, currentRequests.add(request); requests.addRequest(user, request); } + if (!scheduled) { + scheduleRequests(); + } + return currentRequests; } - private void submitRemoteRequest(Request request) { - // TODO Auto-generated method stub - + private boolean submitRemoteRequest(Request request) { + FederationMember member = memberPicker.pick(getMembers()); + IQ iq = new IQ(); + iq.setTo(member.getResourcesInfo().getId()); + Element queryEl = iq.getElement().addElement("query", + ManagerXmppComponent.REQUEST_NAMESPACE); + for (Category category : request.getCategories()) { + Element categoryEl = queryEl.addElement("category"); + categoryEl.addElement("class").setText(category.getCatClass()); + categoryEl.addElement("term").setText(category.getTerm()); + categoryEl.addElement("scheme").setText(category.getScheme()); + } + for (Entry xOCCIEntry : request.getxOCCIAtt().entrySet()) { + Element attributeEl = queryEl.addElement("attribute"); + attributeEl.addAttribute("var", xOCCIEntry.getKey()); + attributeEl.addElement("value").setText(xOCCIEntry.getValue()); + } + IQ response = (IQ) packetSender.syncSendPacket(iq); + if (response.getError() != null) { + return false; + } + request.setState(RequestState.FULFILLED); + request.setInstanceId(response.getElement() + .element("query") + .element("instance") + .elementText("id")); + return true; } - private void submitLocalRequest(Request request) { - // Removing all xOCCI Attribute specific to request type + private boolean submitLocalRequest(Request request) { Map xOCCIAtt = request.getxOCCIAtt(); for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } - String instanceLocation = computePlugin.requestInstance(request.getAuthToken(), - request.getCategories(), xOCCIAtt); + + String instanceLocation = null; + try { + instanceLocation = computePlugin.requestInstance(request.getAuthToken(), + request.getCategories(), xOCCIAtt); + } catch (OCCIException e) { + if (e.getStatus().equals(ErrorType.BAD_REQUEST) + && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + return false; + } else { + //TODO Think this through... + request.setState(RequestState.FAILED); + LOGGER.warn("Request failed locally for an unknown reason.", e); + return true; + } + } + instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); request.setInstanceId(instanceLocation); request.setState(RequestState.FULFILLED); + return true; } - private void submitRequests() { - timer.schedule(new TimerTask() { + private void scheduleRequests() { + scheduled = true; + timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkAndSubmitOpenRequests(); @@ -184,22 +237,17 @@ public void run() { } private void checkAndSubmitOpenRequests() { + boolean allFulfilled = true; for (Request request : requests.get(RequestState.OPEN)) { - // TODO before submit request we have to check - try { - submitLocalRequest(request); - request.setState(RequestState.FULFILLED); - } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.BAD_REQUEST) - && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { - submitRemoteRequest(request); // FIXME submit more than - // one at same time - } else { - // TODO set state to fail? - request.setState(RequestState.FAILED); - // throw e; - } - } + allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); } + if (allFulfilled) { + timer.cancel(); + scheduled = false; + } + } + + public void setPacketSender(PacketSender packetSender) { + this.packetSender = packetSender; } } diff --git a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java new file mode 100644 index 00000000..18411680 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java @@ -0,0 +1,17 @@ +package org.fogbowcloud.manager.core; + +import java.util.List; + +import org.fogbowcloud.manager.core.model.FederationMember; + +public class RoundRobinMemberPicker implements FederationMemberPicker { + + @Override + public FederationMember pick(List members) { + if (members.isEmpty()) { + return null; + } + return members.iterator().next(); + } + +} diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java b/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java similarity index 92% rename from src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java rename to src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java index 27598898..6090e6c5 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ManagerItem.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java @@ -7,14 +7,14 @@ import org.fogbowcloud.manager.xmpp.core.model.DateUtils; -public class ManagerItem { +public class FederationMember { public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; private long lastTime; private ResourcesInfo resourcesInfo; - public ManagerItem(ResourcesInfo resourcesInfo) { + public FederationMember(ResourcesInfo resourcesInfo) { if (resourcesInfo == null) { throw new IllegalArgumentException(); } diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java b/src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java deleted file mode 100644 index 0b880212..00000000 --- a/src/main/java/org/fogbowcloud/manager/core/model/ManagerModel.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.fogbowcloud.manager.core.model; - -import java.util.LinkedList; -import java.util.List; - -public class ManagerModel { - - private List managers = new LinkedList(); - - public void update(List managers) { - if (managers == null) { - throw new IllegalArgumentException(); - } - this.managers = managers; - } - - public List getMembers() { - return managers; - } -} diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java index e0fe05e5..e4da1550 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java @@ -5,7 +5,7 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.occi.request.Instance; +import org.fogbowcloud.manager.occi.instance.Instance; public interface ComputePlugin { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 49bc38cb..ddde7f81 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -26,7 +26,7 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.request.Instance; +import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.RequestConstants; public class OpenStackComputePlugin implements ComputePlugin { diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 7fc094a8..f8536c19 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -5,8 +5,10 @@ import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.occi.request.Instance; +import org.fogbowcloud.manager.occi.instance.ComputeServerResource; +import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestServerResource; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; diff --git a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java similarity index 94% rename from src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java rename to src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java index ba39c4a1..79aa1d53 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java @@ -1,7 +1,8 @@ -package org.fogbowcloud.manager.occi; +package org.fogbowcloud.manager.occi.instance; import java.util.List; +import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Delete; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java similarity index 98% rename from src/main/java/org/fogbowcloud/manager/occi/request/Instance.java rename to src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 74f00cd5..93e406c6 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.request; +package org.fogbowcloud.manager.occi.instance; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java similarity index 94% rename from src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java rename to src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java index ebbffb59..5243be0b 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java @@ -1,10 +1,11 @@ -package org.fogbowcloud.manager.occi; +package org.fogbowcloud.manager.occi.request; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; @@ -12,10 +13,6 @@ import org.fogbowcloud.manager.occi.core.Resource; import org.fogbowcloud.manager.occi.core.ResourceRepository; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.request.Request; -import org.fogbowcloud.manager.occi.request.RequestAttribute; -import org.fogbowcloud.manager.occi.request.RequestConstants; -import org.fogbowcloud.manager.occi.request.RequestType; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Delete; import org.restlet.resource.Get; diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 08afe749..72dab59d 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -8,10 +8,9 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; -import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.jamppa.component.XMPPComponent; -import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; import org.xmpp.packet.IQ.Type; @@ -19,6 +18,8 @@ public class ManagerXmppComponent extends XMPPComponent { public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; + public static final String REQUEST_NAMESPACE = "http://fogbowcloud.org/manager/request"; + private static long PERIOD = 100; private ManagerFacade managerFacade; private final Timer timer = new Timer(); @@ -30,13 +31,8 @@ public ManagerXmppComponent(String jid, String password, String server, this.managerFacade = managerFacade; } - @Override - public void connect() throws ComponentException { - super.connect(); - } - public void init() { - callIamAlive(); + scheduleIamAlive(); } public void iAmAlive() { @@ -60,17 +56,17 @@ public void whoIsalive() { iq.getElement().addElement("query", WHOISALIVE_NAMESPACE); IQ response = (IQ) this.syncSendPacket(iq); - ArrayList members = getMembersFromIQ(response); + ArrayList members = getMembersFromIQ(response); managerFacade.updateMembers(members); } @SuppressWarnings("unchecked") - private static ArrayList getMembersFromIQ( + private static ArrayList getMembersFromIQ( IQ responseFromWhoIsAliveIQ) { Element queryElement = responseFromWhoIsAliveIQ.getElement().element( "query"); Iterator itemIterator = queryElement.elementIterator("item"); - ArrayList aliveItems = new ArrayList(); + ArrayList aliveItems = new ArrayList(); while (itemIterator.hasNext()) { Element itemEl = (Element) itemIterator.next(); @@ -82,13 +78,13 @@ private static ArrayList getMembersFromIQ( String memInUse = statusEl.element("mem-inuse").getText(); ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, cpuInUse, memIdle, memInUse); - ManagerItem item = new ManagerItem(resources); + FederationMember item = new FederationMember(resources); aliveItems.add(item); } return aliveItems; } - private void callIamAlive() { + private void scheduleIamAlive() { timer.schedule(new TimerTask() { @Override public void run() { diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 3ce312b2..2bf4f225 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -7,7 +7,7 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.model.RequestHelper; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; import org.junit.Before; import org.junit.Ignore; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index a97a4cd8..d13a61ef 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -20,9 +20,9 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 09746d14..c933678a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -15,9 +15,9 @@ import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 53ae4844..c16bbbc0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -23,11 +23,11 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.model.ComputeApplication; -import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; +import org.fogbowcloud.manager.occi.util.ComputeApplication; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index a5bc1a98..38ce347d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -11,12 +11,12 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; -import org.fogbowcloud.manager.occi.model.ComputeApplication; -import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; +import org.fogbowcloud.manager.occi.util.ComputeApplication; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index 177be89c..8543ade1 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -18,9 +18,9 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java index 2abc0468..bb05bb1f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java @@ -2,8 +2,8 @@ import java.util.List; -import org.fogbowcloud.manager.occi.model.RequestHelper; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index f6ae7dc0..343bba94 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -12,9 +12,10 @@ import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.model.ComputeApplication; -import org.fogbowcloud.manager.occi.model.PluginHelper; +import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.util.ComputeApplication; +import org.fogbowcloud.manager.occi.util.PluginHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -75,17 +76,17 @@ public void testRequestAValidInstance() { computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); - String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, + Instance instance = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); - Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instanceDetails, + Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instance, ComputeApplication.CORE_ATTRIBUTE_OCCI))); - Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instanceDetails, + Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instance, ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); - Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instanceDetails, + Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instance, ComputeApplication.ARCHITECTURE_ATTRIBUTE_OCCI))); Assert.assertEquals("server-" + FIRST_INSTANCE_ID, - getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); + getAttValueFromDetails(instance, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } private String getAttValueFromDetails(String instanceDetails, String attName) { diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index c3bc62c2..c54fad40 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -3,7 +3,7 @@ import java.util.Properties; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; -import org.fogbowcloud.manager.occi.model.PluginHelper; +import org.fogbowcloud.manager.occi.util.PluginHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestRequestServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java similarity index 97% rename from src/test/java/org/fogbowcloud/manager/occi/TestRequestServerResource.java rename to src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java index bbbf109a..f57a6fc6 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestRequestServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java @@ -1,14 +1,14 @@ -package org.fogbowcloud.manager.occi; +package org.fogbowcloud.manager.occi.request; import java.util.Map; -import org.fogbowcloud.manager.occi.RequestServerResource; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.request.RequestServerResource; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java similarity index 99% rename from src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java rename to src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index 67ad4215..35a72a96 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.model; +package org.fogbowcloud.manager.occi.util; import java.util.ArrayList; import java.util.HashMap; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java similarity index 99% rename from src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java rename to src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index f408bbb0..ae0cb3a9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.model; +package org.fogbowcloud.manager.occi.util; import java.io.IOException; import java.util.HashMap; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java similarity index 93% rename from src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java rename to src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 1ba57477..a1ed4a2f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -1,8 +1,8 @@ -package org.fogbowcloud.manager.occi.model; +package org.fogbowcloud.manager.occi.util; import java.util.List; -import org.fogbowcloud.manager.occi.model.ComputeApplication.InstanceIdGenerator; +import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; import org.mockito.Mockito; import org.restlet.Component; import org.restlet.data.Protocol; diff --git a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java similarity index 98% rename from src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java rename to src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java index 99c94771..f86bf89d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/model/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.occi.model; +package org.fogbowcloud.manager.occi.util; import java.io.IOException; import java.util.ArrayList; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java similarity index 83% rename from src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java rename to src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java index 8847d175..61b1831f 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerItem.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java @@ -4,14 +4,14 @@ import java.text.SimpleDateFormat; import java.util.Date; -import org.fogbowcloud.manager.core.model.ManagerItem; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -public class TestManagerItem { +public class TestFederationMember { private ResourcesInfo resources; private String DATE = "2000-10-31T01:30:00.000+0000"; @@ -25,7 +25,7 @@ public void setUp() { @Test(expected = IllegalArgumentException.class) public void testInvalidResources() { - new ManagerItem(null); + new FederationMember(null); } @Test(expected = IllegalArgumentException.class) @@ -60,15 +60,15 @@ public void testNullResourcesMemInUse() { @Test public void testConstructor() { - ManagerItem managerItem = new ManagerItem(resources); + FederationMember managerItem = new FederationMember(resources); Assert.assertEquals(resources, managerItem.getResourcesInfo()); } @Test public void getFormattedTime() throws ParseException { - ManagerItem managerItem = new ManagerItem(resources); + FederationMember managerItem = new FederationMember(resources); SimpleDateFormat dateFormat = new SimpleDateFormat( - ManagerItem.ISO_8601_DATE_FORMAT); + FederationMember.ISO_8601_DATE_FORMAT); Date date = dateFormat.parse(DATE); Long lastTime = date.getTime(); managerItem.setLastTime(lastTime); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java index 2ec9272d..2a5c6cde 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java @@ -8,8 +8,8 @@ import java.util.concurrent.TimeUnit; import org.dom4j.Element; -import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.model.RendezvousItemCopy; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.RendezvousItemCopy; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java index f92da73b..4e5d468e 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java @@ -6,8 +6,8 @@ import java.util.Properties; import org.fogbowcloud.manager.core.ManagerFacade; -import org.fogbowcloud.manager.core.model.ManagerItem; -import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -30,18 +30,18 @@ public void testConstructorException() throws Exception { @Test public void testGet0ItemsFromIQ() { - managerFacade.updateMembers(new LinkedList()); + managerFacade.updateMembers(new LinkedList()); Assert.assertEquals(0, managerFacade.getMembers().size()); } @Test public void testGet1ItemFromIQ() { - ManagerItem managerItem = new ManagerItem(managerTestHelper.getResources()); - List items = new LinkedList(); + FederationMember managerItem = new FederationMember(managerTestHelper.getResources()); + List items = new LinkedList(); items.add(managerItem); managerFacade.updateMembers(items); - List members = managerFacade.getMembers(); + List members = managerFacade.getMembers(); Assert.assertEquals(1, members.size()); Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); Assert.assertEquals(1, managerFacade.getMembers().size()); @@ -49,13 +49,13 @@ public void testGet1ItemFromIQ() { @Test public void testGetManyItemsFromIQ() { - ArrayList items = new ArrayList(); + ArrayList items = new ArrayList(); for (int i = 0; i < 10; i++) { - items.add(new ManagerItem(managerTestHelper.getResources())); + items.add(new FederationMember(managerTestHelper.getResources())); } managerFacade.updateMembers(items); - List members = managerFacade.getMembers(); + List members = managerFacade.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { Assert.assertEquals("abc", members.get(0).getResourcesInfo() diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java deleted file mode 100644 index cf18346a..00000000 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerModel.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.fogbowcloud.manager.xmpp; - -import java.util.LinkedList; -import java.util.List; - -import org.fogbowcloud.manager.core.model.ManagerItem; -import org.fogbowcloud.manager.core.model.ManagerModel; -import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.fogbowcloud.manager.xmpp.model.ManagerTestHelper; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -public class TestManagerModel { - - ManagerTestHelper managerTestHelper; - private ManagerModel managerModel; - private ResourcesInfo resources; - - @Before - public void setUp() { - managerTestHelper = new ManagerTestHelper(); - resources = managerTestHelper.getResources(); - managerModel = new ManagerModel(); - } - - @Test(expected = IllegalArgumentException.class) - public void testUpdateWithException() { - managerModel.update(null); - } - - @Test - public void testUpdateEmptyList() { - List resources = new LinkedList(); - managerModel.update(resources); - Assert.assertEquals(resources, managerModel.getMembers()); - } - - @Test - public void testUpdate1Member() { - List members = new LinkedList(); - members.add(new ManagerItem(resources)); - managerModel.update(members); - Assert.assertEquals(1, members.size()); - Assert.assertEquals(members, managerModel.getMembers()); - } - - - @Test(expected = IllegalArgumentException.class) - public void testUpdateWithIvalidMember() { - List members = new LinkedList(); - members.add(new ManagerItem(null)); - managerModel.update(members); - } - - @Test - public void testUpdateManyMembers() { - List members = new LinkedList(); - for (int i = 0; i < 10; i++) { - resources.setId("" + i); - members.add(new ManagerItem(resources)); - } - managerModel.update(members); - Assert.assertEquals(10, members.size()); - Assert.assertEquals(members, managerModel.getMembers()); - } -} diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java similarity index 99% rename from src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java rename to src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 2a01c3c5..443f1531 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/model/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.xmpp.model; +package org.fogbowcloud.manager.xmpp.util; import java.util.ArrayList; import java.util.Iterator; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java similarity index 96% rename from src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java rename to src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java index 1f8f08db..0a9f3a7a 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/model/RendezvousItemCopy.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.xmpp.model; +package org.fogbowcloud.manager.xmpp.util; import java.text.SimpleDateFormat; import java.util.Date; From d8f0f787fbb6c98f6bf19141f15381144c86cdd1 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 23 Apr 2014 11:45:32 -0300 Subject: [PATCH 020/185] Implementing Instance and refatoring tests --- .../openstack/OpenStackComputePlugin.java | 44 +++-- .../occi/instance/ComputeServerResource.java | 40 +++-- .../manager/occi/instance/Instance.java | 160 +++++++++++++----- .../manager/occi/core/TestInstance.java | 45 +++++ .../occi/plugins/TestComputeOpenStack.java | 35 ++-- .../manager/occi/util/ComputeApplication.java | 6 +- 6 files changed, 232 insertions(+), 98 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index ddde7f81..c967b3f0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -36,7 +36,7 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; private static final String CLASS_COMPUTE = "kind"; private static final String COMPUTE_ENDPOINT = "/compute"; - + public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; public static final String CIRROS_IMAGE_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; @@ -45,22 +45,21 @@ public class OpenStackComputePlugin implements ComputePlugin { public OpenStackComputePlugin(Properties properties) { this.computeEndpoint = properties.getProperty("compute_openstack_url") + COMPUTE_ENDPOINT; - fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory( - "compute_openstack_flavor_small", properties)); - fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, createFlavorCategory( - "compute_openstack_flavor_medium", properties)); - fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, createFlavorCategory( - "compute_openstack_flavor_large", properties)); + fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, + createFlavorCategory("compute_openstack_flavor_small", properties)); + fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, + createFlavorCategory("compute_openstack_flavor_medium", properties)); + fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, + createFlavorCategory("compute_openstack_flavor_large", properties)); fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category( CIRROS_IMAGE_TERM, OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); } - + private static Category createFlavorCategory(String flavorPropName, Properties properties) { return new Category(properties.getProperty(flavorPropName), - "http://schemas.openstack.org/template/resource#", - OCCIHeaders.MIXIN_CLASS); + "http://schemas.openstack.org/template/resource#", OCCIHeaders.MIXIN_CLASS); } - + @Override public String requestInstance(String authToken, List categories, Map xOCCIAtt) { @@ -122,9 +121,10 @@ public Instance getInstance(String authToken, String instanceId) { } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } -// return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - return null; - } catch (URISyntaxException e) { + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + return Instance.parseInstanceDetails(responseStr); + } catch (URISyntaxException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } catch (HttpException e) { @@ -147,8 +147,9 @@ public List getInstances(String authToken) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } -// return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - return null; + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + return returnInstances(responseStr); } catch (URISyntaxException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); @@ -161,6 +162,17 @@ public List getInstances(String authToken) { } } + private List returnInstances(String responseStr) { + List instances = new ArrayList(); + String[] lines = responseStr.split("\n"); + for (String line : lines) { + if (line.contains(Instance.PREFIX_DEFAULT_INSTANCE)) { + instances.add(Instance.parseInstanceId(line)); + } + } + return instances; + } + public void removeInstances(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java index 79aa1d53..45497024 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java @@ -4,54 +4,52 @@ import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.ServerResource; -public class ComputeServerResource extends ServerResource{ +public class ComputeServerResource extends ServerResource { @Get - public String fetch() { + public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); -// HeaderUtils.checkOCCIContentType(req.getHeaders()); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); - String idVM = (String) getRequestAttributes().get("instanceId"); + String instanceId = (String) getRequestAttributes().get("instanceId"); - if (idVM == null) { - application.getInstances(authToken); + if (instanceId == null) { + return generateResponse(application.getInstances(authToken)); } -// return application.getInstance(authToken, idVM); - return null; + return application.getInstance(authToken, instanceId).toOCCIMassageFormatDetails(); } - + @Delete public String remove() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); - String idVM = (String) getRequestAttributes().get("instanceId"); + String instanceId = (String) getRequestAttributes().get("instanceId"); - if (idVM == null) { -// return application.removeInstances(authToken); - return null; + if (instanceId == null) { + application.removeInstances(authToken); + return ResponseConstants.OK; } -// return application.removeInstance(authToken, idVM); - return null; + application.removeInstance(authToken, instanceId); + return ResponseConstants.OK; } - + @Post public String post() { return null; } - - protected static String generateResponse(List instances, HttpRequest req) { - String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); + + protected static String generateResponse(List instances) { String response = ""; - for (String location : instances) { - response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + location + "\n"; + for (Instance intance : instances) { + response += HeaderUtils.X_OCCI_LOCATION + intance.toOCCIMassageFormatLocation() + "\n"; } if (response.equals("")) { response = "Empty"; diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 93e406c6..59c5f319 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.occi.instance; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -9,29 +10,42 @@ public class Instance { - private String PREFIX_DEFAULT_INSTANCE = "X-OCCI-Location: "; + public static String PREFIX_DEFAULT_INSTANCE = "X-OCCI-Location: "; + private static String PREFIX_DEFAULT_ATTRIBUTE = "X-OCCI-Attribute: "; + private static String CATEGORY = "Category:"; private String id; - private String details; private List resources; + private Link link; private Map attributes; public Instance() { } - public Instance parseIds(String textResponse) { - Instance instance = new Instance(); - instance.setId(textResponse.replace(PREFIX_DEFAULT_INSTANCE , "").trim()); - return instance; + public Instance(String id) { + this.id = id; + } + + public Instance(List resources, Map attributes, Link link) { + this.resources = resources; + this.attributes = attributes; + this.link = link; } - public Instance parseDetails(String textResponse) { + public static Instance parseInstanceId(String textResponse) { + return new Instance(textResponse.replace(PREFIX_DEFAULT_INSTANCE , "").trim()); + } + + public static Instance parseInstanceDetails(String textResponse) { + List resources = new ArrayList(); + Map attributes = new HashMap(); + Link link = null; - String[] lines = textResponse.split("/n"); + String[] lines = textResponse.split("\n"); for (String line : lines) { - + System.out.println("Line = " + line); if (line.contains("Category:")) { - String[] BlockLine = line.split(";"); + String[] blockLine = line.split(";"); String[] blockValues; String term = ""; @@ -40,18 +54,14 @@ public Instance parseDetails(String textResponse) { String title = ""; String rel = ""; String location = ""; - List attributes = new ArrayList(); - List actions = new ArrayList(); + List attributesResource = new ArrayList(); + List actionsResource = new ArrayList(); - for (String block: BlockLine) { - - if(block.contains("Category:")) { + for (String block: blockLine) { + if(block.contains(CATEGORY)) { blockValues = block.split(":"); term = blockValues[1].trim(); - }else if(block.contains("Link:")) { - //TODO create new class Link - } - else { + } else { blockValues = block.split("="); if (blockValues[0].contains("scheme")) { scheme = blockValues[1].replace("\"", "").trim(); @@ -66,29 +76,27 @@ public Instance parseDetails(String textResponse) { }else if (blockValues[0].contains("attributes")) { String[] attributesValues = blockValues[1].replace("\"", "").split(" "); for (String attribute : attributesValues) { - attributes.add(attribute); + attributesResource.add(attribute); } }else if (blockValues[0].contains("actions")) { - String[] attributesValues = blockValues[1].replace("\"", "").split(" "); - for (String action : attributesValues) { - actions.add(action); + String[] actionsValues = blockValues[1].replace("\"", "").split(" "); + for (String action : actionsValues) { + actionsResource.add(action); } } } - } + } Category category = new Category(term, scheme, catClass); - this.resources.add(new Resource(category, attributes, actions, location, title, rel)); -// new Resource(category, supportedAtt, actions, location, title, rel); - }else if (line.contains("Link:")){ - - }else if (line.contains("X-OCCI-Attribute:")){ + resources.add(new Resource(category, attributesResource, actionsResource, location, title, rel)); + }else if (line.contains("Link")){ + link = Link.parseLink(line); + }else if (line.contains("X-OCCI-Attribute: ")){ + String[] blockLine = line.replace(PREFIX_DEFAULT_ATTRIBUTE, "").split("="); + attributes.put(blockLine[0], blockLine[1].replace("\"", "").trim()); } - } - - Instance instance = new Instance(); - instance.setDetails(textResponse); - return instance; + } + return new Instance(resources, attributes, link); } public String toOCCIMassageFormatLocation(){ @@ -96,19 +104,91 @@ public String toOCCIMassageFormatLocation(){ } public String toOCCIMassageFormatDetails(){ - //TODO temporary - return this.details; + String messageFormat = ""; + for (Resource resource : this.resources) { + messageFormat += CATEGORY + " " + resource.toHeader() + "\n"; + } + if(link != null){ + messageFormat += this.link.toOCCIMessageFormatLink() + "\n"; + } + for (String key : this.attributes.keySet()) { + messageFormat += PREFIX_DEFAULT_ATTRIBUTE + key + "=\"" + attributes.get(key) + "\"\n"; + } + + return messageFormat; } public void setId(String id) { this.id = id; } - public void setDetails(String details) { - this.details = details; + public List getResources() { + return resources; } + + public void setResources(List resources) { + this.resources = resources; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + public String getId() { + return id; + } + + public Link getLink() { + return link; + } + + public void setLink(Link link) { + this.link = link; + } - public String getDetails(){ - return this.details; + public static class Link { + + private static final String NAME_LINK = "Link:"; + + private String link; + private Map itens; + + public static Link parseLink(String line){ + Link link = new Link(); + Map itens = new HashMap(); + + String[] blockLine = line.split(";"); + for (String block : blockLine) { + if(block.contains(NAME_LINK)){ + String[] blockValues = block.split(":"); + link.setLink(blockValues[1].replace("\"", "").trim()); + }else{ + String[] blockValues = block.split("="); + itens.put(blockValues[0].replace("\"", "").trim(), blockValues[1].replace("\"", "").trim()); + } + } + link.setItens(itens); + return link; + } + + public String toOCCIMessageFormatLink(){ + String itensMessageFormat = ""; + for (String key : this.itens.keySet()) { + itensMessageFormat += " " + key + "=\"" + this.itens.get(key) + "\";"; + } + return NAME_LINK + " " + this.link + ";" + itensMessageFormat; + } + + public void setLink(String link) { + this.link = link; + } + + public void setItens(Map itens){ + this.itens = itens; + } } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java new file mode 100644 index 00000000..4b17c4d6 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java @@ -0,0 +1,45 @@ +package org.fogbowcloud.manager.occi.core; + +import org.fogbowcloud.manager.occi.instance.Instance; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +public class TestInstance { + + @Test + public void testParteId() { + String textResponse = "X-OCCI-Location: http://localhost:8787/compute/c1490207-6be7-4303-a41c-f8a4b1b9c25d"; + Instance instance = Instance.parseInstanceId(textResponse); + + Assert.assertEquals(textResponse, instance.toOCCIMassageFormatLocation()); + } + + @Ignore + @Test + public void testParseDetails() { + String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infrastructure#\"; class=\"kind\"; " + + "title=\"Compute Resource\"; rel=\"http://schemas.ogf.org/occi/core#resource\"; " + + "location=\"http://localhost:8787/compute/\"; " + + "attributes=\"occi.compute.architecture occi.compute.state{immutable} " + + "occi.compute.speed occi.compute.memory occi.compute.cores occi.compute.hostname\"; " + + "actions=\"http://schemas.ogf.org/occi/infrastructure/compute/action#start http://schemas.ogf.org/occi/infrastructure/compute/action#stop " + + "http://schemas.ogf.org/occi/infrastructure/compute/action#restart " + + "http://schemas.ogf.org/occi/infrastructure/compute/action#suspend\"\n" + + "Category: os_vms; scheme=\"http://schemas.openstack.org/compute/instance#\"; class=\"mixin\"; location=\"http://localhost:8787/os_vms/\"; attributes=\"org.openstack.compute.console.vnc{immutable} org.openstack.compute.state{immutable}\"; actions=\"http://schemas.openstack.org/instance/action#chg_pwd http://schemas.openstack.org/instance/action#create_image\"\n" + + "Category: b4c4322e-1f6c-4cf4-be02-34cc385a3b29; scheme=\"http://schemas.openstack.org/template/os#\"; class=\"mixin\"; title=\"Image: cirros-0.3.1-x86_64-uec\"; rel=\"http://schemas.ogf.org/occi/infrastructure#os_tpl\"; location=\"http://localhost:8787/b4c4322e-1f6c-4cf4-be02-34cc385a3b29/\"\n" + + "Link: ; rel=\"http://schemas.ogf.org/occi/infrastructure#network\"; self=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"; category=\"http://schemas.ogf.org/occi/infrastructure#networkinterface http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface\"; occi.networkinterface.gateway=\"10.0.0.1\"; occi.networkinterface.mac=\"fa:16:3e:5b:9d:4d\"; occi.networkinterface.interface=\"eth0\"; occi.networkinterface.state=\"active\"; occi.networkinterface.allocation=\"static\"; occi.networkinterface.address=\"0.0.0.0\"; occi.core.source=\"/compute/c1490207-6be7-4303-a41c-f8a4b1b9c25d\"; occi.core.target=\"/network/admin\"; occi.core.id=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"\n" + + "X-OCCI-Attribute: org.openstack.compute.console.vnc=\"N/A\"\n" + + "X-OCCI-Attribute: occi.compute.architecture=\"x86\"\n" + + "X-OCCI-Attribute: occi.compute.state=\"inactive\"\n" + + "X-OCCI-Attribute: occi.compute.speed=\"0.0\"\n" + + "X-OCCI-Attribute: org.openstack.compute.state=\"errorz\"\n" + + "X-OCCI-Attribute: occi.compute.memory=\"0.125\"\n" + + "X-OCCI-Attribute: occi.compute.cores=\"1\"\n" + + "X-OCCI-Attribute: occi.compute.hostname=\"server-c1490207-6be7-4303-a41c-f8a4b1b9c25d\"\n" + + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; + Instance instance = Instance.parseInstanceDetails(textResponse); + + Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 343bba94..53cb31ea 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -79,14 +79,14 @@ public void testRequestAValidInstance() { Instance instance = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); - Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instance, + Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), ComputeApplication.CORE_ATTRIBUTE_OCCI))); - Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instance, + Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); - Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instance, + Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), ComputeApplication.ARCHITECTURE_ATTRIBUTE_OCCI))); Assert.assertEquals("server-" + FIRST_INSTANCE_ID, - getAttValueFromDetails(instance, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); + getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } private String getAttValueFromDetails(String instanceDetails, String attName) { @@ -193,7 +193,7 @@ public void testSupportedOCCIAtt() { computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, - FIRST_INSTANCE_ID); + FIRST_INSTANCE_ID).toOCCIMassageFormatDetails(); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } @@ -214,7 +214,7 @@ public void testMoreSupportedOCCIAtts() { computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, - FIRST_INSTANCE_ID); + FIRST_INSTANCE_ID).toOCCIMassageFormatDetails(); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); Assert.assertEquals("inactive", @@ -239,7 +239,7 @@ public void testGetAllInstanceIds() { instanceLocations = getInstanceLocations(computeOpenStack .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(1, instanceLocations.size()); - Assert.assertEquals(URL + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); + Assert.assertEquals(URL + ComputeApplication.TARGET + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); } @Test @@ -264,21 +264,18 @@ public void testGetAllManyInstanceIds() { .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); for (String expectedId : expectedInstanceIds) { - Assert.assertTrue(instanceLocations.contains(URL + "/" + expectedId)); + Assert.assertTrue(instanceLocations.contains(URL + ComputeApplication.TARGET + "/" + expectedId)); } } - private List getInstanceLocations(String instancesFromUser) { - if (instancesFromUser.contains(HeaderUtils.X_OCCI_LOCATION)) { - String[] tokens = instancesFromUser.split("\n"); - List locations = new ArrayList(); - for (int i = 0; i < tokens.length; i++) { - String[] lineTokens = tokens[i].split("Location:"); - locations.add(lineTokens[1].trim()); - } - return locations; + private List getInstanceLocations(List intances) { + List locations = new ArrayList(); + for (Instance instance : intances) { + String instanceMessage = instance.toOCCIMassageFormatLocation(); + String[] lineTokens = instance.toOCCIMassageFormatLocation().split("Location:"); + locations.add(lineTokens[1].trim()); } - return new ArrayList(); + return locations; } @Test @@ -300,7 +297,7 @@ public void testGetInstanceDetails() { .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(1, instanceLocations.size()); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, - FIRST_INSTANCE_ID); + FIRST_INSTANCE_ID).toOCCIMassageFormatDetails(); Assert.assertEquals(FIRST_INSTANCE_ID, getAttValueFromDetails(instanceDetails, ComputeApplication.ID_CORE_ATTRIBUTE_OCCI)); Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instanceDetails, diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index 35a72a96..faa3957e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -238,8 +238,10 @@ public String fetch() { private static String generateResponse(List instances, HttpRequest req) { String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); String response = ""; - for (String location : instances) { - response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + location + "\n"; + if(instances != null){ + for (String location : instances) { + response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + location + "\n"; + } } if (response.equals("")) { response = "Empty"; From 3a8741ac91915fce99fa7be49bc06cef3d9ab4f5 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 14:50:30 -0300 Subject: [PATCH 021/185] Adding flavour and modifying ResourcesInfo --- .../manager/core/model/Flavour.java | 49 +++++++++++++++++++ .../manager/core/model/ResourcesInfo.java | 17 ++++++- 2 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/core/model/Flavour.java diff --git a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java b/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java new file mode 100644 index 00000000..37445d7b --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java @@ -0,0 +1,49 @@ +package org.fogbowcloud.manager.core.model; + +public class Flavour { + + private int capacity; + private String name; + private String cpu; + private String mem; + + public Flavour(String name, String cpu, String mem, int capacity) { + this.setName(name); + this.setCpu(cpu); + this.setMem(mem); + this.setCapacity(capacity); + + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCpu() { + return cpu; + } + + public void setCpu(String cpu) { + this.cpu = cpu; + } + + public String getMem() { + return mem; + } + + public void setMem(String mem) { + this.mem = mem; + } +} diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index 018318ac..e627538a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -1,5 +1,8 @@ package org.fogbowcloud.manager.core.model; +import java.util.LinkedList; +import java.util.List; + public class ResourcesInfo { private String id; @@ -7,14 +10,16 @@ public class ResourcesInfo { private String cpuInUse; private String memIdle; private String memInUse; - + private List flavours; + public ResourcesInfo(String id, String cpuIdle, String cpuInUse, - String memIdle, String memInUse) { + String memIdle, String memInUse, List flavours) { setId(id); setCpuIdle(cpuIdle); setCpuInUse(cpuInUse); setMemIdle(memIdle); setMemInUse(memInUse); + this.setFlavours(flavours); } public String getId() { @@ -75,4 +80,12 @@ public void setMemInUse(String memInUse) { } this.memInUse = memInUse; } + + public List getFlavours() { + return flavours; + } + + public void setFlavours(List flavours) { + this.flavours = flavours; + } } From cc71b83a6cd2f3418c393da6cad195d0af2ba40e Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 15:27:40 -0300 Subject: [PATCH 022/185] Adding ManagerPacketHelper. --- .../manager/core/model/Flavour.java | 9 +- .../manager/xmpp/ManagerPacketHelper.java | 94 +++++++++++++++++++ .../manager/xmpp/ManagerXmppComponent.java | 66 +++---------- 3 files changed, 111 insertions(+), 58 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java diff --git a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java b/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java index 37445d7b..225f6e01 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java @@ -2,24 +2,23 @@ public class Flavour { - private int capacity; + private Integer capacity; private String name; private String cpu; private String mem; - public Flavour(String name, String cpu, String mem, int capacity) { + public Flavour(String name, String cpu, String mem, Integer capacity) { this.setName(name); this.setCpu(cpu); this.setMem(mem); this.setCapacity(capacity); - } - public int getCapacity() { + public Integer getCapacity() { return capacity; } - public void setCapacity(int capacity) { + public void setCapacity(Integer capacity) { this.capacity = capacity; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java new file mode 100644 index 00000000..7bc1948b --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -0,0 +1,94 @@ +package org.fogbowcloud.manager.xmpp; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; + +import org.dom4j.Attribute; +import org.dom4j.Element; +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.Flavour; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.jamppa.component.PacketSender; +import org.xmpp.packet.IQ; +import org.xmpp.packet.IQ.Type; + +public class ManagerPacketHelper { + + public static void iAmAlive(ResourcesInfo resourcesInfo, + String rendezvousAddress, PacketSender packetSender) { + IQ iq = new IQ(Type.get); + iq.setTo(rendezvousAddress); + Element statusEl = iq.getElement() + .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE) + .addElement("status"); + statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); + statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); + statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); + statusEl.addElement("mem-inuse").setText(resourcesInfo.getMemInUse()); + List flavours = resourcesInfo.getFlavours(); + for (Flavour f : flavours) { + Element flavorElement = statusEl.addElement("flavor"); + flavorElement.addElement("name").setText(f.getName()); + flavorElement.addElement("cpu").setText(f.getCpu()); + flavorElement.addElement("mem").setText(f.getMem()); + flavorElement.addElement("capacity").setText( + f.getCapacity().toString()); + } + statusEl.addElement("cert"); + packetSender.syncSendPacket(iq); + } + + public static List whoIsalive(String rendezvousAddress, + PacketSender packetSender) { + IQ iq = new IQ(Type.get); + iq.setTo(rendezvousAddress); + iq.getElement().addElement("query", + ManagerXmppComponent.WHOISALIVE_NAMESPACE); + IQ response = (IQ) packetSender.syncSendPacket(iq); + + ArrayList members = getMembersFromIQ(response); + return members; + } + + @SuppressWarnings("unchecked") + private static ArrayList getMembersFromIQ( + IQ responseFromWhoIsAliveIQ) { + Element queryElement = responseFromWhoIsAliveIQ.getElement().element( + "query"); + Iterator itemIterator = queryElement.elementIterator("item"); + ArrayList aliveItems = new ArrayList(); + + while (itemIterator.hasNext()) { + Element itemEl = (Element) itemIterator.next(); + Attribute id = itemEl.attribute("id"); + Element statusEl = itemEl.element("status"); + String cpuIdle = statusEl.element("cpu-idle").getText(); + String cpuInUse = statusEl.element("cpu-inuse").getText(); + String memIdle = statusEl.element("mem-idle").getText(); + String memInUse = statusEl.element("mem-inuse").getText(); + + List flavoursList = new LinkedList(); + Iterator flavourIterator = itemEl + .elementIterator("flavor"); + while (flavourIterator.hasNext()) { + Element flavour = (Element) itemIterator.next(); + String name = flavour.element("name").getText(); + String cpu = flavour.element("cpu").getText(); + String mem = flavour.element("mem").getText(); + int capacity = Integer.parseInt(flavour.element("capacity") + .getText()); + Flavour flavor = new Flavour(name, cpu, mem, capacity); + flavoursList.add(flavor); + } + + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, + cpuInUse, memIdle, memInUse, flavoursList); + FederationMember item = new FederationMember(resources); + aliveItems.add(item); + } + return aliveItems; + } + +} diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 72dab59d..b49f9ffb 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -1,30 +1,23 @@ package org.fogbowcloud.manager.xmpp; -import java.util.ArrayList; -import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; -import org.dom4j.Attribute; -import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; -import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.jamppa.component.XMPPComponent; -import org.xmpp.packet.IQ; -import org.xmpp.packet.IQ.Type; +import org.xmpp.packet.Packet; public class ManagerXmppComponent extends XMPPComponent { public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; public static final String REQUEST_NAMESPACE = "http://fogbowcloud.org/manager/request"; - + private static long PERIOD = 100; private ManagerFacade managerFacade; private final Timer timer = new Timer(); private String rendezvousAddress; - + public ManagerXmppComponent(String jid, String password, String server, int port, ManagerFacade managerFacade) { super(jid, password, server, port); @@ -34,54 +27,21 @@ public ManagerXmppComponent(String jid, String password, String server, public void init() { scheduleIamAlive(); } - + public void iAmAlive() { - IQ iq = new IQ(Type.get); - iq.setTo(rendezvousAddress); - iq.setFrom(getJID()); - Element statusEl = iq.getElement() - .addElement("query", IAMALIVE_NAMESPACE).addElement("status"); - ResourcesInfo resourcesInfo = managerFacade.getResourcesInfo(); - statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); - statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); - statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); - statusEl.addElement("mem-inuse").setText(resourcesInfo.getMemInUse()); - this.syncSendPacket(iq); + ManagerPacketHelper.iAmAlive(managerFacade.getResourcesInfo(), + rendezvousAddress, this); } - public void whoIsalive() { - IQ iq = new IQ(Type.get); - iq.setTo(rendezvousAddress); - iq.setFrom(getJID()); - iq.getElement().addElement("query", WHOISALIVE_NAMESPACE); - IQ response = (IQ) this.syncSendPacket(iq); - - ArrayList members = getMembersFromIQ(response); - managerFacade.updateMembers(members); + @Override + protected void send(Packet packet) { + packet.setFrom(getJID()); + super.send(packet); } - - @SuppressWarnings("unchecked") - private static ArrayList getMembersFromIQ( - IQ responseFromWhoIsAliveIQ) { - Element queryElement = responseFromWhoIsAliveIQ.getElement().element( - "query"); - Iterator itemIterator = queryElement.elementIterator("item"); - ArrayList aliveItems = new ArrayList(); - while (itemIterator.hasNext()) { - Element itemEl = (Element) itemIterator.next(); - Attribute id = itemEl.attribute("id"); - Element statusEl = itemEl.element("status"); - String cpuIdle = statusEl.element("cpu-idle").getText(); - String cpuInUse = statusEl.element("cpu-inuse").getText(); - String memIdle = statusEl.element("mem-idle").getText(); - String memInUse = statusEl.element("mem-inuse").getText(); - ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse); - FederationMember item = new FederationMember(resources); - aliveItems.add(item); - } - return aliveItems; + public void whoIsalive() { + managerFacade.updateMembers(ManagerPacketHelper.whoIsalive( + rendezvousAddress, this)); } private void scheduleIamAlive() { From 4a93d188b75df082832fd2d9ac50332b48eb0963 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 23 Apr 2014 15:40:40 -0300 Subject: [PATCH 023/185] Implement fake getResourcesInfo in OpenStackComputePlugin --- .../manager/core/ManagerFacade.java | 4 ++- .../manager/core/model/Flavour.java | 1 + .../openstack/OpenStackComputePlugin.java | 28 +++++++++++++++++-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 8c46a7eb..24e651ca 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -76,7 +76,9 @@ public List getMembers() { public ResourcesInfo getResourcesInfo() { String token = identityPlugin.getToken(properties.getProperty("federation.user.name"), properties.getProperty("federation.user.password")); - return computePlugin.getResourcesInfo(token); + ResourcesInfo resourcesInfo = computePlugin.getResourcesInfo(token); + resourcesInfo.setId(properties.getProperty("xmpp_jid")); + return resourcesInfo; } public String getUser(String authToken) { diff --git a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java b/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java index 37445d7b..eb8c5a57 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.core.model; +//TODO rename this class to Flavor public class Flavour { private int capacity; diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index c967b3f0..74b636e9 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -19,6 +19,8 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; +import org.apache.log4j.varia.FallbackErrorHandler; +import org.fogbowcloud.manager.core.model.Flavour; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -223,7 +225,29 @@ public void removeInstance(String authToken, String instanceId) { @Override public ResourcesInfo getResourcesInfo(String authToken) { - // TODO Auto-generated method stub - return null; + // TODO Fake resources + String cpuIdle = "1000"; + String cpuInUse = "0"; + String memIdle = "2048000"; + String memInUse = "0"; + return new ResourcesInfo(null, cpuIdle, cpuInUse, memIdle, memInUse, getFlavors(cpuIdle, memIdle)); + } + + private List getFlavors(String cpuIdleStr, String memIdleStr) { + int cpuIdle = Integer.parseInt(cpuIdleStr); + int memIdle = Integer.parseInt(memIdleStr); + List flavors = new ArrayList(); + + //flavors + int capacity = Math.min(cpuIdle / 1, memIdle / 2048); + Flavour smallFlavor = new Flavour(RequestConstants.SMALL_TERM, "1", "2048", capacity); + capacity = Math.min(cpuIdle / 2, memIdle / 4096); + Flavour mediumFlavor = new Flavour(RequestConstants.MEDIUM_TERM, "2", "4096", capacity); + capacity = Math.min(cpuIdle / 4, memIdle / 8192); + Flavour largeFlavor = new Flavour(RequestConstants.LARGE_TERM, "4", "8192", capacity); + flavors.add(smallFlavor); + flavors.add(mediumFlavor); + flavors.add(largeFlavor); + return flavors; } } From 8a70e8290a6d3a8d4530a22e79fccd170bf2194f Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 23 Apr 2014 20:50:27 +0200 Subject: [PATCH 024/185] Proper round robin. --- .../org/fogbowcloud/manager/core/RoundRobinMemberPicker.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java index 18411680..9e2c7755 100644 --- a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java @@ -6,12 +6,15 @@ public class RoundRobinMemberPicker implements FederationMemberPicker { + private int current = -1; + @Override public FederationMember pick(List members) { if (members.isEmpty()) { return null; } - return members.iterator().next(); + current = (current + 1) % members.size(); + return members.get(current); } } From bd7d53eda012cd68bbd4a564c2c16bbda99da9c9 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 15:53:31 -0300 Subject: [PATCH 025/185] Fixing old tests to new architecture. --- .../manager/xmpp/TestFederationMember.java | 12 ++-- .../manager/xmpp/util/ManagerTestHelper.java | 64 ++++++++++++++----- 2 files changed, 55 insertions(+), 21 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java index 61b1831f..1587fa6d 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java @@ -3,8 +3,10 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.LinkedList; import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.Flavour; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; @@ -31,31 +33,31 @@ public void testInvalidResources() { @Test(expected = IllegalArgumentException.class) public void testNullResourceId() { new ResourcesInfo(null, "cpuIdle", - "cpuInUse", "memIdle", "memInUse"); + "cpuInUse", "memIdle", "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesCpuIdle() { new ResourcesInfo("id", null, - "cpuInUse", "memIdle", "memInUse"); + "cpuInUse", "memIdle", "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesCpuInUse() { new ResourcesInfo("id", "CpuIdle", - null, "memIdle", "memInUse"); + null, "memIdle", "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesMemIdle() { new ResourcesInfo("id", "CpuIdle", - "cpuInUse", null, "memInUse"); + "cpuInUse", null, "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesMemInUse() { new ResourcesInfo("id", "CpuIdle", - "cpuInUse", "memIdle", null); + "cpuInUse", "memIdle", null, new LinkedList()); } @Test diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 443f1531..310e0901 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -2,12 +2,14 @@ import java.util.ArrayList; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.model.Flavour; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; @@ -42,8 +44,10 @@ public class ManagerTestHelper { private ManagerXmppComponent managerXmppComponent; public ResourcesInfo getResources() { + List flavours = new LinkedList(); + flavours.add(new Flavour("samll", "cpu", "mem", 2)); ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", - "value3", "value4"); + "value3", "value4", flavours); return resources; } @@ -52,21 +56,34 @@ public IQ createWhoIsAliveResponse(ArrayList aliveIds, IQ resultIQ = IQ.createResultIQ(iq); Element queryElement = resultIQ.getElement().addElement("query", WHOISALIVE_NAMESPACE); - for (RendezvousItemCopy rendezvouItem : aliveIds) { + for (RendezvousItemCopy rendezvousItem : aliveIds) { Element itemEl = queryElement.addElement("item"); - itemEl.addAttribute("id", rendezvouItem.getResourcesInfo().getId()); + itemEl.addAttribute("id", rendezvousItem.getResourcesInfo().getId()); Element statusEl = itemEl.addElement("status"); statusEl.addElement("cpu-idle").setText( - rendezvouItem.getResourcesInfo().getCpuIdle()); + rendezvousItem.getResourcesInfo().getCpuIdle()); statusEl.addElement("cpu-inuse").setText( - rendezvouItem.getResourcesInfo().getCpuInUse()); + rendezvousItem.getResourcesInfo().getCpuInUse()); statusEl.addElement("mem-idle").setText( - rendezvouItem.getResourcesInfo().getMemIdle()); + rendezvousItem.getResourcesInfo().getMemIdle()); statusEl.addElement("mem-inuse").setText( - rendezvouItem.getResourcesInfo().getMemInUse()); + rendezvousItem.getResourcesInfo().getMemInUse()); + + List flavours = rendezvousItem.getResourcesInfo() + .getFlavours(); + for (Flavour f : flavours) { + Element flavorElement = statusEl.addElement("flavor"); + flavorElement.addElement("name").setText(f.getName()); + flavorElement.addElement("cpu").setText(f.getCpu()); + flavorElement.addElement("mem").setText(f.getMem()); + flavorElement.addElement("capacity").setText( + f.getCapacity().toString()); + } + statusEl.addElement("cert"); statusEl.addElement("updated").setText( - String.valueOf(rendezvouItem.getFormattedTime())); + String.valueOf(rendezvousItem.getFormattedTime())); + // add rendezvous item like it should be } return resultIQ; } @@ -91,23 +108,25 @@ public XMPPClient createXMPPClient() throws XMPPException { public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Exception { - + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - + Properties properties = new Properties(); properties.put("federation.user.name", "fogbow"); properties.put("federation.user.password", "fogbow"); - + ManagerFacade managerFacade = new ManagerFacade(properties); managerFacade.setComputePlugin(computePlugin); managerFacade.setIdentityPlugin(identityPlugin); - + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); - Mockito.when(computePlugin.getResourcesInfo(TOKEN)).thenReturn(getResources()); - Mockito.when(identityPlugin.getToken("fogbow", "fogbow")).thenReturn(TOKEN); + Mockito.when(computePlugin.getResourcesInfo(TOKEN)).thenReturn( + getResources()); + Mockito.when(identityPlugin.getToken("fogbow", "fogbow")).thenReturn( + TOKEN); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -143,10 +162,23 @@ public List getItemsFromIQ(Packet response) { String cpuInUse = statusEl.element("cpu-inuse").getText(); String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); - // String updated = statusEl.element("updated").getText(); + + List flavoursList = new LinkedList(); + Iterator flavourIterator = itemEl + .elementIterator("flavor"); + while (flavourIterator.hasNext()) { + Element flavour = (Element) itemIterator.next(); + String name = flavour.element("name").getText(); + String cpu = flavour.element("cpu").getText(); + String mem = flavour.element("mem").getText(); + int capacity = Integer.parseInt(flavour.element("capacity") + .getText()); + Flavour flavor = new Flavour(name, cpu, mem, capacity); + flavoursList.add(flavor); + } ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse); + cpuInUse, memIdle, memInUse, flavoursList); RendezvousItemCopy item = new RendezvousItemCopy(resources); aliveItems.add(item); } From c53a712ecbe4aa552f93819f81db29bfdb16a3dc Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 23 Apr 2014 21:11:58 +0200 Subject: [PATCH 026/185] Moving xmpp bits to ManagerPacketHelper --- .../manager/core/ManagerFacade.java | 33 +++++-------------- .../manager/xmpp/ManagerPacketHelper.java | 29 ++++++++++++++++ 2 files changed, 37 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 8c46a7eb..891f5311 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -4,14 +4,12 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import org.apache.log4j.Logger; -import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -26,9 +24,8 @@ import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; -import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; +import org.fogbowcloud.manager.xmpp.ManagerPacketHelper; import org.jamppa.component.PacketSender; -import org.xmpp.packet.IQ; public class ManagerFacade { @@ -171,30 +168,16 @@ public List createRequests(String authToken, List categories, private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(getMembers()); - IQ iq = new IQ(); - iq.setTo(member.getResourcesInfo().getId()); - Element queryEl = iq.getElement().addElement("query", - ManagerXmppComponent.REQUEST_NAMESPACE); - for (Category category : request.getCategories()) { - Element categoryEl = queryEl.addElement("category"); - categoryEl.addElement("class").setText(category.getCatClass()); - categoryEl.addElement("term").setText(category.getTerm()); - categoryEl.addElement("scheme").setText(category.getScheme()); - } - for (Entry xOCCIEntry : request.getxOCCIAtt().entrySet()) { - Element attributeEl = queryEl.addElement("attribute"); - attributeEl.addAttribute("var", xOCCIEntry.getKey()); - attributeEl.addElement("value").setText(xOCCIEntry.getValue()); - } - IQ response = (IQ) packetSender.syncSendPacket(iq); - if (response.getError() != null) { + String memberAddress = member.getResourcesInfo().getId(); + + String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, + memberAddress, packetSender); + if (remoteInstanceId == null) { return false; } + request.setState(RequestState.FULFILLED); - request.setInstanceId(response.getElement() - .element("query") - .element("instance") - .elementText("id")); + request.setInstanceId(remoteInstanceId); return true; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 7bc1948b..f1d3fc63 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -4,12 +4,15 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map.Entry; import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavour; import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.request.Request; import org.jamppa.component.PacketSender; import org.xmpp.packet.IQ; import org.xmpp.packet.IQ.Type; @@ -91,4 +94,30 @@ private static ArrayList getMembersFromIQ( return aliveItems; } + public static String remoteRequest(Request request, + String memberAddress, PacketSender packetSender) { + IQ iq = new IQ(); + iq.setTo(memberAddress); + Element queryEl = iq.getElement().addElement("query", + ManagerXmppComponent.REQUEST_NAMESPACE); + for (Category category : request.getCategories()) { + Element categoryEl = queryEl.addElement("category"); + categoryEl.addElement("class").setText(category.getCatClass()); + categoryEl.addElement("term").setText(category.getTerm()); + categoryEl.addElement("scheme").setText(category.getScheme()); + } + for (Entry xOCCIEntry : request.getxOCCIAtt() + .entrySet()) { + Element attributeEl = queryEl.addElement("attribute"); + attributeEl.addAttribute("var", xOCCIEntry.getKey()); + attributeEl.addElement("value").setText(xOCCIEntry.getValue()); + } + IQ response = (IQ) packetSender.syncSendPacket(iq); + if (response.getError() != null) { + return null; + } + return response.getElement().element("query") + .element("instance") + .elementText("id"); + } } From 0c37cfd9e1b443ab950d0108130311819d5d9331 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 23 Apr 2014 16:12:40 -0300 Subject: [PATCH 027/185] Implementing ManagerFacade and request. --- .../manager/core/ManagerFacade.java | 53 +++++++++++++++---- .../manager/occi/request/Request.java | 12 ++++- 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 8c46a7eb..0f711f8a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -106,30 +106,61 @@ private void checkRequestId(String authToken, String requestId) { } public List getInstances(String authToken) { - // TODO check other manager - + // TODO check other manager + return this.computePlugin.getInstances(authToken); } public Instance getInstance(String authToken, String instanceId) { - // TODO check other manager - checkInstanceId(authToken, instanceId); - return this.computePlugin.getInstance(authToken, instanceId); + Request request = getRequestFromInstance(authToken, instanceId); + if(isLocal(request)){ + return this.computePlugin.getInstance(authToken, instanceId); + } else { + return createGetInstanceIQ(authToken, request); + } + } + + private Instance createGetInstanceIQ(String authToken, Request request) { + return null; } public void removeInstances(String authToken) { // TODO check other manager - + this.computePlugin.removeInstances(authToken); } - public void removeInstance(String authToken, String instanceId) { - // TODO check other manager + public void removeInstance(String authToken, String instanceId) { + Request request = getRequestFromInstance(authToken, instanceId); + if(isLocal(request)){ + this.computePlugin.removeInstance(authToken, instanceId); + } else { + createRemoveIQ(authToken, request); + } + } - checkInstanceId(authToken, instanceId); - this.computePlugin.removeInstance(authToken, instanceId); + private void createRemoveIQ(String authToken, Request request) { + // TODO Auto-generated method stub } + public Request getRequestFromInstance(String authToken, String instanceId){ + String user = getUser(authToken); + List userRequests = requests.getByUser(user); + for (Request request : userRequests) { + if (instanceId.equals(request.getInstanceId())) { + return request; + } + } + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } + + private boolean isLocal(Request request) { + if(request.getMemberId() == null){ + return true; + } + return false; + } + private void checkInstanceId(String authToken, String instanceId) { String user = getUser(authToken); List userRequests = requests.getByUser(user); @@ -158,7 +189,7 @@ public List createRequests(String authToken, List categories, for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); Request request = new Request(requestId, authToken, "", RequestState.OPEN, categories, - xOCCIAtt); + xOCCIAtt, null); currentRequests.add(request); requests.addRequest(user, request); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 068e65f9..1c6c1f21 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -10,14 +10,16 @@ public class Request { private String id; private String authToken; private String instanceId; + private String memberId; private RequestState state; private List categories; private Map xOCCIAtt; public Request(String id, String authToken, String instanceId, RequestState state, - List categories, Map xOCCIAtt) { + List categories, Map xOCCIAtt, String memberId) { this.id = id; this.authToken = authToken; + this.memberId = memberId; setInstanceId(instanceId); setState(state); this.categories = categories; @@ -65,4 +67,12 @@ public String getAuthToken() { public Map getxOCCIAtt() { return this.xOCCIAtt; } + + public String getMemberId() { + return memberId; + } + + public void setMemberId(String memberId) { + this.memberId = memberId; + } } \ No newline at end of file From cdcd421b3ef1cfd53f11f171b81f1c109f2c56bc Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 23 Apr 2014 21:36:00 +0200 Subject: [PATCH 028/185] Moving scheduler period to configuration --- manager.conf.example | 7 ++++- .../manager/core/ManagerFacade.java | 11 ++++++-- .../manager/occi/TestOCCIApplication.java | 28 +++++++++++-------- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index 18575df7..8f315c90 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -10,4 +10,9 @@ compute_openstack_flavor_medium=m1-medium compute_openstack_flavor_large=m1-large identity_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackIdentityPlugin -identity_openstack_url=http://localhost:5000 \ No newline at end of file +identity_openstack_url=http://localhost:5000 + +federation.user.name=fogbow +federation.user.password=fogbow + +scheduler_period=30000 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index c9a28783..fa0b5665 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -30,7 +30,7 @@ public class ManagerFacade { private static final Logger LOGGER = Logger.getLogger(ManagerFacade.class); - public static final long SCHEDULER_PERIOD = 30000; + public static final long DEFAULT_SCHEDULER_PERIOD = 30000; private boolean scheduled = false; private final Timer timer = new Timer(); @@ -207,7 +207,7 @@ public List createRequests(String authToken, List categories, List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, authToken, "", RequestState.OPEN, categories, + Request request = new Request(requestId, authToken, null, RequestState.OPEN, categories, xOCCIAtt, null); currentRequests.add(request); requests.addRequest(user, request); @@ -264,12 +264,17 @@ private boolean submitLocalRequest(Request request) { private void scheduleRequests() { scheduled = true; + String schedulerPeriodStr = properties.getProperty( + "scheduler_period"); + long schedulerPeriod = schedulerPeriodStr == null ? + DEFAULT_SCHEDULER_PERIOD : Long.valueOf(schedulerPeriodStr); + timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkAndSubmitOpenRequests(); } - }, 0, SCHEDULER_PERIOD); + }, 0, schedulerPeriod); } private void checkAndSubmitOpenRequests() { diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 38ce347d..dbd6d206 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -24,19 +24,23 @@ public class TestOCCIApplication { - private OCCIApplication occiApplication; - private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" - + RequestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + private static final String INSTANCE_LOCATION = HeaderUtils.X_OCCI_LOCATION + + "http://localhost:" + RequestHelper.ENDPOINT_PORT + + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - private String expectedInstanceId = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "") - .trim(); - + private static final String INSTANCE_ID = INSTANCE_LOCATION.replace( + HeaderUtils.X_OCCI_LOCATION, "").trim(); + private static final Long SCHEDULER_PERIOD = 500L; + + private OCCIApplication occiApplication; private Map xOCCIAtt; @SuppressWarnings("unchecked") @Before public void setUp() { - ManagerFacade managerFacade = new ManagerFacade(new Properties()); + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + ManagerFacade managerFacade = new ManagerFacade(properties); occiApplication = new OCCIApplication(managerFacade); // default instance count value is 1 @@ -47,7 +51,7 @@ public void setUp() { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(instanceLocation); + Mockito.any(Map.class))).thenReturn(INSTANCE_LOCATION); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( @@ -67,7 +71,7 @@ public void testGetRequestDetails() throws InterruptedException { requestId); Assert.assertEquals(requestId, requestDetails.getId()); - Assert.assertEquals("", requestDetails.getInstanceId()); + Assert.assertNull(requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); } @@ -81,13 +85,13 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { requestId); Assert.assertEquals(requestId, requestDetails.getId()); - Assert.assertEquals("", requestDetails.getInstanceId()); + Assert.assertNull(requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); - Thread.sleep(ManagerFacade.SCHEDULER_PERIOD); + Thread.sleep(SCHEDULER_PERIOD * 2); Assert.assertEquals(requestId, requestDetails.getId()); - Assert.assertEquals(expectedInstanceId, requestDetails.getInstanceId()); + Assert.assertEquals(INSTANCE_ID, requestDetails.getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requestDetails.getState()); } From e18e52e22c950b6fd5b6c000d3c0a744de424b85 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 23 Apr 2014 16:40:55 -0300 Subject: [PATCH 029/185] Implement createRemoteRequest, getRemoteRequest and removeRemoteRequest --- .../manager/core/ManagerFacade.java | 98 +++++++++++-------- 1 file changed, 59 insertions(+), 39 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index f56268f1..c9a28783 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -34,7 +34,7 @@ public class ManagerFacade { private boolean scheduled = false; private final Timer timer = new Timer(); - + private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); private FederationMemberPicker memberPicker = new RoundRobinMemberPicker(); @@ -50,11 +50,11 @@ public ManagerFacade(Properties properties) { throw new IllegalArgumentException(); } } - + public void setComputePlugin(ComputePlugin computePlugin) { this.computePlugin = computePlugin; } - + public void setIdentityPlugin(IdentityPlugin identityPlugin) { this.identityPlugin = identityPlugin; } @@ -71,8 +71,7 @@ public List getMembers() { } public ResourcesInfo getResourcesInfo() { - String token = identityPlugin.getToken(properties.getProperty("federation.user.name"), - properties.getProperty("federation.user.password")); + String token = getFederationUserToken(); ResourcesInfo resourcesInfo = computePlugin.getResourcesInfo(token); resourcesInfo.setId(properties.getProperty("xmpp_jid")); return resourcesInfo; @@ -105,18 +104,18 @@ private void checkRequestId(String authToken, String requestId) { } public List getInstances(String authToken) { - // TODO check other manager - + // TODO check other manager + return this.computePlugin.getInstances(authToken); } public Instance getInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); - if(isLocal(request)){ - return this.computePlugin.getInstance(authToken, instanceId); + if (isLocal(request)) { + return this.computePlugin.getInstance(authToken, instanceId); } else { return createGetInstanceIQ(authToken, request); - } + } } private Instance createGetInstanceIQ(String authToken, Request request) { @@ -125,24 +124,24 @@ private Instance createGetInstanceIQ(String authToken, Request request) { public void removeInstances(String authToken) { // TODO check other manager - + this.computePlugin.removeInstances(authToken); } - public void removeInstance(String authToken, String instanceId) { + public void removeInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); - if(isLocal(request)){ - this.computePlugin.removeInstance(authToken, instanceId); + if (isLocal(request)) { + this.computePlugin.removeInstance(authToken, instanceId); } else { createRemoveIQ(authToken, request); - } + } } private void createRemoveIQ(String authToken, Request request) { - // TODO Auto-generated method stub + // TODO Auto-generated method stub } - public Request getRequestFromInstance(String authToken, String instanceId){ + public Request getRequestFromInstance(String authToken, String instanceId) { String user = getUser(authToken); List userRequests = requests.getByUser(user); for (Request request : userRequests) { @@ -150,32 +149,53 @@ public Request getRequestFromInstance(String authToken, String instanceId){ return request; } } - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } - + private boolean isLocal(Request request) { - if(request.getMemberId() == null){ + if (request.getMemberId() == null) { return true; } return false; } - - private void checkInstanceId(String authToken, String instanceId) { - String user = getUser(authToken); - List userRequests = requests.getByUser(user); - for (Request request : userRequests) { - if (instanceId.equals(request.getInstanceId())) { - return; - } - } - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); - } public Request getRequest(String authToken, String requestId) { checkRequestId(authToken, requestId); return requests.get(requestId); } + public String createRemoteRequest(List categories, Map xOCCIAtt) { + String token = getFederationUserToken(); + try { + return computePlugin.requestInstance(token, categories, xOCCIAtt); + } catch (OCCIException e) { + LOGGER.error(e); + return null; + } + } + + // TODO Think about always get new federation user token or store a valid one. + private String getFederationUserToken() { + String token = identityPlugin.getToken(properties.getProperty("federation.user.name"), + properties.getProperty("federation.user.password")); + return token; + } + + public Instance getRemoteInstance(String instanceId) { + String token = getFederationUserToken(); + try { + return computePlugin.getInstance(token, instanceId); + } catch (OCCIException e) { + LOGGER.error(e); + return null; + } + } + + public void removeRemoteInstance(String instanceId) { + String token = getFederationUserToken(); + computePlugin.removeInstance(token, instanceId); + } + public List createRequests(String authToken, List categories, Map xOCCIAtt) { String user = getUser(authToken); @@ -195,20 +215,20 @@ public List createRequests(String authToken, List categories, if (!scheduled) { scheduleRequests(); } - + return currentRequests; } private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(getMembers()); String memberAddress = member.getResourcesInfo().getId(); - - String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, - memberAddress, packetSender); + + String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, memberAddress, + packetSender); if (remoteInstanceId == null) { return false; } - + request.setState(RequestState.FULFILLED); request.setInstanceId(remoteInstanceId); return true; @@ -219,7 +239,7 @@ private boolean submitLocalRequest(Request request) { for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } - + String instanceLocation = null; try { instanceLocation = computePlugin.requestInstance(request.getAuthToken(), @@ -229,13 +249,13 @@ private boolean submitLocalRequest(Request request) { && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { return false; } else { - //TODO Think this through... + // TODO Think this through... request.setState(RequestState.FAILED); LOGGER.warn("Request failed locally for an unknown reason.", e); return true; } } - + instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); request.setInstanceId(instanceLocation); request.setState(RequestState.FULFILLED); From 4e55cf3109ec12d5b056d9ef5aece662e37d1794 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 16:54:18 -0300 Subject: [PATCH 030/185] Fixing managerXmppComponent --- .../manager/xmpp/ManagerPacketHelper.java | 5 ++-- .../manager/xmpp/TestManagerComponent.java | 25 ++++++++++++------- .../manager/xmpp/util/ManagerTestHelper.java | 4 ++- 3 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index f1d3fc63..b30190b2 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -50,7 +50,6 @@ public static List whoIsalive(String rendezvousAddress, iq.getElement().addElement("query", ManagerXmppComponent.WHOISALIVE_NAMESPACE); IQ response = (IQ) packetSender.syncSendPacket(iq); - ArrayList members = getMembersFromIQ(response); return members; } @@ -73,10 +72,10 @@ private static ArrayList getMembersFromIQ( String memInUse = statusEl.element("mem-inuse").getText(); List flavoursList = new LinkedList(); - Iterator flavourIterator = itemEl + Iterator flavourIterator = statusEl .elementIterator("flavor"); while (flavourIterator.hasNext()) { - Element flavour = (Element) itemIterator.next(); + Element flavour = (Element) flavourIterator.next(); String name = flavour.element("name").getText(); String cpu = flavour.element("cpu").getText(); String mem = flavour.element("mem").getText(); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java index 2a5c6cde..ae1715f0 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java @@ -23,10 +23,10 @@ import org.xmpp.packet.Packet; public class TestManagerComponent { - + private ManagerTestHelper managerTestHelper; private ManagerXmppComponent managerXmppComponent; - + @Before public void setUp() throws ComponentException { managerTestHelper = new ManagerTestHelper(); @@ -136,7 +136,7 @@ public boolean accept(Packet packet) { public void testCallIAmAlive() throws Exception { final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); final Semaphore semaphore = new Semaphore(0); - + final PacketListener callbackIAmAlive = new PacketListener() { public void processPacket(Packet packet) { IQ iAmAlive = (IQ) packet; @@ -144,7 +144,7 @@ public void processPacket(Packet packet) { xmppClient.send(IQ.createResultIQ(iAmAlive)); } }; - + final PacketListener callbackWhoIsAlive = new PacketListener() { public void processPacket(Packet packet) { IQ whoIsAlive = (IQ) packet; @@ -156,12 +156,12 @@ public void processPacket(Packet packet) { try { xmppClient.syncSend(iq); } catch (XMPPException e) { - //No problem if exception is throwed + // No problem if exception is throwed } } }; - + xmppClient.on(new PacketFilter() { @Override public boolean accept(Packet packet) { @@ -173,7 +173,7 @@ public boolean accept(Packet packet) { ManagerTestHelper.IAMALIVE_NAMESPACE); } }, callbackIAmAlive); - + xmppClient.on(new PacketFilter() { @Override public boolean accept(Packet packet) { @@ -185,10 +185,14 @@ public boolean accept(Packet packet) { ManagerTestHelper.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); - + managerXmppComponent = managerTestHelper .initializeXMPPManagerComponent(true); Assert.assertTrue(semaphore.tryAcquire(10000, TimeUnit.MILLISECONDS)); + Assert.assertEquals(2, managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().size()); + Assert.assertEquals("small", managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().get(0).getName()); xmppClient.disconnect(); } @@ -207,7 +211,7 @@ public void processPacket(Packet packet) { try { xmppClient.syncSend(iq); } catch (XMPPException e) { - //No problem if exception is throwed + // No problem if exception is throwed } semaphore.release(); } @@ -229,6 +233,9 @@ public boolean accept(Packet packet) { Assert.assertTrue(semaphore.tryAcquire(20000, TimeUnit.MILLISECONDS)); Assert.assertEquals(1, managerXmppComponent.getManagerFacade() .getMembers().size()); + Assert.assertEquals("small", managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().get(0) + .getName()); xmppClient.disconnect(); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 310e0901..9ee9d12f 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -45,7 +45,8 @@ public class ManagerTestHelper { public ResourcesInfo getResources() { List flavours = new LinkedList(); - flavours.add(new Flavour("samll", "cpu", "mem", 2)); + flavours.add(new Flavour("small", "cpu", "mem", 2)); + flavours.add(new Flavour("small", "cpu", "mem", 3)); ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", "value3", "value4", flavours); return resources; @@ -115,6 +116,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) Properties properties = new Properties(); properties.put("federation.user.name", "fogbow"); properties.put("federation.user.password", "fogbow"); + properties.put("xmpp_jid", "manager.test.com"); ManagerFacade managerFacade = new ManagerFacade(properties); managerFacade.setComputePlugin(computePlugin); From b0415d5da945d97712a0ea990946b5b89bbea773 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 17:01:40 -0300 Subject: [PATCH 031/185] Fixing Tests --- .../fogbowcloud/manager/xmpp/TestManagerComponent.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java index ae1715f0..6f9b107c 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java @@ -129,6 +129,10 @@ public boolean accept(Packet packet) { Assert.assertEquals(1, managerXmppComponent.getManagerFacade() .getMembers().size()); + Assert.assertEquals(2, managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().size()); + Assert.assertEquals("small", managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().get(0).getName()); xmppClient.disconnect(); } @@ -156,7 +160,7 @@ public void processPacket(Packet packet) { try { xmppClient.syncSend(iq); } catch (XMPPException e) { - // No problem if exception is throwed + // No problem if exception is thrown } } @@ -189,10 +193,6 @@ public boolean accept(Packet packet) { managerXmppComponent = managerTestHelper .initializeXMPPManagerComponent(true); Assert.assertTrue(semaphore.tryAcquire(10000, TimeUnit.MILLISECONDS)); - Assert.assertEquals(2, managerXmppComponent.getManagerFacade() - .getMembers().get(0).getResourcesInfo().getFlavours().size()); - Assert.assertEquals("small", managerXmppComponent.getManagerFacade() - .getMembers().get(0).getResourcesInfo().getFlavours().get(0).getName()); xmppClient.disconnect(); } From 0c007dd0559cead6b025bbc35686d53c78a67ba0 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 17:09:33 -0300 Subject: [PATCH 032/185] Replacing RendezvousItemcopy with FederationMember --- .../manager/xmpp/TestManagerComponent.java | 20 ++++---- .../manager/xmpp/util/ManagerTestHelper.java | 11 ++-- .../manager/xmpp/util/RendezvousItemCopy.java | 51 ------------------- 3 files changed, 16 insertions(+), 66 deletions(-) delete mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java index 6f9b107c..42f16ea2 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java @@ -8,8 +8,8 @@ import java.util.concurrent.TimeUnit; import org.dom4j.Element; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.RendezvousItemCopy; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; @@ -101,11 +101,11 @@ public void processPacket(Packet packet) { } catch (InterruptedException e) { e.printStackTrace(); } - List aliveIds = new ArrayList(); - aliveIds.add(new RendezvousItemCopy(managerTestHelper + List aliveIds = new ArrayList(); + aliveIds.add(new FederationMember(managerTestHelper .getResources())); IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); + (ArrayList) aliveIds, whoIsAlive); xmppClient.send(iq); } }; @@ -152,11 +152,11 @@ public void processPacket(Packet packet) { final PacketListener callbackWhoIsAlive = new PacketListener() { public void processPacket(Packet packet) { IQ whoIsAlive = (IQ) packet; - List aliveIds = new ArrayList(); - aliveIds.add(new RendezvousItemCopy(managerTestHelper + List aliveIds = new ArrayList(); + aliveIds.add(new FederationMember(managerTestHelper .getResources())); IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); + (ArrayList) aliveIds, whoIsAlive); try { xmppClient.syncSend(iq); } catch (XMPPException e) { @@ -203,11 +203,11 @@ public void testCallWhoIsAlive() throws Exception { final PacketListener callbackWhoIsAlive = new PacketListener() { public void processPacket(Packet packet) { IQ whoIsAlive = (IQ) packet; - List aliveIds = new ArrayList(); - aliveIds.add(new RendezvousItemCopy(managerTestHelper + List aliveIds = new ArrayList(); + aliveIds.add(new FederationMember(managerTestHelper .getResources())); IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); + (ArrayList) aliveIds, whoIsAlive); try { xmppClient.syncSend(iq); } catch (XMPPException e) { diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 9ee9d12f..a2fe2bbd 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -9,6 +9,7 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavour; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -52,12 +53,12 @@ public ResourcesInfo getResources() { return resources; } - public IQ createWhoIsAliveResponse(ArrayList aliveIds, + public IQ createWhoIsAliveResponse(ArrayList aliveIds, IQ iq) { IQ resultIQ = IQ.createResultIQ(iq); Element queryElement = resultIQ.getElement().addElement("query", WHOISALIVE_NAMESPACE); - for (RendezvousItemCopy rendezvousItem : aliveIds) { + for (FederationMember rendezvousItem : aliveIds) { Element itemEl = queryElement.addElement("item"); itemEl.addAttribute("id", rendezvousItem.getResourcesInfo().getId()); @@ -151,10 +152,10 @@ public void shutdown() throws ComponentException { } @SuppressWarnings("unchecked") - public List getItemsFromIQ(Packet response) { + public List getItemsFromIQ(Packet response) { Element queryElement = response.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); - ArrayList aliveItems = new ArrayList(); + ArrayList aliveItems = new ArrayList(); while (itemIterator.hasNext()) { Element itemEl = (Element) itemIterator.next(); @@ -181,7 +182,7 @@ public List getItemsFromIQ(Packet response) { ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, cpuInUse, memIdle, memInUse, flavoursList); - RendezvousItemCopy item = new RendezvousItemCopy(resources); + FederationMember item = new FederationMember(resources); aliveItems.add(item); } return aliveItems; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java deleted file mode 100644 index 0a9f3a7a..00000000 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/RendezvousItemCopy.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.fogbowcloud.manager.xmpp.util; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; - -public class RendezvousItemCopy { - - public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private long lastTime; - private ResourcesInfo resourcesInfo; - - public RendezvousItemCopy(ResourcesInfo resourcesInfo) { - if (resourcesInfo == null) { - throw new IllegalArgumentException(); - } - lastTime = new DateUtils().currentTimeMillis(); - this.resourcesInfo = resourcesInfo; - } - - public ResourcesInfo getResourcesInfo() { - return resourcesInfo; - } - - public long getLastTime() { - return lastTime; - } - - public String getFormattedTime() { - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - - Date date = new Date(lastTime); - - return dateFormatISO8601.format(date); - } - - /** - * This method was implemented just for unit test. - * - * @param lastTime - */ - protected void setLastTime(long lastTime){ - this.lastTime = lastTime; - } -} From e0374c5f072cf1d9d8e0ed5797625353663efebc Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 23 Apr 2014 17:42:02 -0300 Subject: [PATCH 033/185] Refactoring TestOCCIApplication --- .../manager/occi/TestOCCIApplication.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index dbd6d206..7b544dd0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -10,7 +10,10 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; @@ -34,13 +37,14 @@ public class TestOCCIApplication { private OCCIApplication occiApplication; private Map xOCCIAtt; + ManagerFacade managerFacade; @SuppressWarnings("unchecked") @Before public void setUp() { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - ManagerFacade managerFacade = new ManagerFacade(properties); + managerFacade = new ManagerFacade(properties); occiApplication = new OCCIApplication(managerFacade); // default instance count value is 1 @@ -51,7 +55,7 @@ public void setUp() { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_LOCATION); + Mockito.any(Map.class))).thenThrow(new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( @@ -77,6 +81,12 @@ public void testGetRequestDetails() throws InterruptedException { @Test public void testGetRequestDetailsAfterPeriod() throws InterruptedException { + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_LOCATION); + managerFacade.setComputePlugin(computePlugin); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); @@ -87,7 +97,7 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertNull(requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); - + Thread.sleep(SCHEDULER_PERIOD * 2); Assert.assertEquals(requestId, requestDetails.getId()); From cb4a137ad7ee57f07f6a5631c9662747a6a152a6 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 23 Apr 2014 17:48:26 -0300 Subject: [PATCH 034/185] Fixing code style --- .../core/model/{Flavour.java => Flavor.java} | 4 ++-- .../manager/core/model/ResourcesInfo.java | 9 ++++----- .../openstack/OpenStackComputePlugin.java | 12 ++++++------ .../manager/xmpp/ManagerPacketHelper.java | 10 +++++----- .../manager/xmpp/TestFederationMember.java | 12 ++++++------ .../manager/xmpp/util/ManagerTestHelper.java | 17 ++++++++--------- 6 files changed, 31 insertions(+), 33 deletions(-) rename src/main/java/org/fogbowcloud/manager/core/model/{Flavour.java => Flavor.java} (88%) diff --git a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java b/src/main/java/org/fogbowcloud/manager/core/model/Flavor.java similarity index 88% rename from src/main/java/org/fogbowcloud/manager/core/model/Flavour.java rename to src/main/java/org/fogbowcloud/manager/core/model/Flavor.java index 5a3bc161..b7371c82 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/Flavour.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/Flavor.java @@ -1,14 +1,14 @@ package org.fogbowcloud.manager.core.model; //TODO rename this class to Flavor -public class Flavour { +public class Flavor { private Integer capacity; private String name; private String cpu; private String mem; - public Flavour(String name, String cpu, String mem, Integer capacity) { + public Flavor(String name, String cpu, String mem, Integer capacity) { this.setName(name); this.setCpu(cpu); this.setMem(mem); diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index e627538a..cf1151ac 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -1,6 +1,5 @@ package org.fogbowcloud.manager.core.model; -import java.util.LinkedList; import java.util.List; public class ResourcesInfo { @@ -10,10 +9,10 @@ public class ResourcesInfo { private String cpuInUse; private String memIdle; private String memInUse; - private List flavours; + private List flavours; public ResourcesInfo(String id, String cpuIdle, String cpuInUse, - String memIdle, String memInUse, List flavours) { + String memIdle, String memInUse, List flavours) { setId(id); setCpuIdle(cpuIdle); setCpuInUse(cpuInUse); @@ -81,11 +80,11 @@ public void setMemInUse(String memInUse) { this.memInUse = memInUse; } - public List getFlavours() { + public List getFlavours() { return flavours; } - public void setFlavours(List flavours) { + public void setFlavours(List flavours) { this.flavours = flavours; } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 74b636e9..070ccbf8 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -20,7 +20,7 @@ import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.apache.log4j.varia.FallbackErrorHandler; -import org.fogbowcloud.manager.core.model.Flavour; +import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -233,18 +233,18 @@ public ResourcesInfo getResourcesInfo(String authToken) { return new ResourcesInfo(null, cpuIdle, cpuInUse, memIdle, memInUse, getFlavors(cpuIdle, memIdle)); } - private List getFlavors(String cpuIdleStr, String memIdleStr) { + private List getFlavors(String cpuIdleStr, String memIdleStr) { int cpuIdle = Integer.parseInt(cpuIdleStr); int memIdle = Integer.parseInt(memIdleStr); - List flavors = new ArrayList(); + List flavors = new ArrayList(); //flavors int capacity = Math.min(cpuIdle / 1, memIdle / 2048); - Flavour smallFlavor = new Flavour(RequestConstants.SMALL_TERM, "1", "2048", capacity); + Flavor smallFlavor = new Flavor(RequestConstants.SMALL_TERM, "1", "2048", capacity); capacity = Math.min(cpuIdle / 2, memIdle / 4096); - Flavour mediumFlavor = new Flavour(RequestConstants.MEDIUM_TERM, "2", "4096", capacity); + Flavor mediumFlavor = new Flavor(RequestConstants.MEDIUM_TERM, "2", "4096", capacity); capacity = Math.min(cpuIdle / 4, memIdle / 8192); - Flavour largeFlavor = new Flavour(RequestConstants.LARGE_TERM, "4", "8192", capacity); + Flavor largeFlavor = new Flavor(RequestConstants.LARGE_TERM, "4", "8192", capacity); flavors.add(smallFlavor); flavors.add(mediumFlavor); flavors.add(largeFlavor); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index b30190b2..87d33be1 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -9,7 +9,7 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.core.model.Flavour; +import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.request.Request; @@ -30,8 +30,8 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); statusEl.addElement("mem-inuse").setText(resourcesInfo.getMemInUse()); - List flavours = resourcesInfo.getFlavours(); - for (Flavour f : flavours) { + List flavours = resourcesInfo.getFlavours(); + for (Flavor f : flavours) { Element flavorElement = statusEl.addElement("flavor"); flavorElement.addElement("name").setText(f.getName()); flavorElement.addElement("cpu").setText(f.getCpu()); @@ -71,7 +71,7 @@ private static ArrayList getMembersFromIQ( String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); - List flavoursList = new LinkedList(); + List flavoursList = new LinkedList(); Iterator flavourIterator = statusEl .elementIterator("flavor"); while (flavourIterator.hasNext()) { @@ -81,7 +81,7 @@ private static ArrayList getMembersFromIQ( String mem = flavour.element("mem").getText(); int capacity = Integer.parseInt(flavour.element("capacity") .getText()); - Flavour flavor = new Flavour(name, cpu, mem, capacity); + Flavor flavor = new Flavor(name, cpu, mem, capacity); flavoursList.add(flavor); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java index 1587fa6d..3d8ed5fe 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java @@ -6,7 +6,7 @@ import java.util.LinkedList; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.core.model.Flavour; +import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; @@ -33,31 +33,31 @@ public void testInvalidResources() { @Test(expected = IllegalArgumentException.class) public void testNullResourceId() { new ResourcesInfo(null, "cpuIdle", - "cpuInUse", "memIdle", "memInUse", new LinkedList()); + "cpuInUse", "memIdle", "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesCpuIdle() { new ResourcesInfo("id", null, - "cpuInUse", "memIdle", "memInUse", new LinkedList()); + "cpuInUse", "memIdle", "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesCpuInUse() { new ResourcesInfo("id", "CpuIdle", - null, "memIdle", "memInUse", new LinkedList()); + null, "memIdle", "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesMemIdle() { new ResourcesInfo("id", "CpuIdle", - "cpuInUse", null, "memInUse", new LinkedList()); + "cpuInUse", null, "memInUse", new LinkedList()); } @Test(expected = IllegalArgumentException.class) public void testNullResourcesMemInUse() { new ResourcesInfo("id", "CpuIdle", - "cpuInUse", "memIdle", null, new LinkedList()); + "cpuInUse", "memIdle", null, new LinkedList()); } @Test diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index a2fe2bbd..b31db2be 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -10,7 +10,7 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.core.model.Flavour; +import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; @@ -45,9 +45,9 @@ public class ManagerTestHelper { private ManagerXmppComponent managerXmppComponent; public ResourcesInfo getResources() { - List flavours = new LinkedList(); - flavours.add(new Flavour("small", "cpu", "mem", 2)); - flavours.add(new Flavour("small", "cpu", "mem", 3)); + List flavours = new LinkedList(); + flavours.add(new Flavor("small", "cpu", "mem", 2)); + flavours.add(new Flavor("small", "cpu", "mem", 3)); ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", "value3", "value4", flavours); return resources; @@ -72,9 +72,9 @@ public IQ createWhoIsAliveResponse(ArrayList aliveIds, statusEl.addElement("mem-inuse").setText( rendezvousItem.getResourcesInfo().getMemInUse()); - List flavours = rendezvousItem.getResourcesInfo() + List flavours = rendezvousItem.getResourcesInfo() .getFlavours(); - for (Flavour f : flavours) { + for (Flavor f : flavours) { Element flavorElement = statusEl.addElement("flavor"); flavorElement.addElement("name").setText(f.getName()); flavorElement.addElement("cpu").setText(f.getCpu()); @@ -85,7 +85,6 @@ public IQ createWhoIsAliveResponse(ArrayList aliveIds, statusEl.addElement("cert"); statusEl.addElement("updated").setText( String.valueOf(rendezvousItem.getFormattedTime())); - // add rendezvous item like it should be } return resultIQ; } @@ -166,7 +165,7 @@ public List getItemsFromIQ(Packet response) { String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); - List flavoursList = new LinkedList(); + List flavoursList = new LinkedList(); Iterator flavourIterator = itemEl .elementIterator("flavor"); while (flavourIterator.hasNext()) { @@ -176,7 +175,7 @@ public List getItemsFromIQ(Packet response) { String mem = flavour.element("mem").getText(); int capacity = Integer.parseInt(flavour.element("capacity") .getText()); - Flavour flavor = new Flavour(name, cpu, mem, capacity); + Flavor flavor = new Flavor(name, cpu, mem, capacity); flavoursList.add(flavor); } From 48ccd454f781e6c3bc2cf857ca5e17b055504804 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 24 Apr 2014 11:52:04 -0300 Subject: [PATCH 035/185] Implementing and testing Get and Delete behaviour. --- .../manager/core/ManagerFacade.java | 8 +- .../openstack/OpenStackComputePlugin.java | 7 +- .../occi/instance/ComputeServerResource.java | 10 +- .../manager/occi/TestDeleteCompute.java | 101 ++++++++--- .../manager/occi/TestGetCompute.java | 162 +++++++----------- .../occi/plugins/TestComputeOpenStack.java | 2 +- .../manager/occi/util/ComputeApplication.java | 4 +- .../manager/occi/util/RequestHelper.java | 27 ++- 8 files changed, 180 insertions(+), 141 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index fa0b5665..1f148464 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -124,11 +124,13 @@ private Instance createGetInstanceIQ(String authToken, Request request) { public void removeInstances(String authToken) { // TODO check other manager - + getUser(authToken); + this.computePlugin.removeInstances(authToken); } public void removeInstance(String authToken, String instanceId) { + System.out.println("removing"); Request request = getRequestFromInstance(authToken, instanceId); if (isLocal(request)) { this.computePlugin.removeInstance(authToken, instanceId); @@ -291,4 +293,8 @@ private void checkAndSubmitOpenRequests() { public void setPacketSender(PacketSender packetSender) { this.packetSender = packetSender; } + + public void setRequests(RequestRepository requests) { + this.requests = requests; + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 070ccbf8..33482b2b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -19,7 +19,6 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -import org.apache.log4j.varia.FallbackErrorHandler; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -37,7 +36,7 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String TERM_COMPUTE = "compute"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; private static final String CLASS_COMPUTE = "kind"; - private static final String COMPUTE_ENDPOINT = "/compute"; + private static final String COMPUTE_ENDPOINT = "/compute/"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; public static final String CIRROS_IMAGE_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; @@ -114,7 +113,7 @@ public Instance getInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { - httpGet = new HttpGet(computeEndpoint + "/" + instanceId); + httpGet = new HttpGet(computeEndpoint + instanceId); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -202,7 +201,7 @@ public void removeInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeEndpoint + "/" + instanceId); + httpDelete = new HttpDelete(computeEndpoint + instanceId); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpDelete); diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java index 45497024..fd426dd1 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java @@ -17,22 +17,24 @@ public class ComputeServerResource extends ServerResource { public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); + HeaderUtils.checkOCCIContentType(req.getHeaders()); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); String instanceId = (String) getRequestAttributes().get("instanceId"); - + if (instanceId == null) { return generateResponse(application.getInstances(authToken)); - } - return application.getInstance(authToken, instanceId).toOCCIMassageFormatDetails(); + } + return application.getInstance(authToken, instanceId).toOCCIMassageFormatDetails(); } @Delete public String remove() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); + HeaderUtils.checkOCCIContentType(req.getHeaders()); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); String instanceId = (String) getRequestAttributes().get("instanceId"); - + if (instanceId == null) { application.removeInstances(authToken); return ResponseConstants.OK; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 2bf4f225..722bbb96 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -1,61 +1,110 @@ package org.fogbowcloud.manager.occi; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.DefaultHttpClient; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; +import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; public class TestDeleteCompute { - //TODO rename + // TODO rename RequestHelper requestHelper; - + @Before public void setup() throws Exception { this.requestHelper = new RequestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - + Mockito.doNothing().when(computePlugin).removeInstances(RequestHelper.ACCESS_TOKEN); + Mockito.doNothing().when(computePlugin) + .removeInstance(RequestHelper.ACCESS_TOKEN, RequestHelper.INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( + RequestHelper.USER_MOCK); - this.requestHelper.initializeComponent(computePlugin, identityPlugin); + this.requestHelper.initializeComponentCompute(computePlugin, identityPlugin); } - - @After - public void tearDown() throws Exception{ + + @After + public void tearDown() throws Exception { this.requestHelper.stopComponent(); } - - @Ignore - @Test(expected = OCCIException.class) - public void TestWrongAccessToken() throws Exception{ - HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); + @Test + public void TestDelete() throws Exception { + HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE + ""); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, requestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpDelete); + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Test + public void TestDeleteSpecificInstanceFound() throws Exception { + HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE + + RequestHelper.INSTANCE_ID); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpDelete); + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Test + public void TestDeleteSpecificInstanceNotFound() throws Exception { + HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE + "wrong"); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpDelete); + + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); + } + + @Test + public void TestWrongAccessToken() throws Exception { + HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE + + RequestHelper.INSTANCE_ID); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); - client.execute(httpDelete); + HttpResponse response = client.execute(httpDelete); + + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); + } + + @Test + public void TestEmptyAccessToken() throws Exception { + HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpDelete); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } - - @Ignore - @Test(expected = OCCIException.class) - public void TestInvalidVM() throws Exception{ + + @Test + public void TestWrongContentType() throws Exception { HttpDelete get = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); + get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - client.execute(get); - } - - + HttpResponse response = client.execute(get); + + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); + } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index c933678a..ad97eadb 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -1,27 +1,25 @@ package org.fogbowcloud.manager.occi; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.request.RequestAttribute; -import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.instance.Instance; +import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.util.RequestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; @@ -29,17 +27,30 @@ public class TestGetCompute { //TODO rename RequestHelper requestHelper; + List instances; @Before public void setup() throws Exception { this.requestHelper = new RequestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())).thenReturn(new Instance()); + instances = new ArrayList(); + instances.add(new Instance("test1")); + instances.add(new Instance("test2")); + Mockito.when(computePlugin.getInstances(Mockito.anyString())).thenReturn(instances); + + List list = new ArrayList(); + Map map = new HashMap(); + map.put("test", "test"); + Link link = null; + Instance instance = new Instance(list,map,link); + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())).thenReturn(instance); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); - - this.requestHelper.initializeComponent(computePlugin, identityPlugin); + + this.requestHelper.initializeComponentCompute(computePlugin, identityPlugin); } @After @@ -47,130 +58,81 @@ public void tearDown() throws Exception{ this.requestHelper.stopComponent(); } - @Ignore @Test - public void TestGetComputeEmpty() throws Exception{ + public void TestGetComputeOk() throws Exception{ HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(instances.size(), RequestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } - - @Ignore + @Test - public void TestGetComputeOneVM() throws Exception{ - //Post /request - HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); - HttpClient client = new DefaultHttpClient(); - Category category = new Category(RequestConstants.TERM, - RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); - httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - HttpResponse response = client.execute(httpPost); - - //Get /compute/ - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + public void TestGetSpecificInstanceFound() throws Exception { + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + RequestHelper.INSTANCE_ID); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); - client = new DefaultHttpClient(); - response = client.execute(httpGet); - - Assert.assertEquals(1, RequestHelper.getRequestLocations(response).size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - } - - @Ignore - @Test - public void TestGetComputeManyVMs() throws Exception{ - //Post /request - HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); - Category category = new Category(RequestConstants.TERM, - RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); - httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - httpPost.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, - RequestAttribute.INSTANCE_COUNT.getValue() + " = 3"); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpPost); - List requestIDs = RequestHelper.getRequestLocations(response); - - Assert.assertEquals(3, requestIDs.size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - - //Get /compute/ - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); - client = new DefaultHttpClient(); - response = client.execute(httpGet); + HttpResponse response = client.execute(httpGet); - Assert.assertEquals(3, RequestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } - @Ignore @Test - public void TestGetComputeDetailsSpecificVM() throws Exception{ - //Post /request - HttpPost httpPost = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); - HttpClient client = new DefaultHttpClient(); - Category category = new Category(RequestConstants.TERM, - RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); - httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - HttpResponse response = client.execute(httpPost); - - String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); - String idVm = responseStr.replace("X-OCCI-Location: http://localhost:8182/request/", "").trim(); - - //Get /compute/$VM - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + idVm); + public void TestGetSpecificInstanceNotFound() throws Exception { + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + "wrong"); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); - client = new DefaultHttpClient(); - response = client.execute(httpGet); - responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); - System.out.println(responseStr); - + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); - Assert.assertEquals(1, RequestHelper.getRequestLocations(response).size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - } + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); + } - @Ignore - @Test(expected = OCCIException.class) - public void TestWrongContentType() throws Exception{ + @Test + public void TestWrongContentType() throws Exception { HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - client.execute(httpGet); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); } - @Ignore - @Test(expected = OCCIException.class) - public void TestWrongAccessToken() throws Exception{ + @Test + public void TestAccessToken() throws Exception { HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Test + public void TestWrongAccessToken() throws Exception { + HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + RequestHelper.INSTANCE_ID); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); - client.execute(httpGet); - } + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); + } - @Ignore - @Test(expected = OCCIException.class) - public void TestInvalidVM() throws Exception{ + @Test + public void TestEmptyAccessToken() throws Exception { HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); HttpClient client = new DefaultHttpClient(); - client.execute(httpGet); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 53cb31ea..c0747644 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -271,7 +271,7 @@ public void testGetAllManyInstanceIds() { private List getInstanceLocations(List intances) { List locations = new ArrayList(); for (Instance instance : intances) { - String instanceMessage = instance.toOCCIMassageFormatLocation(); +// String instanceMessage = instance.toOCCIMassageFormatLocation(); String[] lineTokens = instance.toOCCIMassageFormatLocation().split("Location:"); locations.add(lineTokens[1].trim()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index faa3957e..be3714f0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -25,7 +25,7 @@ public class ComputeApplication extends Application { - public static final String TARGET = "/compute"; + public static final String TARGET = "/compute/"; public static final String CORE_ATTRIBUTE_OCCI = "occi.compute.cores"; public static final String MEMORY_ATTRIBUTE_OCCI = "occi.compute.memory"; public static final String ARCHITECTURE_ATTRIBUTE_OCCI = "occi.compute.architecture"; @@ -82,7 +82,7 @@ private void normalizeDefaultAttributes() { public Restlet createInboundRoot() { Router router = new Router(getContext()); router.attach(TARGET, ComputeServer.class); - router.attach(TARGET + "/{instanceid}", ComputeServer.class); + router.attach(TARGET + "{instanceid}", ComputeServer.class); return router; } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java index f86bf89d..448aa167 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java @@ -17,13 +17,14 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestRepository; import org.restlet.Component; import org.restlet.data.Protocol; public class RequestHelper { - private Component component; - + public static String INSTANCE_ID = "1234567ujhgf45hdb4w"; public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; public static final String INVALID_TOKEN = "invalid-token"; public static final String CONTENT_TYPE_OCCI = "text/occi"; @@ -32,7 +33,9 @@ public class RequestHelper { public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; - + private Component component; + RequestRepository requests; + public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); @@ -44,6 +47,24 @@ public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin iden component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); } + + public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { + component = new Component(); + component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); + + ManagerFacade facade = new ManagerFacade(new Properties()); + facade.setComputePlugin(computePlugin); + facade.setIdentityPlugin(identityPlugin); + + requests = new RequestRepository(); + Request request = new Request("1", RequestHelper.ACCESS_TOKEN, INSTANCE_ID, + null, null, null, null); + requests.addRequest(RequestHelper.USER_MOCK, request); + facade.setRequests(requests); + + component.getDefaultHost().attach(new OCCIApplication(facade)); + component.start(); + } public void stopComponent() throws Exception { component.stop(); From d26710d1fc044ba4ec07e887fc2b32fb1c03b09f Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 24 Apr 2014 12:51:26 -0300 Subject: [PATCH 036/185] Implementing Get and Delete behaviour --- .../manager/core/ManagerFacade.java | 30 +++++++++++++++---- .../manager/occi/TestGetCompute.java | 2 +- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 1f148464..6117f7b0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -104,9 +104,21 @@ private void checkRequestId(String authToken, String requestId) { } public List getInstances(String authToken) { - // TODO check other manager + // TODO check other manager + List instances = new ArrayList(); + for (Request request : requests.getByUser(getUser(authToken))) { + if (isLocal(request)) { + instances.addAll(this.computePlugin.getInstances(authToken)); + } else { + instances.addAll(createGetInstancesIQ(request)); + } + } + return instances; + } - return this.computePlugin.getInstances(authToken); + private List createGetInstancesIQ(Request request) { + // TODO Auto-generated method stub + return null; } public Instance getInstance(String authToken, String instanceId) { @@ -124,13 +136,21 @@ private Instance createGetInstanceIQ(String authToken, Request request) { public void removeInstances(String authToken) { // TODO check other manager - getUser(authToken); + for (Request request : requests.getByUser(getUser(authToken))) { + if (isLocal(request)) { + this.computePlugin.removeInstances(authToken); + } else { + createRemoveInstancesIQ(request); + } + } + } + + private void createRemoveInstancesIQ(Request request) { + // TODO Auto-generated method stub - this.computePlugin.removeInstances(authToken); } public void removeInstance(String authToken, String instanceId) { - System.out.println("removing"); Request request = getRequestFromInstance(authToken, instanceId); if (isLocal(request)) { this.computePlugin.removeInstance(authToken, instanceId); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index ad97eadb..18c49965 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -135,4 +135,4 @@ public void TestEmptyAccessToken() throws Exception { Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } -} +} \ No newline at end of file From 729f2c53c21a7697a1b2c91fcf64fbc93b5778cf Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 24 Apr 2014 14:45:15 -0300 Subject: [PATCH 037/185] Refactoring TestOCCIApplication --- .../manager/occi/TestOCCIApplication.java | 42 +++++++++---------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 7b544dd0..7cb2723e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -28,13 +28,12 @@ public class TestOCCIApplication { private static final String INSTANCE_LOCATION = HeaderUtils.X_OCCI_LOCATION - + "http://localhost:" + RequestHelper.ENDPOINT_PORT - + ComputeApplication.TARGET + + "http://localhost:" + RequestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String INSTANCE_ID = INSTANCE_LOCATION.replace( HeaderUtils.X_OCCI_LOCATION, "").trim(); private static final Long SCHEDULER_PERIOD = 500L; - + private OCCIApplication occiApplication; private Map xOCCIAtt; ManagerFacade managerFacade; @@ -55,7 +54,9 @@ public void setUp() { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenThrow(new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.BAD_REQUEST, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( @@ -67,39 +68,34 @@ public void setUp() { @Test public void testGetRequestDetails() throws InterruptedException { - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + xOCCIAtt); List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); - Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, - requestId); + Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, requestId); Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertNull(requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); } - + @Test public void testGetRequestDetailsAfterPeriod() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_LOCATION); - managerFacade.setComputePlugin(computePlugin); + Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_LOCATION); - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + managerFacade.setComputePlugin(computePlugin); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + xOCCIAtt); List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); - Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, - requestId); - - Assert.assertEquals(requestId, requestDetails.getId()); - Assert.assertNull(requestDetails.getInstanceId()); - Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); + Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, requestId); Thread.sleep(SCHEDULER_PERIOD * 2); - + Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertEquals(INSTANCE_ID, requestDetails.getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requestDetails.getState()); @@ -131,7 +127,8 @@ public void testManyResquestUser() { public void testRemoveAllRequest() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); @@ -148,7 +145,8 @@ public void testRemoveAllRequest() { public void testRemoveSpecificRequest() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); + occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + xOCCIAtt); List requestsFromUser = occiApplication .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); From 43f4d3253db5c133195bc9eba3b73b8c956cab96 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Thu, 24 Apr 2014 20:15:43 +0200 Subject: [PATCH 038/185] Fixes tests related to getting and removing instances. --- .../manager/core/ManagerFacade.java | 57 +++++----- .../openstack/OpenStackComputePlugin.java | 8 +- .../manager/occi/instance/Instance.java | 62 ++++++----- .../manager/occi/request/Request.java | 14 ++- .../occi/request/RequestRepository.java | 10 ++ .../manager/occi/TestDeleteCompute.java | 64 ++++++----- .../manager/occi/TestDeleteRequest.java | 100 +++++++++--------- .../manager/occi/TestGetCompute.java | 86 ++++++++------- .../manager/occi/TestGetRequest.java | 92 ++++++++-------- .../manager/occi/TestOCCIApplication.java | 45 ++++---- .../manager/occi/TestPostRequest.java | 100 +++++++++--------- .../manager/occi/core/TestHeaderUtils.java | 8 +- .../manager/occi/core/TestInstance.java | 4 +- ...RequestHelper.java => OCCITestHelper.java} | 11 +- 14 files changed, 349 insertions(+), 312 deletions(-) rename src/test/java/org/fogbowcloud/manager/occi/util/{RequestHelper.java => OCCITestHelper.java} (93%) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 6117f7b0..b30ef3d2 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -104,70 +104,69 @@ private void checkRequestId(String authToken, String requestId) { } public List getInstances(String authToken) { - // TODO check other manager List instances = new ArrayList(); for (Request request : requests.getByUser(getUser(authToken))) { + String instanceId = request.getInstanceId(); + if (instanceId == null) { + continue; + } if (isLocal(request)) { - instances.addAll(this.computePlugin.getInstances(authToken)); + instances.add(this.computePlugin.getInstance(authToken, instanceId)); } else { - instances.addAll(createGetInstancesIQ(request)); + instances.add(getRemoteInstance(request)); } } return instances; } - private List createGetInstancesIQ(Request request) { - // TODO Auto-generated method stub - return null; - } - public Instance getInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); if (isLocal(request)) { return this.computePlugin.getInstance(authToken, instanceId); - } else { - return createGetInstanceIQ(authToken, request); - } + } + return getRemoteInstance(request); } - private Instance createGetInstanceIQ(String authToken, Request request) { + private Instance getRemoteInstance(Request request) { return null; } public void removeInstances(String authToken) { - // TODO check other manager for (Request request : requests.getByUser(getUser(authToken))) { + String instanceId = request.getInstanceId(); + if (instanceId == null) { + continue; + } if (isLocal(request)) { - this.computePlugin.removeInstances(authToken); + this.computePlugin.removeInstance(authToken, instanceId); } else { - createRemoveInstancesIQ(request); + removeRemoteInstance(request); } } } - private void createRemoveInstancesIQ(Request request) { - // TODO Auto-generated method stub - - } - public void removeInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); if (isLocal(request)) { this.computePlugin.removeInstance(authToken, instanceId); } else { - createRemoveIQ(authToken, request); + removeRemoteInstance(request); } } - private void createRemoveIQ(String authToken, Request request) { + private void removeRemoteInstance(Request request) { // TODO Auto-generated method stub } public Request getRequestFromInstance(String authToken, String instanceId) { String user = getUser(authToken); - List userRequests = requests.getByUser(user); + List userRequests = requests.getAll(); for (Request request : userRequests) { if (instanceId.equals(request.getInstanceId())) { + if (!request.getUser().equals(user)) { + throw new OCCIException(ErrorType.UNAUTHORIZED, + ResponseConstants.UNAUTHORIZED); + } return request; } } @@ -175,10 +174,7 @@ public Request getRequestFromInstance(String authToken, String instanceId) { } private boolean isLocal(Request request) { - if (request.getMemberId() == null) { - return true; - } - return false; + return request.getMemberId() == null; } public Request getRequest(String authToken, String requestId) { @@ -203,7 +199,7 @@ private String getFederationUserToken() { return token; } - public Instance getRemoteInstance(String instanceId) { + public Instance getInstanceForRemoteMember(String instanceId) { String token = getFederationUserToken(); try { return computePlugin.getInstance(token, instanceId); @@ -213,7 +209,7 @@ public Instance getRemoteInstance(String instanceId) { } } - public void removeRemoteInstance(String instanceId) { + public void removeInstanceForRemoteMember(String instanceId) { String token = getFederationUserToken(); computePlugin.removeInstance(token, instanceId); } @@ -229,8 +225,7 @@ public List createRequests(String authToken, List categories, List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, authToken, null, RequestState.OPEN, categories, - xOCCIAtt, null); + Request request = new Request(requestId, authToken, user, categories, xOCCIAtt); currentRequests.add(request); requests.addRequest(user, request); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 33482b2b..e6e042bc 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -124,7 +124,7 @@ public Instance getInstance(String authToken, String instanceId) { } String responseStr = EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - return Instance.parseInstanceDetails(responseStr); + return Instance.parseInstance(instanceId, responseStr); } catch (URISyntaxException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); @@ -150,7 +150,7 @@ public List getInstances(String authToken) { } String responseStr = EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - return returnInstances(responseStr); + return parseInstances(responseStr); } catch (URISyntaxException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); @@ -163,12 +163,12 @@ public List getInstances(String authToken) { } } - private List returnInstances(String responseStr) { + private List parseInstances(String responseStr) { List instances = new ArrayList(); String[] lines = responseStr.split("\n"); for (String line : lines) { if (line.contains(Instance.PREFIX_DEFAULT_INSTANCE)) { - instances.add(Instance.parseInstanceId(line)); + instances.add(Instance.parseInstance(line)); } } return instances; diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 59c5f319..1bcf3ae5 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -26,60 +26,61 @@ public Instance(String id) { this.id = id; } - public Instance(List resources, Map attributes, Link link) { + public Instance(String id, List resources, Map attributes, Link link) { + this(id); this.resources = resources; this.attributes = attributes; this.link = link; } - public static Instance parseInstanceId(String textResponse) { - return new Instance(textResponse.replace(PREFIX_DEFAULT_INSTANCE , "").trim()); + public static Instance parseInstance(String textResponse) { + return new Instance(textResponse.replace(PREFIX_DEFAULT_INSTANCE, "").trim()); } - public static Instance parseInstanceDetails(String textResponse) { + public static Instance parseInstance(String id, String textResponse) { List resources = new ArrayList(); Map attributes = new HashMap(); Link link = null; - + String[] lines = textResponse.split("\n"); for (String line : lines) { - System.out.println("Line = " + line); if (line.contains("Category:")) { String[] blockLine = line.split(";"); - String[] blockValues; - String term = ""; + String term = ""; String scheme = ""; String catClass = ""; String title = ""; String rel = ""; String location = ""; List attributesResource = new ArrayList(); - List actionsResource = new ArrayList(); - - for (String block: blockLine) { - if(block.contains(CATEGORY)) { + List actionsResource = new ArrayList(); + + for (String block : blockLine) { + if (block.contains(CATEGORY)) { blockValues = block.split(":"); term = blockValues[1].trim(); } else { blockValues = block.split("="); if (blockValues[0].contains("scheme")) { scheme = blockValues[1].replace("\"", "").trim(); - }else if (blockValues[0].contains("class")) { + } else if (blockValues[0].contains("class")) { catClass = blockValues[1].replace("\"", "").trim(); - }else if (blockValues[0].contains("title")) { + } else if (blockValues[0].contains("title")) { title = blockValues[1].replace("\"", "").trim(); - }else if (blockValues[0].contains("rel")) { + } else if (blockValues[0].contains("rel")) { rel = blockValues[1].replace("\"", "").trim(); - }else if (blockValues[0].contains("location")) { + } else if (blockValues[0].contains("location")) { location = blockValues[1].replace("\"", "").trim(); - }else if (blockValues[0].contains("attributes")) { - String[] attributesValues = blockValues[1].replace("\"", "").split(" "); + } else if (blockValues[0].contains("attributes")) { + String[] attributesValues = blockValues[1].replace( + "\"", "").split(" "); for (String attribute : attributesValues) { attributesResource.add(attribute); } - }else if (blockValues[0].contains("actions")) { - String[] actionsValues = blockValues[1].replace("\"", "").split(" "); + } else if (blockValues[0].contains("actions")) { + String[] actionsValues = blockValues[1].replace( + "\"", "").split(" "); for (String action : actionsValues) { actionsResource.add(action); } @@ -87,16 +88,19 @@ public static Instance parseInstanceDetails(String textResponse) { } } Category category = new Category(term, scheme, catClass); - resources.add(new Resource(category, attributesResource, actionsResource, location, title, rel)); - }else if (line.contains("Link")){ + resources.add(new Resource(category, attributesResource, + actionsResource, location, title, rel)); + } else if (line.contains("Link")) { link = Link.parseLink(line); - }else if (line.contains("X-OCCI-Attribute: ")){ - - String[] blockLine = line.replace(PREFIX_DEFAULT_ATTRIBUTE, "").split("="); - attributes.put(blockLine[0], blockLine[1].replace("\"", "").trim()); + } else if (line.contains("X-OCCI-Attribute: ")) { + + String[] blockLine = line.replace(PREFIX_DEFAULT_ATTRIBUTE, "") + .split("="); + attributes.put(blockLine[0], blockLine[1].replace("\"", "") + .trim()); } - } - return new Instance(resources, attributes, link); + } + return new Instance(id, resources, attributes, link); } public String toOCCIMassageFormatLocation(){ @@ -108,7 +112,7 @@ public String toOCCIMassageFormatDetails(){ for (Resource resource : this.resources) { messageFormat += CATEGORY + " " + resource.toHeader() + "\n"; } - if(link != null){ + if (link != null){ messageFormat += this.link.toOCCIMessageFormatLink() + "\n"; } for (String key : this.attributes.keySet()) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 1c6c1f21..4ecf77fd 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -14,22 +14,26 @@ public class Request { private RequestState state; private List categories; private Map xOCCIAtt; + private String user; - public Request(String id, String authToken, String instanceId, RequestState state, - List categories, Map xOCCIAtt, String memberId) { + public Request(String id, String authToken, String user, + List categories, Map xOCCIAtt) { this.id = id; this.authToken = authToken; - this.memberId = memberId; - setInstanceId(instanceId); - setState(state); + this.user = user; this.categories = categories; this.xOCCIAtt = xOCCIAtt; + setState(RequestState.OPEN); } public List getCategories() { return categories; } + public String getUser() { + return user; + } + public String getInstanceId() { return instanceId; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index 306034ba..8eb37e28 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -77,4 +77,14 @@ public void remove(String requestId) { } } } + + public List getAll() { + List allRequests = new LinkedList(); + for (List userRequests : requests.values()) { + for (Request request : userRequests) { + allRequests.add(request); + } + } + return allRequests; + } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 722bbb96..395506ef 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -1,5 +1,8 @@ package org.fogbowcloud.manager.occi; +import java.util.LinkedList; +import java.util.List; + import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; @@ -8,7 +11,8 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -18,21 +22,27 @@ public class TestDeleteCompute { // TODO rename - RequestHelper requestHelper; + OCCITestHelper requestHelper; @Before public void setup() throws Exception { - this.requestHelper = new RequestHelper(); + this.requestHelper = new OCCITestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.doNothing().when(computePlugin).removeInstances(RequestHelper.ACCESS_TOKEN); + Mockito.doNothing().when(computePlugin).removeInstances(OCCITestHelper.ACCESS_TOKEN); Mockito.doNothing().when(computePlugin) - .removeInstance(RequestHelper.ACCESS_TOKEN, RequestHelper.INSTANCE_ID); + .removeInstance(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( - RequestHelper.USER_MOCK); - - this.requestHelper.initializeComponentCompute(computePlugin, identityPlugin); + Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + OCCITestHelper.USER_MOCK); + + List requests = new LinkedList(); + Request request = new Request("1", OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.USER_MOCK, null, null); + request.setInstanceId(OCCITestHelper.INSTANCE_ID); + requests.add(request); + + this.requestHelper.initializeComponentCompute(computePlugin, identityPlugin, requests); } @After @@ -42,9 +52,9 @@ public void tearDown() throws Exception { @Test public void TestDelete() throws Exception { - HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE + ""); - httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, requestHelper.ACCESS_TOKEN); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + ""); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpDelete); @@ -53,10 +63,10 @@ public void TestDelete() throws Exception { @Test public void TestDeleteSpecificInstanceFound() throws Exception { - HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE - + RequestHelper.INSTANCE_ID); - httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + + OCCITestHelper.INSTANCE_ID); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpDelete); @@ -65,9 +75,9 @@ public void TestDeleteSpecificInstanceFound() throws Exception { @Test public void TestDeleteSpecificInstanceNotFound() throws Exception { - HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE + "wrong"); - httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + "wrong"); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpDelete); @@ -76,20 +86,20 @@ public void TestDeleteSpecificInstanceNotFound() throws Exception { @Test public void TestWrongAccessToken() throws Exception { - HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE - + RequestHelper.INSTANCE_ID); - httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + + OCCITestHelper.INSTANCE_ID); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpDelete); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } @Test public void TestEmptyAccessToken() throws Exception { - HttpDelete httpDelete = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); - httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE); + httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpDelete); @@ -99,9 +109,9 @@ public void TestEmptyAccessToken() throws Exception { @Test public void TestWrongContentType() throws Exception { - HttpDelete get = new HttpDelete(RequestHelper.URI_FOGBOW_COMPUTE); + HttpDelete get = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE); get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index d13a61ef..7d2636d6 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -22,7 +22,7 @@ import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -31,20 +31,20 @@ public class TestDeleteRequest { - RequestHelper requestHelper; + OCCITestHelper requestHelper; @SuppressWarnings("unchecked") @Before public void setup() throws Exception { - this.requestHelper = new RequestHelper(); + this.requestHelper = new OCCITestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); - Mockito.when(identityPlugin.getUser(RequestHelper.INVALID_TOKEN)).thenThrow( + Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); @@ -52,8 +52,8 @@ public void setup() throws Exception { @Test public void testRequest() throws URISyntaxException, HttpException, IOException { - HttpDelete delete = new HttpDelete(RequestHelper.URI_FOGBOW_REQUEST); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(delete); @@ -63,54 +63,54 @@ public void testRequest() throws URISyntaxException, HttpException, IOException @Test public void testDeleteEmptyRequest() throws URISyntaxException, HttpException, IOException { // Get - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Delete - HttpDelete delete = new HttpDelete(RequestHelper.URI_FOGBOW_REQUEST); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); client = new DefaultHttpClient(); response = client.execute(delete); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Get response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testDeleteSpecificRequest() throws URISyntaxException, HttpException, IOException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - List requestLocations = RequestHelper.getRequestLocations(response); + List requestLocations = OCCITestHelper.getRequestLocations(response); Assert.assertEquals(1, requestLocations.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Delete HttpDelete delete = new HttpDelete(requestLocations.get(0)); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(delete); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Get - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @@ -118,17 +118,17 @@ public void testDeleteSpecificRequest() throws URISyntaxException, HttpException public void testDeleteManyRequestsIndividually() throws URISyntaxException, HttpException, IOException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 200"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - List requestLocations = RequestHelper.getRequestLocations(response); + List requestLocations = OCCITestHelper.getRequestLocations(response); Assert.assertEquals(200, requestLocations.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); @@ -137,64 +137,64 @@ public void testDeleteManyRequestsIndividually() throws URISyntaxException, Http HttpDelete delete; for (String requestLocation : requestLocations) { delete = new HttpDelete(requestLocation); - delete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + delete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(delete); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } // Get - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testDeleteAllRequests() throws URISyntaxException, HttpException, IOException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 200"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - List requestIDs = RequestHelper.getRequestLocations(response); + List requestIDs = OCCITestHelper.getRequestLocations(response); Assert.assertEquals(200, requestIDs.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Delete - HttpDelete delete = new HttpDelete(RequestHelper.URI_FOGBOW_REQUEST); - delete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST); + delete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(delete); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Get - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testDeleteRequestNotFound() throws URISyntaxException, HttpException, IOException { - HttpDelete delete = new HttpDelete(RequestHelper.URI_FOGBOW_REQUEST + "/" + HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST + "/" + "not_found_id"); - delete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + delete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(delete); @@ -203,9 +203,9 @@ public void testDeleteRequestNotFound() throws URISyntaxException, HttpException @Test public void testDeleteWithInvalidToken() throws URISyntaxException, HttpException, IOException { - HttpDelete delete = new HttpDelete(RequestHelper.URI_FOGBOW_REQUEST); - delete.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.INVALID_TOKEN); + HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST); + delete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.INVALID_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(delete); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 18c49965..4ddaa6a9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -16,7 +17,8 @@ import org.fogbowcloud.manager.occi.core.Resource; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.instance.Instance.Link; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -25,56 +27,66 @@ public class TestGetCompute { - //TODO rename - RequestHelper requestHelper; - List instances; + private static final String INSTANCE_1_ID = "test1"; + private static final String INSTANCE_2_ID = "test2"; + + OCCITestHelper helper; @Before public void setup() throws Exception { - this.requestHelper = new RequestHelper(); + this.helper = new OCCITestHelper(); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())).thenReturn(new Instance()); - instances = new ArrayList(); - instances.add(new Instance("test1")); - instances.add(new Instance("test2")); - Mockito.when(computePlugin.getInstances(Mockito.anyString())).thenReturn(instances); - List list = new ArrayList(); Map map = new HashMap(); map.put("test", "test"); Link link = null; - Instance instance = new Instance(list,map,link); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())).thenReturn(instance); + Instance instance1 = new Instance(INSTANCE_1_ID, list, map, link); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when(computePlugin.getInstance(Mockito.anyString(), + Mockito.eq(INSTANCE_1_ID))).thenReturn(instance1); + Mockito.when(computePlugin.getInstance(Mockito.anyString(), + Mockito.eq(INSTANCE_2_ID))).thenReturn(new Instance(INSTANCE_2_ID)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + OCCITestHelper.USER_MOCK); + + List requests = new LinkedList(); + Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.USER_MOCK, null, null); + request1.setInstanceId(INSTANCE_1_ID); + requests.add(request1); + Request request2 = new Request("2", OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.USER_MOCK, null, null); + request2.setInstanceId(INSTANCE_2_ID); + requests.add(request2); - this.requestHelper.initializeComponentCompute(computePlugin, identityPlugin); + this.helper.initializeComponentCompute(computePlugin, identityPlugin, requests); } @After public void tearDown() throws Exception{ - this.requestHelper.stopComponent(); + this.helper.stopComponent(); } @Test public void TestGetComputeOk() throws Exception{ - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - Assert.assertEquals(instances.size(), RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(2, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void TestGetSpecificInstanceFound() throws Exception { - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + RequestHelper.INSTANCE_ID); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_1_ID); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); @@ -83,9 +95,9 @@ public void TestGetSpecificInstanceFound() throws Exception { @Test public void TestGetSpecificInstanceNotFound() throws Exception { - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + "wrong"); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + "wrong"); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); @@ -94,9 +106,9 @@ public void TestGetSpecificInstanceNotFound() throws Exception { @Test public void TestWrongContentType() throws Exception { - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); @@ -105,9 +117,9 @@ public void TestWrongContentType() throws Exception { @Test public void TestAccessToken() throws Exception { - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); @@ -116,19 +128,19 @@ public void TestAccessToken() throws Exception { @Test public void TestWrongAccessToken() throws Exception { - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE + RequestHelper.INSTANCE_ID); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_1_ID); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } @Test public void TestEmptyAccessToken() throws Exception { - HttpGet httpGet = new HttpGet(RequestHelper.URI_FOGBOW_COMPUTE); - httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index c16bbbc0..62d78738 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -27,7 +27,7 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.ComputeApplication; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -36,14 +36,14 @@ public class TestGetRequest { - private RequestHelper requestHelper; - private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + RequestHelper.ENDPOINT_PORT + private OCCITestHelper requestHelper; + private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + OCCITestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; @SuppressWarnings("unchecked") @Before public void setup() throws Exception { - this.requestHelper = new RequestHelper(); + this.requestHelper = new OCCITestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( @@ -51,9 +51,9 @@ public void setup() throws Exception { Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( - RequestHelper.USER_MOCK); - Mockito.when(identityPlugin.getUser(RequestHelper.INVALID_TOKEN)).thenThrow( + Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); requestHelper.initializeComponent(computePlugin, identityPlugin); @@ -61,33 +61,33 @@ public void setup() throws Exception { @Test public void testGetRequest() throws URISyntaxException, HttpException, IOException { - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testGetRequestPlainContent() throws URISyntaxException, HttpException, IOException { - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); get.addHeader(OCCIHeaders.CONTENT_TYPE, "text/plain"); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); - Assert.assertEquals(0, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testGetRequestInvalidToken() throws URISyntaxException, HttpException, IOException { - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.INVALID_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.INVALID_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); @@ -97,48 +97,48 @@ public void testGetRequestInvalidToken() throws URISyntaxException, HttpExceptio @Test public void testGetResquestTwoIds() throws URISyntaxException, HttpException, IOException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 2"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); // Get - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); client = new DefaultHttpClient(); response = client.execute(get); - Assert.assertEquals(2, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(2, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testGetResquestManyIds() throws URISyntaxException, HttpException, IOException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 200"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); // Get - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); client = new DefaultHttpClient(); response = client.execute(get); - Assert.assertEquals(200, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(200, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @@ -146,20 +146,20 @@ public void testGetResquestManyIds() throws URISyntaxException, HttpException, I public void testGetSpecificRequest() throws URISyntaxException, ParseException, IOException, HttpException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 1"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); // Get - HttpGet get = new HttpGet(RequestHelper.getRequestLocations(response).get(0)); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.getRequestLocations(response).get(0)); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); @@ -168,9 +168,9 @@ public void testGetSpecificRequest() throws URISyntaxException, ParseException, @Test public void testGetRequestNotFound() throws URISyntaxException, ParseException, IOException, HttpException { - HttpGet get = new HttpGet(RequestHelper.URI_FOGBOW_REQUEST + "/" + "not_found"); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST + "/" + "not_found"); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); @@ -181,20 +181,20 @@ public void testGetRequestNotFound() throws URISyntaxException, ParseException, public void testGetStatusRequest() throws URISyntaxException, ParseException, IOException, HttpException { // Post - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 1"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); // Get - HttpGet get = new HttpGet(RequestHelper.getRequestLocations(response).get(0)); - get.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - get.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + HttpGet get = new HttpGet(OCCITestHelper.getRequestLocations(response).get(0)); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); String requestDetails = EntityUtils.toString(response.getEntity(), diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 7cb2723e..35f27231 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -19,7 +19,7 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.ComputeApplication; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -28,7 +28,7 @@ public class TestOCCIApplication { private static final String INSTANCE_LOCATION = HeaderUtils.X_OCCI_LOCATION - + "http://localhost:" + RequestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + + "http://localhost:" +OCCITestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String INSTANCE_ID = INSTANCE_LOCATION.replace( HeaderUtils.X_OCCI_LOCATION, "").trim(); @@ -59,8 +59,8 @@ public void setUp() { ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn( - RequestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + OCCITestHelper.USER_MOCK); managerFacade.setIdentityPlugin(identityPlugin); managerFacade.setComputePlugin(computePlugin); @@ -68,18 +68,19 @@ public void setUp() { @Test public void testGetRequestDetails() throws InterruptedException { - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); - List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + List requests = occiApplication.getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); - Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, requestId); + Request requestDetails = occiApplication.getRequest(OCCITestHelper.ACCESS_TOKEN, requestId); Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertNull(requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); } + @SuppressWarnings("unchecked") @Test public void testGetRequestDetailsAfterPeriod() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); @@ -87,12 +88,12 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { .thenReturn(INSTANCE_LOCATION); managerFacade.setComputePlugin(computePlugin); - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); - List requests = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + List requests = occiApplication.getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); - Request requestDetails = occiApplication.getRequest(RequestHelper.ACCESS_TOKEN, requestId); + Request requestDetails = occiApplication.getRequest(OCCITestHelper.ACCESS_TOKEN, requestId); Thread.sleep(SCHEDULER_PERIOD * 2); @@ -103,10 +104,10 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { @Test public void testResquestUser() { - this.occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + this.occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication - .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + .getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(1, requestsFromUser.size()); } @@ -115,10 +116,10 @@ public void testResquestUser() { public void testManyResquestUser() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - this.occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + this.occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication - .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + .getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(numberOfInstances, requestsFromUser.size()); } @@ -127,16 +128,16 @@ public void testManyResquestUser() { public void testRemoveAllRequest() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication - .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + .getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(numberOfInstances, requestsFromUser.size()); - occiApplication.removeAllRequests(RequestHelper.ACCESS_TOKEN); - requestsFromUser = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + occiApplication.removeAllRequests(OCCITestHelper.ACCESS_TOKEN); + requestsFromUser = occiApplication.getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(0, requestsFromUser.size()); } @@ -145,16 +146,16 @@ public void testRemoveAllRequest() { public void testRemoveSpecificRequest() { int numberOfInstances = 10; xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(numberOfInstances)); - occiApplication.createRequests(RequestHelper.ACCESS_TOKEN, new ArrayList(), + occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); List requestsFromUser = occiApplication - .getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + .getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(numberOfInstances, requestsFromUser.size()); - occiApplication.removeRequest(RequestHelper.ACCESS_TOKEN, requestsFromUser.get(1).getId()); - requestsFromUser = occiApplication.getRequestsFromUser(RequestHelper.ACCESS_TOKEN); + occiApplication.removeRequest(OCCITestHelper.ACCESS_TOKEN, requestsFromUser.get(1).getId()); + requestsFromUser = occiApplication.getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); Assert.assertEquals(numberOfInstances - 1, requestsFromUser.size()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index 8543ade1..6928f4ee 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -20,7 +20,7 @@ import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -29,20 +29,20 @@ public class TestPostRequest { - private RequestHelper requestHelper; + private OCCITestHelper requestHelper; @SuppressWarnings("unchecked") @Before public void setup() throws Exception { - this.requestHelper = new RequestHelper(); + this.requestHelper = new OCCITestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(RequestHelper.ACCESS_TOKEN)).thenReturn(RequestHelper.USER_MOCK); - Mockito.when(identityPlugin.getUser(RequestHelper.INVALID_TOKEN)).thenThrow( + Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); @@ -50,15 +50,15 @@ public void setup() throws Exception { @Test public void testPostRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - List requestIDs = RequestHelper.getRequestLocations(response); + List requestIDs = OCCITestHelper.getRequestLocations(response); Assert.assertEquals(1, requestIDs.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); @@ -66,17 +66,17 @@ public void testPostRequest() throws URISyntaxException, HttpException, IOExcept @Test public void testPostRequestTwoInstances() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 2"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - List requestIDs = RequestHelper.getRequestLocations(response); + List requestIDs = OCCITestHelper.getRequestLocations(response); Assert.assertEquals(2, requestIDs.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); @@ -85,17 +85,17 @@ public void testPostRequestTwoInstances() throws URISyntaxException, HttpExcepti @Test public void testPostRequestManyInstances() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " = 200"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - List requestIDs = RequestHelper.getRequestLocations(response); + List requestIDs = OCCITestHelper.getRequestLocations(response); Assert.assertEquals(200, requestIDs.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); @@ -104,11 +104,11 @@ public void testPostRequestManyInstances() throws URISyntaxException, HttpExcept @Test public void testPostInvalidCategoryTermRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category("wrong", RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); @@ -119,11 +119,11 @@ public void testPostInvalidCategoryTermRequest() throws URISyntaxException, Http @Test public void testPostInvalidCategorySchemeRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, "http://schemas.fogbowcloud.org/wrong#", OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); @@ -134,11 +134,11 @@ public void testPostInvalidCategorySchemeRequest() throws URISyntaxException, Ht @Test public void testPostInvalidCategoryClassRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, "mixin"); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); @@ -149,11 +149,11 @@ public void testPostInvalidCategoryClassRequest() throws URISyntaxException, Htt @Test public void testPostInvalidAttributeRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " =\"x\""); @@ -166,11 +166,11 @@ public void testPostInvalidAttributeRequest() throws URISyntaxException, HttpExc @Test public void testPostInvalidAcessTokenRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.INVALID_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.INVALID_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); @@ -181,11 +181,11 @@ public void testPostInvalidAcessTokenRequest() throws URISyntaxException, HttpEx @Test public void testPostInvalidContentTypeRequest() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); post.addHeader(OCCIHeaders.CONTENT_TYPE, "text/plain"); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); @@ -196,11 +196,11 @@ public void testPostInvalidContentTypeRequest() throws URISyntaxException, HttpE @Test public void testPostRequestInvalidAttributeInstances() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " =\"x\""); @@ -213,11 +213,11 @@ public void testPostRequestInvalidAttributeInstances() throws URISyntaxException @Test public void testPostRequestInvalidAttributeType() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.TYPE.getValue() + " =\"x\""); @@ -230,11 +230,11 @@ public void testPostRequestInvalidAttributeType() throws URISyntaxException, Htt @Test public void testPostRequestInvalidAttributeValidFrom() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + " =\"x\""); @@ -247,11 +247,11 @@ public void testPostRequestInvalidAttributeValidFrom() throws URISyntaxException @Test public void testPostRequestInvalidAttributeValidUntil() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.VALID_UNTIL.getValue() + " =\"x\""); @@ -264,11 +264,11 @@ public void testPostRequestInvalidAttributeValidUntil() throws URISyntaxExceptio @Test public void testPostRequestAllAttributes() throws URISyntaxException, HttpException, IOException { - HttpPost post = new HttpPost(RequestHelper.URI_FOGBOW_REQUEST); + HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); - post.addHeader(OCCIHeaders.CONTENT_TYPE, RequestHelper.CONTENT_TYPE_OCCI); - post.addHeader(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + "=10"); @@ -281,7 +281,7 @@ public void testPostRequestAllAttributes() throws URISyntaxException, HttpExcept HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); - Assert.assertEquals(10, RequestHelper.getRequestLocations(response).size()); + Assert.assertEquals(10, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java index bb05bb1f..0d9dcc0b 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestHeaderUtils.java @@ -3,7 +3,7 @@ import java.util.List; import org.fogbowcloud.manager.occi.request.RequestConstants; -import org.fogbowcloud.manager.occi.util.RequestHelper; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -21,10 +21,10 @@ public void setup() throws Exception { @Test public void testValidSyntaxToken() { - headers.add(OCCIHeaders.X_AUTH_TOKEN, RequestHelper.ACCESS_TOKEN); + headers.add(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); String token = HeaderUtils.getAuthToken(headers); - Assert.assertEquals(RequestHelper.ACCESS_TOKEN, token); + Assert.assertEquals(OCCITestHelper.ACCESS_TOKEN, token); } @Test(expected = OCCIException.class) @@ -115,7 +115,7 @@ public void testGetCategoryWrongSyntax() { @Test public void testValidContentType() { headers.add(HeaderUtils.normalize(OCCIHeaders.CONTENT_TYPE), - RequestHelper.CONTENT_TYPE_OCCI); + OCCITestHelper.CONTENT_TYPE_OCCI); HeaderUtils.checkOCCIContentType(headers); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java index 4b17c4d6..4b207444 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java @@ -10,7 +10,7 @@ public class TestInstance { @Test public void testParteId() { String textResponse = "X-OCCI-Location: http://localhost:8787/compute/c1490207-6be7-4303-a41c-f8a4b1b9c25d"; - Instance instance = Instance.parseInstanceId(textResponse); + Instance instance = Instance.parseInstance(textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatLocation()); } @@ -38,7 +38,7 @@ public void testParseDetails() { + "X-OCCI-Attribute: occi.compute.cores=\"1\"\n" + "X-OCCI-Attribute: occi.compute.hostname=\"server-c1490207-6be7-4303-a41c-f8a4b1b9c25d\"\n" + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; - Instance instance = Instance.parseInstanceDetails(textResponse); + Instance instance = Instance.parseInstance(textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java similarity index 93% rename from src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java rename to src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 448aa167..4ae413aa 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/RequestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -22,7 +22,7 @@ import org.restlet.Component; import org.restlet.data.Protocol; -public class RequestHelper { +public class OCCITestHelper { public static String INSTANCE_ID = "1234567ujhgf45hdb4w"; public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; @@ -48,7 +48,8 @@ public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin iden component.start(); } - public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { + public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlugin identityPlugin, + List requestsToAdd) throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); @@ -57,10 +58,10 @@ public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlug facade.setIdentityPlugin(identityPlugin); requests = new RequestRepository(); - Request request = new Request("1", RequestHelper.ACCESS_TOKEN, INSTANCE_ID, - null, null, null, null); - requests.addRequest(RequestHelper.USER_MOCK, request); facade.setRequests(requests); + for (Request request : requestsToAdd) { + requests.addRequest(OCCITestHelper.USER_MOCK, request); + } component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); From 43bdc4a9b216f658826830f9eb5e93917597b242 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Thu, 24 Apr 2014 15:26:30 -0300 Subject: [PATCH 039/185] Changing Cert position. --- .../java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 87d33be1..539b3d8a 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -26,6 +26,7 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, Element statusEl = iq.getElement() .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE) .addElement("status"); + iq.getElement().addElement("cert"); statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); @@ -39,7 +40,6 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, flavorElement.addElement("capacity").setText( f.getCapacity().toString()); } - statusEl.addElement("cert"); packetSender.syncSendPacket(iq); } @@ -65,6 +65,7 @@ private static ArrayList getMembersFromIQ( while (itemIterator.hasNext()) { Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); + //TODO get certificate Element statusEl = itemEl.element("status"); String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); From 13008ec2ef25afcb0bf82b75ff5b5722fa2fabf1 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Thu, 24 Apr 2014 20:39:42 +0200 Subject: [PATCH 040/185] First bits on get remote instance --- .../manager/xmpp/ManagerPacketHelper.java | 23 +++++++++++++++++++ .../manager/xmpp/ManagerXmppComponent.java | 1 + 2 files changed, 24 insertions(+) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 87d33be1..3553b578 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -12,6 +12,7 @@ import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.Request; import org.jamppa.component.PacketSender; import org.xmpp.packet.IQ; @@ -119,4 +120,26 @@ public static String remoteRequest(Request request, .element("instance") .elementText("id"); } + + public static Instance getRemoteInstance(Request request, + String memberAddress, PacketSender packetSender) { + IQ iq = new IQ(); + iq.setTo(memberAddress); + Element queryEl = iq.getElement().addElement("query", + ManagerXmppComponent.GETINSTANCE_NAMESPACE); + Element instanceEl = queryEl.addElement("instance"); + instanceEl.addElement("id").setText(request.getInstanceId()); + + IQ response = (IQ) packetSender.syncSendPacket(iq); + if (response.getError() != null) { + return null; + } + + return parseInstance(response.getElement().element("query") + .element("instance")); + } + + private static Instance parseInstance(Element instanceEl) { + return null; + } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index b49f9ffb..829d0dbf 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -12,6 +12,7 @@ public class ManagerXmppComponent extends XMPPComponent { public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; public static final String REQUEST_NAMESPACE = "http://fogbowcloud.org/manager/request"; + public static final String GETINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/getinstance"; private static long PERIOD = 100; private ManagerFacade managerFacade; From 4e562139fd866b0911e5501f3783016df4582eb3 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Thu, 24 Apr 2014 15:42:04 -0300 Subject: [PATCH 041/185] Fixing cert location. --- .../java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 539b3d8a..5280bdb1 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -26,7 +26,7 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, Element statusEl = iq.getElement() .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE) .addElement("status"); - iq.getElement().addElement("cert"); + iq.getElement().element("query").addElement("cert"); statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); From e409272fa1706bdd401c9acbe771f33e5ddee4c8 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 24 Apr 2014 16:37:05 -0300 Subject: [PATCH 042/185] Implementing gerRemoteInstance --- .../manager/occi/instance/Instance.java | 30 ++++--- .../manager/xmpp/ManagerPacketHelper.java | 86 ++++++++++++++++++- .../manager/xmpp/ManagerXmppComponent.java | 1 + 3 files changed, 104 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 1bcf3ae5..0f336d53 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -158,8 +158,16 @@ public static class Link { private static final String NAME_LINK = "Link:"; - private String link; - private Map itens; + private String name; + private Map attributes; + + public Link() { + } + + public Link(String name, Map attributes) { + this.name = name; + this.attributes = attributes; + } public static Link parseLink(String line){ Link link = new Link(); @@ -169,30 +177,30 @@ public static Link parseLink(String line){ for (String block : blockLine) { if(block.contains(NAME_LINK)){ String[] blockValues = block.split(":"); - link.setLink(blockValues[1].replace("\"", "").trim()); + link.setName(blockValues[1].replace("\"", "").trim()); }else{ String[] blockValues = block.split("="); itens.put(blockValues[0].replace("\"", "").trim(), blockValues[1].replace("\"", "").trim()); } } - link.setItens(itens); + link.setAttributes(itens); return link; } public String toOCCIMessageFormatLink(){ String itensMessageFormat = ""; - for (String key : this.itens.keySet()) { - itensMessageFormat += " " + key + "=\"" + this.itens.get(key) + "\";"; + for (String key : this.attributes.keySet()) { + itensMessageFormat += " " + key + "=\"" + this.attributes.get(key) + "\";"; } - return NAME_LINK + " " + this.link + ";" + itensMessageFormat; + return NAME_LINK + " " + this.name + ";" + itensMessageFormat; } - public void setLink(String link) { - this.link = link; + public void setName(String name) { + this.name = name; } - public void setItens(Map itens){ - this.itens = itens; + public void setAttributes(Map attributes){ + this.attributes = attributes; } } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 3553b578..04e9d222 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -1,9 +1,11 @@ package org.fogbowcloud.manager.xmpp; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Map.Entry; import org.dom4j.Attribute; @@ -12,7 +14,12 @@ import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.instance.Instance; +import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; import org.jamppa.component.PacketSender; import org.xmpp.packet.IQ; @@ -137,9 +144,84 @@ public static Instance getRemoteInstance(Request request, return parseInstance(response.getElement().element("query") .element("instance")); - } + } + + public static void getRemoteResponseDelete(Request request, + String memberAddress, PacketSender packetSender) { + IQ iq = new IQ(); + iq.setTo(memberAddress); + Element queryEl = iq.getElement().addElement("query", + ManagerXmppComponent.REMOVEINSTACE_NAMESPACE); + Element instanceEl = queryEl.addElement("instance"); + instanceEl.addElement("id").setText(request.getInstanceId()); + + IQ response = (IQ) packetSender.syncSendPacket(iq); + if (response.getError() != null) { + } + + String error = response.getElement().element("error").getText(); + if(error.equals("NOT_FOUND")){ + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } + } + @SuppressWarnings("unchecked") private static Instance parseInstance(Element instanceEl) { - return null; + String id = instanceEl.element("id").getText(); + + Element linkEl = instanceEl.element("link"); + String linkName = linkEl.elementText("name"); + Iterator linkAttributeIterator = linkEl.elementIterator("attribute"); + + Map attributesLink = new HashMap(); + while (linkAttributeIterator.hasNext()) { + Element itemAttributeEl = (Element) linkAttributeIterator.next(); + String key = itemAttributeEl.getStringValue(); + String value = itemAttributeEl.getText(); + attributesLink.put(key, value); + } + Link link = new Link(linkName, attributesLink); + + Iterator resourceIterator = instanceEl.elementIterator("resource"); + List resources = new ArrayList(); + while (resourceIterator.hasNext()) { + Element itemResourseEl = (Element) resourceIterator.next(); + String termCategory = itemResourseEl.element("category").element("term").getText(); + String schemeCategory = itemResourseEl.element("category").element("scheme").getText(); + String classCategory = itemResourseEl.element("category").element("class").getText(); + Category category = new Category(termCategory, schemeCategory, classCategory); + + Iterator resourceAttributeIterator = instanceEl.elementIterator("attribute"); + List resourceAttributes = new ArrayList(); + while (resourceAttributeIterator.hasNext()) { + Element itemResourseAttributeEl = (Element) resourceAttributeIterator.next(); + resourceAttributes.add(itemResourseAttributeEl.getText()); + } + + Iterator resourceActionsIterator = instanceEl.elementIterator("action"); + List resourceActions = new ArrayList(); + while (resourceActionsIterator.hasNext()) { + Element itemResourseActionEl = (Element) resourceActionsIterator.next(); + resourceActions.add(itemResourseActionEl.getText()); + } + + String location = itemResourseEl.element("location").getText(); + String title = itemResourseEl.element("title").getText(); + String rel = itemResourseEl.element("rel").getText(); + + resources.add(new Resource(category, resourceAttributes, resourceActions, location, title, rel)); + } + + Iterator attributesIterator = instanceEl.elementIterator("attribute"); + + Map attributes = new HashMap(); + while (attributesIterator.hasNext()) { + Element attributeEl = (Element) attributesIterator.next(); + String key = attributeEl.getStringValue(); + String value = attributeEl.getText(); + attributes.put(key, value); + } + + return new Instance(id, resources, attributes, link); } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 829d0dbf..1ebca4b5 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -13,6 +13,7 @@ public class ManagerXmppComponent extends XMPPComponent { public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; public static final String REQUEST_NAMESPACE = "http://fogbowcloud.org/manager/request"; public static final String GETINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/getinstance"; + public static final String REMOVEINSTACE_NAMESPACE = "http://fogbowcloud.org/manager/removoinstace"; private static long PERIOD = 100; private ManagerFacade managerFacade; From c0e18a42287054a885ee4799095ed0fac3a40b31 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Thu, 24 Apr 2014 21:50:24 +0200 Subject: [PATCH 043/185] Implementing XMPP handlers for get and remove. --- .../manager/occi/instance/Instance.java | 8 ++ .../manager/xmpp/GetInstanceHandler.java | 81 +++++++++++++++++++ .../manager/xmpp/ManagerPacketHelper.java | 2 +- .../manager/xmpp/ManagerXmppComponent.java | 4 +- .../manager/xmpp/RemoveInstanceHandler.java | 44 ++++++++++ 5 files changed, 137 insertions(+), 2 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java create mode 100644 src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 0f336d53..4d8ec981 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -199,8 +199,16 @@ public void setName(String name) { this.name = name; } + public String getName() { + return name; + } + public void setAttributes(Map attributes){ this.attributes = attributes; } + + public Map getAttributes() { + return attributes; + } } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java new file mode 100644 index 00000000..4da69855 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java @@ -0,0 +1,81 @@ +package org.fogbowcloud.manager.xmpp; + +import java.util.List; +import java.util.Map.Entry; + +import org.dom4j.Element; +import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.instance.Instance; +import org.fogbowcloud.manager.occi.instance.Instance.Link; +import org.jamppa.component.handler.AbstractQueryHandler; +import org.xmpp.packet.IQ; +import org.xmpp.packet.PacketError.Condition; + +public class GetInstanceHandler extends AbstractQueryHandler { + + private ManagerFacade facade; + + public GetInstanceHandler(ManagerFacade facade) { + super(ManagerXmppComponent.GETINSTANCE_NAMESPACE); + this.facade = facade; + } + + @Override + public IQ handle(IQ query) { + String instanceId = query.getElement().element("instance") + .elementText("id"); + Instance instance = facade.getInstanceForRemoteMember(instanceId); + + IQ response = IQ.createResultIQ(query); + if (instance == null) { + response.setError(Condition.item_not_found); + return response; + } + + Element queryEl = response.getElement().addElement("query", + ManagerXmppComponent.GETINSTANCE_NAMESPACE); + Element instanceEl = queryEl.addElement("instance"); + instanceEl.addElement("id").setText(instanceId); + + Element linkEl = instanceEl.addElement("link"); + Link link = instance.getLink(); + linkEl.addElement("link").setText(link.getName()); + for (Entry linkAtt : link.getAttributes().entrySet()) { + Element attributeEl = linkEl.addElement("attribute"); + attributeEl.addAttribute("val", linkAtt.getKey()); + attributeEl.setText(linkAtt.getValue()); + } + + List resources = instance.getResources(); + for (Resource resource : resources) { + Element resourceEl = instanceEl.addElement("resource"); + Element categoryEl = resourceEl.addElement("category"); + + Category category = resource.getCategory(); + categoryEl.addElement("term").setText(category.getTerm()); + categoryEl.addElement("scheme").setText(category.getScheme()); + categoryEl.addElement("class").setText(category.getCatClass()); + for (String attribute : resource.getAttributes()) { + categoryEl.addElement("attribute").setText(attribute); + } + for (String action : resource.getActions()) { + categoryEl.addElement("action").setText(action); + } + + resourceEl.addElement("location").setText(resource.getLocation()); + resourceEl.addElement("title").setText(resource.getTitle()); + resourceEl.addElement("rel").setText(resource.getRel()); + } + + for (Entry instanceAtt : instance.getAttributes().entrySet()) { + Element attributeEl = instanceEl.addElement("attribute"); + attributeEl.addAttribute("val", instanceAtt.getKey()); + attributeEl.setText(instanceAtt.getValue()); + } + + return response; + } + +} diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index a3522daa..2ea09dda 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -152,7 +152,7 @@ public static void getRemoteResponseDelete(Request request, IQ iq = new IQ(); iq.setTo(memberAddress); Element queryEl = iq.getElement().addElement("query", - ManagerXmppComponent.REMOVEINSTACE_NAMESPACE); + ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); instanceEl.addElement("id").setText(request.getInstanceId()); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 1ebca4b5..2306368b 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -13,7 +13,7 @@ public class ManagerXmppComponent extends XMPPComponent { public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; public static final String REQUEST_NAMESPACE = "http://fogbowcloud.org/manager/request"; public static final String GETINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/getinstance"; - public static final String REMOVEINSTACE_NAMESPACE = "http://fogbowcloud.org/manager/removoinstace"; + public static final String REMOVEINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/removeinstance"; private static long PERIOD = 100; private ManagerFacade managerFacade; @@ -24,6 +24,8 @@ public ManagerXmppComponent(String jid, String password, String server, int port, ManagerFacade managerFacade) { super(jid, password, server, port); this.managerFacade = managerFacade; + addGetHandler(new GetInstanceHandler(managerFacade)); + addSetHandler(new RemoveInstanceHandler(managerFacade)); } public void init() { diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java new file mode 100644 index 00000000..3c51322d --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java @@ -0,0 +1,44 @@ +package org.fogbowcloud.manager.xmpp; + +import org.apache.http.HttpStatus; +import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.jamppa.component.handler.AbstractQueryHandler; +import org.xmpp.packet.IQ; +import org.xmpp.packet.PacketError.Condition; + +public class RemoveInstanceHandler extends AbstractQueryHandler { + + private ManagerFacade facade; + + public RemoveInstanceHandler(ManagerFacade facade) { + super(ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); + this.facade = facade; + } + + @Override + public IQ handle(IQ query) { + String instanceId = query.getElement().element("instance") + .elementText("id"); + IQ response = IQ.createResultIQ(query); + try { + facade.removeInstanceForRemoteMember(instanceId); + } catch (OCCIException e) { + response.setError(getCondition(e)); + } + return response; + } + + private Condition getCondition(OCCIException e) { + switch (e.getStatus().getCode()) { + case HttpStatus.SC_NOT_FOUND: + return Condition.item_not_found; + case HttpStatus.SC_UNAUTHORIZED: + return Condition.not_authorized; + case HttpStatus.SC_BAD_REQUEST: + return Condition.bad_request; + default: + return Condition.internal_server_error; + } + } +} From f1e4ecb65ab91cea394461f2743c2aec5676eddc Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Thu, 24 Apr 2014 21:58:01 +0200 Subject: [PATCH 044/185] Raising propert exceptions during remote instance deletion --- .../manager/xmpp/ManagerPacketHelper.java | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 2ea09dda..3d93e2c3 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -24,6 +24,8 @@ import org.jamppa.component.PacketSender; import org.xmpp.packet.IQ; import org.xmpp.packet.IQ.Type; +import org.xmpp.packet.PacketError; +import org.xmpp.packet.PacketError.Condition; public class ManagerPacketHelper { @@ -106,6 +108,7 @@ public static String remoteRequest(Request request, String memberAddress, PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(memberAddress); + iq.setType(Type.set); Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.REQUEST_NAMESPACE); for (Category category : request.getCategories()) { @@ -133,6 +136,7 @@ public static Instance getRemoteInstance(Request request, String memberAddress, PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(memberAddress); + iq.setType(Type.get); Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.GETINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); @@ -147,10 +151,11 @@ public static Instance getRemoteInstance(Request request, .element("instance")); } - public static void getRemoteResponseDelete(Request request, + public static void deleteRemoteInstace(Request request, String memberAddress, PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(memberAddress); + iq.setType(Type.set); Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); @@ -158,14 +163,21 @@ public static void getRemoteResponseDelete(Request request, IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - } - - String error = response.getElement().element("error").getText(); - if(error.equals("NOT_FOUND")){ - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + raiseException(response.getError()); } } + private static void raiseException(PacketError error) { + Condition condition = error.getCondition(); + if (condition.equals(Condition.item_not_found)) { + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } + if (condition.equals(Condition.not_authorized)) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } + @SuppressWarnings("unchecked") private static Instance parseInstance(Element instanceEl) { String id = instanceEl.element("id").getText(); From ad03754e6f16b0284cf506c733a0a29933ed4189 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 24 Apr 2014 17:01:48 -0300 Subject: [PATCH 045/185] Fixing parseInstance --- .../org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 3d93e2c3..1ae2cc98 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -189,7 +189,7 @@ private static Instance parseInstance(Element instanceEl) { Map attributesLink = new HashMap(); while (linkAttributeIterator.hasNext()) { Element itemAttributeEl = (Element) linkAttributeIterator.next(); - String key = itemAttributeEl.getStringValue(); + String key = itemAttributeEl.attributeValue("val"); String value = itemAttributeEl.getText(); attributesLink.put(key, value); } @@ -230,7 +230,7 @@ private static Instance parseInstance(Element instanceEl) { Map attributes = new HashMap(); while (attributesIterator.hasNext()) { Element attributeEl = (Element) attributesIterator.next(); - String key = attributeEl.getStringValue(); + String key = attributeEl.attributeValue("val"); String value = attributeEl.getText(); attributes.put(key, value); } From a228b2e3ceba4c97f98459abc469917446a1c7de Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Thu, 24 Apr 2014 22:13:26 +0200 Subject: [PATCH 046/185] Added handler for remote requests. --- .../manager/core/ManagerFacade.java | 2 +- .../manager/xmpp/GetInstanceHandler.java | 4 +- .../manager/xmpp/ManagerPacketHelper.java | 14 +++++ .../manager/xmpp/ManagerXmppComponent.java | 1 + .../manager/xmpp/RemoveInstanceHandler.java | 21 +------ .../manager/xmpp/RequestInstanceHandler.java | 60 +++++++++++++++++++ 6 files changed, 81 insertions(+), 21 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index b30ef3d2..caadb9fb 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -182,7 +182,7 @@ public Request getRequest(String authToken, String requestId) { return requests.get(requestId); } - public String createRemoteRequest(List categories, Map xOCCIAtt) { + public String createRequestForRemoteMember(List categories, Map xOCCIAtt) { String token = getFederationUserToken(); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java index 4da69855..f97fc1b0 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java @@ -24,8 +24,8 @@ public GetInstanceHandler(ManagerFacade facade) { @Override public IQ handle(IQ query) { - String instanceId = query.getElement().element("instance") - .elementText("id"); + String instanceId = query.getElement().element("query") + .element("instance").elementText("id"); Instance instance = facade.getInstanceForRemoteMember(instanceId); IQ response = IQ.createResultIQ(query); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 1ae2cc98..378a740f 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.Map.Entry; +import org.apache.http.HttpStatus; import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; @@ -237,4 +238,17 @@ private static Instance parseInstance(Element instanceEl) { return new Instance(id, resources, attributes, link); } + + public static Condition getCondition(OCCIException e) { + switch (e.getStatus().getCode()) { + case HttpStatus.SC_NOT_FOUND: + return Condition.item_not_found; + case HttpStatus.SC_UNAUTHORIZED: + return Condition.not_authorized; + case HttpStatus.SC_BAD_REQUEST: + return Condition.bad_request; + default: + return Condition.internal_server_error; + } + } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 2306368b..1ea8fb21 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -26,6 +26,7 @@ public ManagerXmppComponent(String jid, String password, String server, this.managerFacade = managerFacade; addGetHandler(new GetInstanceHandler(managerFacade)); addSetHandler(new RemoveInstanceHandler(managerFacade)); + addSetHandler(new RequestInstanceHandler(managerFacade)); } public void init() { diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java index 3c51322d..70c46c33 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java @@ -1,11 +1,9 @@ package org.fogbowcloud.manager.xmpp; -import org.apache.http.HttpStatus; import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.occi.core.OCCIException; import org.jamppa.component.handler.AbstractQueryHandler; import org.xmpp.packet.IQ; -import org.xmpp.packet.PacketError.Condition; public class RemoveInstanceHandler extends AbstractQueryHandler { @@ -18,27 +16,14 @@ public RemoveInstanceHandler(ManagerFacade facade) { @Override public IQ handle(IQ query) { - String instanceId = query.getElement().element("instance") - .elementText("id"); + String instanceId = query.getElement().element("query") + .element("instance").elementText("id"); IQ response = IQ.createResultIQ(query); try { facade.removeInstanceForRemoteMember(instanceId); } catch (OCCIException e) { - response.setError(getCondition(e)); + response.setError(ManagerPacketHelper.getCondition(e)); } return response; } - - private Condition getCondition(OCCIException e) { - switch (e.getStatus().getCode()) { - case HttpStatus.SC_NOT_FOUND: - return Condition.item_not_found; - case HttpStatus.SC_UNAUTHORIZED: - return Condition.not_authorized; - case HttpStatus.SC_BAD_REQUEST: - return Condition.bad_request; - default: - return Condition.internal_server_error; - } - } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java new file mode 100644 index 00000000..f91defd3 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java @@ -0,0 +1,60 @@ +package org.fogbowcloud.manager.xmpp; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.dom4j.Element; +import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.jamppa.component.handler.AbstractQueryHandler; +import org.xmpp.packet.IQ; +import org.xmpp.packet.PacketError.Condition; + +public class RequestInstanceHandler extends AbstractQueryHandler { + + private ManagerFacade facade; + + public RequestInstanceHandler(ManagerFacade facade) { + super(ManagerXmppComponent.REQUEST_NAMESPACE); + this.facade = facade; + } + + @SuppressWarnings("unchecked") + @Override + public IQ handle(IQ query) { + Element queryEl = query.getElement().element("query"); + List categories = new LinkedList(); + List categoriesEl = queryEl.elements("category"); + for (Element categoryEl : categoriesEl) { + Category category = new Category( + categoryEl.elementText("term"), + categoryEl.elementText("scheme"), + categoryEl.elementText("class")); + categories.add(category); + } + Map xOCCIAtt = new HashMap(); + List attributesEl = queryEl.elements("attribute"); + for (Element attributeEl : attributesEl) { + xOCCIAtt.put(attributeEl.attributeValue("var"), attributeEl.getText()); + } + + IQ response = IQ.createResultIQ(query); + try { + String instanceId = facade.createRequestForRemoteMember(categories, xOCCIAtt); + if (instanceId == null) { + response.setError(Condition.item_not_found); + } else { + Element queryResponseEl = response.getElement().addElement("query", + ManagerXmppComponent.REQUEST_NAMESPACE); + queryResponseEl.addElement("instance").addElement("id") + .setText(instanceId); + } + } catch (OCCIException e) { + response.setError(ManagerPacketHelper.getCondition(e)); + } + return response; + } +} From 87b2beb913758171f870379ac21b3c8ca2e46707 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 24 Apr 2014 17:46:18 -0300 Subject: [PATCH 047/185] Implement getResourceInfo in ComputeOpenStack using compute v2 API. --- manager.conf.example | 8 +- .../manager/core/ManagerFacade.java | 4 +- .../openstack/OpenStackComputePlugin.java | 92 +++++++++++++++---- .../occi/plugins/TestComputeOpenStack.java | 2 +- 4 files changed, 80 insertions(+), 26 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index 8f315c90..e8365fb4 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -4,7 +4,8 @@ xmpp_host=127.0.0.1 xmpp_port=5347 compute_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackComputePlugin -compute_openstack_url=http://localhost:8182 +compute_openstack_occi_url=http://localhost:8182 +compute_openstack_v2api_url=http://localhost:8182 compute_openstack_flavor_small=m1-small compute_openstack_flavor_medium=m1-medium compute_openstack_flavor_large=m1-large @@ -12,7 +13,8 @@ compute_openstack_flavor_large=m1-large identity_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackIdentityPlugin identity_openstack_url=http://localhost:5000 -federation.user.name=fogbow -federation.user.password=fogbow +federation_user_name=fogbow +federation_user_password=fogbow +federation_use_tenant_id=$tenantId scheduler_period=30000 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index caadb9fb..70aee8ef 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -194,8 +194,8 @@ public String createRequestForRemoteMember(List categories, Map fogTermToOpensStackCategory = new HashMap(); public OpenStackComputePlugin(Properties properties) { - this.computeEndpoint = properties.getProperty("compute_openstack_url") + COMPUTE_ENDPOINT; + this.computeOCCIEndpoint = properties.getProperty("compute_openstack_occi_url") + + COMPUTE_ENDPOINT; + this.computeV2APIEndepoint = properties.getProperty("compute_openstack_v2api_url") + + COMPUTE_V2_API_ENDEPOINT; + this.federationTenantId = properties.getProperty("federation_user_tenant_id"); + fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory("compute_openstack_flavor_small", properties)); fogTermToOpensStackCategory.put(RequestConstants.MEDIUM_TERM, @@ -80,7 +96,7 @@ public String requestInstance(String authToken, List categories, HttpClient httpCLient = new DefaultHttpClient(); HttpPost httpPost; try { - httpPost = new HttpPost(computeEndpoint); + httpPost = new HttpPost(computeOCCIEndpoint); httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); for (Category category : openStackCategories) { @@ -113,7 +129,7 @@ public Instance getInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { - httpGet = new HttpGet(computeEndpoint + instanceId); + httpGet = new HttpGet(computeOCCIEndpoint + instanceId); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -141,7 +157,7 @@ public List getInstances(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { - httpGet = new HttpGet(computeEndpoint); + httpGet = new HttpGet(computeOCCIEndpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); @@ -178,7 +194,7 @@ public void removeInstances(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeEndpoint); + httpDelete = new HttpDelete(computeOCCIEndpoint); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpDelete); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { @@ -201,7 +217,7 @@ public void removeInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeEndpoint + instanceId); + httpDelete = new HttpDelete(computeOCCIEndpoint + instanceId); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpDelete); @@ -224,23 +240,59 @@ public void removeInstance(String authToken, String instanceId) { @Override public ResourcesInfo getResourcesInfo(String authToken) { - // TODO Fake resources - String cpuIdle = "1000"; - String cpuInUse = "0"; - String memIdle = "2048000"; - String memInUse = "0"; - return new ResourcesInfo(null, cpuIdle, cpuInUse, memIdle, memInUse, getFlavors(cpuIdle, memIdle)); + HttpClient httpCLient = new DefaultHttpClient(); + HttpGet httpGet; + try { + httpGet = new HttpGet(computeV2APIEndepoint + federationTenantId + "/limits"); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + HttpResponse response = httpCLient.execute(httpGet); + + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + + String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); + String cpuInUse = getAttFromJson(TOTAL_CORES_USED_ATT, responseStr); + String maxMem = getAttFromJson(MAX_TOTAL_RAM_SIZE_ATT, responseStr); + String memInUse = getAttFromJson(TOTAL_RAM_USED_ATT, responseStr); + + int cpuIdle = Integer.parseInt(maxCpu) - Integer.parseInt(cpuInUse); + int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); + + return new ResourcesInfo(null, String.valueOf(cpuIdle), cpuInUse, + String.valueOf(memIdle), memInUse, getFlavors(cpuIdle, memIdle)); + + } catch (URISyntaxException e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); + } catch (HttpException e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); + } catch (IOException e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); + } + } + + private String getAttFromJson(String attName, String responseStr) { + try { + JSONObject root = new JSONObject(responseStr); + return root.getJSONObject(LIMITS).getJSONObject(ABSOLUTE).getString(attName).toString(); + } catch (JSONException e) { + return null; + } } - private List getFlavors(String cpuIdleStr, String memIdleStr) { - int cpuIdle = Integer.parseInt(cpuIdleStr); - int memIdle = Integer.parseInt(memIdleStr); + private List getFlavors(int cpuIdle, int memIdle) { List flavors = new ArrayList(); - - //flavors - int capacity = Math.min(cpuIdle / 1, memIdle / 2048); + // flavors + int capacity = Math.min(cpuIdle / 1, memIdle / 2048); Flavor smallFlavor = new Flavor(RequestConstants.SMALL_TERM, "1", "2048", capacity); - capacity = Math.min(cpuIdle / 2, memIdle / 4096); + capacity = Math.min(cpuIdle / 2, memIdle / 4096); Flavor mediumFlavor = new Flavor(RequestConstants.MEDIUM_TERM, "2", "4096", capacity); capacity = Math.min(cpuIdle / 4, memIdle / 8192); Flavor largeFlavor = new Flavor(RequestConstants.LARGE_TERM, "4", "8192", capacity); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index c0747644..331326e6 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -40,7 +40,7 @@ public class TestComputeOpenStack { @Before public void setUp() throws Exception { Properties properties = new Properties(); - properties.put("compute_openstack_url", URL); + properties.put("compute_openstack_occi_url", URL); properties.put("compute_openstack_flavor_small", ComputeApplication.SMALL_FLAVOR_TERM); properties.put("compute_openstack_flavor_medium", ComputeApplication.MEDIUM_FLAVOR_TERM); properties.put("compute_openstack_flavor_large", ComputeApplication.MEDIUM_FLAVOR_TERM); From af84be34f762154b413ef3e9e68cddc1298d913e Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 25 Apr 2014 09:21:08 -0300 Subject: [PATCH 048/185] Fixing GetCompute and DeleteCompute tests --- .../manager/occi/TestDeleteCompute.java | 54 ++++++++++++------- .../manager/occi/TestGetCompute.java | 36 +++++++++---- .../manager/occi/util/OCCITestHelper.java | 3 +- 3 files changed, 64 insertions(+), 29 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 395506ef..56b9553d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -7,6 +7,7 @@ import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; @@ -20,38 +21,44 @@ import org.mockito.Mockito; public class TestDeleteCompute { - - // TODO rename - OCCITestHelper requestHelper; + + public static String INSTANCE_ID = "1234567ujhgf45hdb4w"; + public static String OTHER_INSTANCE_ID = "otherInstanceId"; + + private OCCITestHelper helper; @Before public void setup() throws Exception { - this.requestHelper = new OCCITestHelper(); + this.helper = new OCCITestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.doNothing().when(computePlugin).removeInstances(OCCITestHelper.ACCESS_TOKEN); Mockito.doNothing().when(computePlugin) - .removeInstance(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.INSTANCE_ID); + .removeInstance(OCCITestHelper.ACCESS_TOKEN, INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); List requests = new LinkedList(); - Request request = new Request("1", OCCITestHelper.ACCESS_TOKEN, + Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, null, null); - request.setInstanceId(OCCITestHelper.INSTANCE_ID); - requests.add(request); + request1.setInstanceId(INSTANCE_ID); + requests.add(request1); + Request request2 = new Request("1", "otherToken", + "otherUser", null, null); + request2.setInstanceId(OTHER_INSTANCE_ID); + requests.add(request2); - this.requestHelper.initializeComponentCompute(computePlugin, identityPlugin, requests); + this.helper.initializeComponentCompute(computePlugin, identityPlugin, requests); } @After public void tearDown() throws Exception { - this.requestHelper.stopComponent(); + this.helper.stopComponent(); } @Test - public void TestDelete() throws Exception { + public void testDelete() throws Exception { HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + ""); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -60,11 +67,22 @@ public void TestDelete() throws Exception { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } + + @Test + public void testDeleteSpecificInstanceOtherUser() throws Exception { + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + OTHER_INSTANCE_ID); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + } @Test - public void TestDeleteSpecificInstanceFound() throws Exception { + public void testDeleteSpecificInstanceFound() throws Exception { HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE - + OCCITestHelper.INSTANCE_ID); + + INSTANCE_ID); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); @@ -74,7 +92,7 @@ public void TestDeleteSpecificInstanceFound() throws Exception { } @Test - public void TestDeleteSpecificInstanceNotFound() throws Exception { + public void testDeleteSpecificInstanceNotFound() throws Exception { HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + "wrong"); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -85,9 +103,9 @@ public void TestDeleteSpecificInstanceNotFound() throws Exception { } @Test - public void TestWrongAccessToken() throws Exception { + public void testWrongAccessToken() throws Exception { HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE - + OCCITestHelper.INSTANCE_ID); + + INSTANCE_ID); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); @@ -97,7 +115,7 @@ public void TestWrongAccessToken() throws Exception { } @Test - public void TestEmptyAccessToken() throws Exception { + public void testEmptyAccessToken() throws Exception { HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); @@ -108,7 +126,7 @@ public void TestEmptyAccessToken() throws Exception { } @Test - public void TestWrongContentType() throws Exception { + public void testWrongContentType() throws Exception { HttpDelete get = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE); get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 4ddaa6a9..3d01f340 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -29,8 +29,9 @@ public class TestGetCompute { private static final String INSTANCE_1_ID = "test1"; private static final String INSTANCE_2_ID = "test2"; + private static final String INSTANCE_3_ID_WITHOUT_USER = "test3"; - OCCITestHelper helper; + private OCCITestHelper helper; @Before public void setup() throws Exception { @@ -47,6 +48,8 @@ public void setup() throws Exception { Mockito.eq(INSTANCE_1_ID))).thenReturn(instance1); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.eq(INSTANCE_2_ID))).thenReturn(new Instance(INSTANCE_2_ID)); + Mockito.when(computePlugin.getInstance(Mockito.anyString(), + Mockito.eq(INSTANCE_3_ID_WITHOUT_USER))).thenReturn(instance1); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( @@ -61,6 +64,10 @@ public void setup() throws Exception { OCCITestHelper.USER_MOCK, null, null); request2.setInstanceId(INSTANCE_2_ID); requests.add(request2); + Request request3 = new Request("3", "token", + "user", null, null); + request3.setInstanceId(INSTANCE_3_ID_WITHOUT_USER); + requests.add(request3); this.helper.initializeComponentCompute(computePlugin, identityPlugin, requests); } @@ -71,19 +78,19 @@ public void tearDown() throws Exception{ } @Test - public void TestGetComputeOk() throws Exception{ + public void testGetComputeOk() throws Exception{ HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - Assert.assertEquals(2, OCCITestHelper.getRequestLocations(response).size()); + Assert.assertEquals(3, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test - public void TestGetSpecificInstanceFound() throws Exception { + public void testGetSpecificInstanceFound() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_1_ID); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -94,7 +101,7 @@ public void TestGetSpecificInstanceFound() throws Exception { } @Test - public void TestGetSpecificInstanceNotFound() throws Exception { + public void testGetSpecificInstanceNotFound() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + "wrong"); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -105,7 +112,18 @@ public void TestGetSpecificInstanceNotFound() throws Exception { } @Test - public void TestWrongContentType() throws Exception { + public void testGetSpecificInstanceOtherUser() throws Exception { + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_3_ID_WITHOUT_USER); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + } + + @Test + public void testWrongContentType() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -116,7 +134,7 @@ public void TestWrongContentType() throws Exception { } @Test - public void TestAccessToken() throws Exception { + public void testAccessToken() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -127,7 +145,7 @@ public void TestAccessToken() throws Exception { } @Test - public void TestWrongAccessToken() throws Exception { + public void testWrongAccessToken() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_1_ID); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); @@ -138,7 +156,7 @@ public void TestWrongAccessToken() throws Exception { } @Test - public void TestEmptyAccessToken() throws Exception { + public void testEmptyAccessToken() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 4ae413aa..3fa0f37f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -24,7 +24,6 @@ public class OCCITestHelper { - public static String INSTANCE_ID = "1234567ujhgf45hdb4w"; public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; public static final String INVALID_TOKEN = "invalid-token"; public static final String CONTENT_TYPE_OCCI = "text/occi"; @@ -34,7 +33,7 @@ public class OCCITestHelper { public static final int ENDPOINT_PORT = 8182; private Component component; - RequestRepository requests; + private RequestRepository requests; public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { component = new Component(); From 10d8aff686d035aeb95866f86b0998bbf71a004c Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Fri, 25 Apr 2014 17:25:06 -0300 Subject: [PATCH 049/185] Changing ManagerFacadeLocation, implementig certificateHandlerHelper --- manager.conf.example | 20 -------- .../core/CertificateHandlerHelper.java | 51 +++++++++++++++++++ .../core/TestCertificateOperations.java | 30 +++++++++++ .../{xmpp => core}/TestManagerFacade.java | 2 +- src/test/resources/manager.conf.test | 1 + src/test/resources/server.crt | 20 ++++++++ 6 files changed, 103 insertions(+), 21 deletions(-) delete mode 100644 manager.conf.example create mode 100644 src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java create mode 100644 src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java rename src/test/java/org/fogbowcloud/manager/{xmpp => core}/TestManagerFacade.java (98%) create mode 100644 src/test/resources/manager.conf.test create mode 100644 src/test/resources/server.crt diff --git a/manager.conf.example b/manager.conf.example deleted file mode 100644 index e8365fb4..00000000 --- a/manager.conf.example +++ /dev/null @@ -1,20 +0,0 @@ -xmpp_jid=manager.test.com -xmpp_password=password -xmpp_host=127.0.0.1 -xmpp_port=5347 - -compute_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackComputePlugin -compute_openstack_occi_url=http://localhost:8182 -compute_openstack_v2api_url=http://localhost:8182 -compute_openstack_flavor_small=m1-small -compute_openstack_flavor_medium=m1-medium -compute_openstack_flavor_large=m1-large - -identity_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackIdentityPlugin -identity_openstack_url=http://localhost:5000 - -federation_user_name=fogbow -federation_user_password=fogbow -federation_use_tenant_id=$tenantId - -scheduler_period=30000 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java new file mode 100644 index 00000000..eb0ee12f --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java @@ -0,0 +1,51 @@ +package org.fogbowcloud.manager.core; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Properties; + +import org.apache.commons.codec.binary.Base64; + +public class CertificateHandlerHelper { + private static final String CERTIFICATE_KEY = "certificate"; + private final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; + + public static String ConvertToSendingFormat() throws CertificateException, + IOException { + Certificate cert = getCertificate(); + byte[] base64Certificate = Base64.encodeBase64(cert.getEncoded()); + return new String(base64Certificate); + } + + public static Certificate getCertificate() throws IOException, + CertificateException { + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(CONFIG_PATH); + properties.load(input); + String path = properties.getProperty(CERTIFICATE_KEY); + + final CertificateFactory certFactory = CertificateFactory + .getInstance("X.509"); + input = new FileInputStream(path); + final Certificate cert = (Certificate) certFactory + .generateCertificate(new FileInputStream(path)); + input.close(); + return cert; + } + + public static Certificate ConvertToCertificateFormat( + String base64StringCertificate) throws CertificateException { + byte[] base64BytesCertificate = base64StringCertificate.getBytes(); + CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + byte[] certificateBytes = Base64.decodeBase64(base64BytesCertificate); + InputStream in = new ByteArrayInputStream(certificateBytes); + X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in); + return cert; + } +} diff --git a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java new file mode 100644 index 00000000..a8cf187f --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java @@ -0,0 +1,30 @@ +package org.fogbowcloud.manager.core; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Properties; + +import org.apache.commons.codec.binary.Base64; +import org.junit.Assert; +import org.junit.Test; + +public class TestCertificateOperations { + + private static final String CERTIFICATE_KEY = "certificate"; + private final String DEFAULT_PATH_TEST_VALUE_EMPTY = "src/test/resources/manager.conf.test"; + + @Test + public void testGetCertificate() throws IOException, CertificateException { + Certificate cert = CertificateHandlerHelper.getCertificate(); + Certificate result = CertificateHandlerHelper + .ConvertToCertificateFormat(CertificateHandlerHelper + .ConvertToSendingFormat()); + Assert.assertEquals(cert, result); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java similarity index 98% rename from src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java rename to src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java index 4e5d468e..2d32b35e 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.xmpp; +package org.fogbowcloud.manager.core; import java.util.ArrayList; import java.util.LinkedList; diff --git a/src/test/resources/manager.conf.test b/src/test/resources/manager.conf.test new file mode 100644 index 00000000..05322761 --- /dev/null +++ b/src/test/resources/manager.conf.test @@ -0,0 +1 @@ +certificate= src/test/resources/server.crt \ No newline at end of file diff --git a/src/test/resources/server.crt b/src/test/resources/server.crt new file mode 100644 index 00000000..76e57fe0 --- /dev/null +++ b/src/test/resources/server.crt @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDMDCCAhgCCQChFPK3nBHHrDANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJC +UjEQMA4GA1UECAwHUGFyYWliYTEWMBQGA1UEBwwNQ2FtcGluYSBHYW5kZTEhMB8G +A1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMB4XDTE0MDQyNTE4MDg0NVoX +DTE1MDQyNTE4MDg0NVowWjELMAkGA1UEBhMCQlIxEDAOBgNVBAgMB1BhcmFpYmEx +FjAUBgNVBAcMDUNhbXBpbmEgR2FuZGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdp +dHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANZToOrP +g4/Y23J0K3nR9Wk9Wi/uUzvAxxPJtv2FgUc49fgZ0pyikLk8z61MTjGj00wYdF16 +kRd5nUcz64jWHLutlQfkXAOyPkk8l4Juq++9CoUvXiU8zp5dWbj2E0fKgqZMASPV +uJWdAH0mWiuL7wYaSGkhmiEKlbjUlQ7bwWIuX+HvLfZMBJonOROTU/vYfpz4gFNU +Si5abKBWSGvrG2z8wdyKILAdhefnqPqmKdxYCbkFIge9ytvoNt8yY8VTthT080Nv +l+a7dWoTZMOvQRuOnCWNZt9Bszd0XUo5RkxNAyAGJJu8FqD96PX0ipAnDRqP1F6/ +mba9D46b5AEG33MCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEADaeMqWMTRGfDemWU +BmTFSPIeGzFFRiQ+ET8zntTJI+rrxkm6RV3o/R/7/fN33i7XzvvHnaYhhPQOKG2F +X5Yg6rp3fsQewl+QpmUtktTSIG05VK2VTMSmie9H119KUCtSjB9HWRPgw/dNjX7o +7hjdyiUDpvrtbEPtKoxKQ8SIBVG+eXmu+YAkaiqzkjYdjqVlHGgdaWqAr2SqRzGt +2JXAFb5pn+px8gegv+Kduu2HelC9Hsfsk19WPReZ76iBKJyHSDGVCEAt//MY6AX/ +W5I0UdoWqS5wMEh7yfNVDZ6CY2iRsnWKok5R1ETaShTfSnBq5xZ++OkzAwBfI2tF +A0em9w== +-----END CERTIFICATE----- From 4255b2edb7bcafa92150a4e0049a66bdc0416343 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 25 Apr 2014 17:39:40 -0300 Subject: [PATCH 050/185] Implementing and Refatoring XMPP tests. --- .../manager/core/ManagerFacade.java | 10 +- .../manager/occi/core/Resource.java | 21 +-- .../manager/occi/instance/Instance.java | 112 +++++++-------- .../manager/xmpp/GetInstanceHandler.java | 14 +- .../manager/xmpp/ManagerPacketHelper.java | 18 ++- .../manager/xmpp/RequestInstanceHandler.java | 2 +- .../manager/occi/core/TestInstance.java | 31 ++-- .../manager/occi/core/TestResource.java | 6 +- .../xmpp/TestDeleteRemoteInstance.java | 76 ++++++++++ .../manager/xmpp/TestGetRemoteInstance.java | 121 ++++++++++++++++ ...anagerComponent.java => TestIAmAlive.java} | 98 +------------ .../xmpp/TestRequestRemoteInstance.java | 85 +++++++++++ .../manager/xmpp/TestWhoIsAlive.java | 133 ++++++++++++++++++ .../manager/xmpp/util/ManagerTestHelper.java | 76 +++++++++- 14 files changed, 616 insertions(+), 187 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java create mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java rename src/test/java/org/fogbowcloud/manager/xmpp/{TestManagerComponent.java => TestIAmAlive.java} (57%) create mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java create mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 70aee8ef..6abee80a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -9,6 +9,7 @@ import java.util.TimerTask; import java.util.UUID; +import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; @@ -194,7 +195,8 @@ public String createRequestForRemoteMember(List categories, Map suppor } public String toHeader() { + String title = ""; + if (!getTitle().equals(null) || !getTitle().equals("")) { + title = "\"; title=\"" + getTitle(); + } + return category.getTerm() + "; scheme=\"" + category.getScheme() + "\"; class=\"" - + category.getCatClass() + "\" attributes=\"" + attributesToHeader() + "\" actions=\"" - + actionsToHeader() + "\" location=\"" + getLocation() + "\" title=\"" + getTitle() - + "\" rel=\"" + getRel() + "\""; + + category.getCatClass() + title + "\"; rel=\"" + getRel() + "\"; location=\"" + + getLocation() + "\"; attributes=\"" + attributesToHeader() + "\"; actions=\"" + + actionsToHeader() + "\""; } - + private String actionsToHeader() { String actionsString = ""; for (String action : getActions()) { actionsString += action + " "; } - return actionsString.trim(); + return actionsString.trim(); } - + private String attributesToHeader() { String attributesString = ""; for (String attribute : getAttributes()) { attributesString += attribute + " "; } - return attributesString.trim(); - } + return attributesString.trim(); + } public Category getCategory() { return category; diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 4d8ec981..1a6e6b03 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -1,7 +1,7 @@ package org.fogbowcloud.manager.occi.instance; import java.util.ArrayList; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -13,7 +13,7 @@ public class Instance { public static String PREFIX_DEFAULT_INSTANCE = "X-OCCI-Location: "; private static String PREFIX_DEFAULT_ATTRIBUTE = "X-OCCI-Attribute: "; private static String CATEGORY = "Category:"; - + private String id; private List resources; private Link link; @@ -21,25 +21,25 @@ public class Instance { public Instance() { } - + public Instance(String id) { this.id = id; - } - + } + public Instance(String id, List resources, Map attributes, Link link) { this(id); this.resources = resources; this.attributes = attributes; this.link = link; } - + public static Instance parseInstance(String textResponse) { return new Instance(textResponse.replace(PREFIX_DEFAULT_INSTANCE, "").trim()); } - + public static Instance parseInstance(String id, String textResponse) { List resources = new ArrayList(); - Map attributes = new HashMap(); + Map attributes = new LinkedHashMap(); Link link = null; String[] lines = textResponse.split("\n"); @@ -73,14 +73,12 @@ public static Instance parseInstance(String id, String textResponse) { } else if (blockValues[0].contains("location")) { location = blockValues[1].replace("\"", "").trim(); } else if (blockValues[0].contains("attributes")) { - String[] attributesValues = blockValues[1].replace( - "\"", "").split(" "); + String[] attributesValues = blockValues[1].replace("\"", "").split(" "); for (String attribute : attributesValues) { attributesResource.add(attribute); } } else if (blockValues[0].contains("actions")) { - String[] actionsValues = blockValues[1].replace( - "\"", "").split(" "); + String[] actionsValues = blockValues[1].replace("\"", "").split(" "); for (String action : actionsValues) { actionsResource.add(action); } @@ -88,44 +86,42 @@ public static Instance parseInstance(String id, String textResponse) { } } Category category = new Category(term, scheme, catClass); - resources.add(new Resource(category, attributesResource, - actionsResource, location, title, rel)); + resources.add(new Resource(category, attributesResource, actionsResource, location, + title, rel)); } else if (line.contains("Link")) { link = Link.parseLink(line); } else if (line.contains("X-OCCI-Attribute: ")) { - String[] blockLine = line.replace(PREFIX_DEFAULT_ATTRIBUTE, "") - .split("="); - attributes.put(blockLine[0], blockLine[1].replace("\"", "") - .trim()); + String[] blockLine = line.replace(PREFIX_DEFAULT_ATTRIBUTE, "").split("="); + attributes.put(blockLine[0], blockLine[1].replace("\"", "").trim()); } } return new Instance(id, resources, attributes, link); - } - - public String toOCCIMassageFormatLocation(){ + } + + public String toOCCIMassageFormatLocation() { return PREFIX_DEFAULT_INSTANCE + this.id; } - - public String toOCCIMassageFormatDetails(){ + + public String toOCCIMassageFormatDetails() { String messageFormat = ""; for (Resource resource : this.resources) { messageFormat += CATEGORY + " " + resource.toHeader() + "\n"; } - if (link != null){ + if (link != null) { messageFormat += this.link.toOCCIMessageFormatLink() + "\n"; } for (String key : this.attributes.keySet()) { - messageFormat += PREFIX_DEFAULT_ATTRIBUTE + key + "=\"" + attributes.get(key) + "\"\n"; + messageFormat += PREFIX_DEFAULT_ATTRIBUTE + key + "=\"" + attributes.get(key) + "\"\n"; } - - return messageFormat; - } - + + return messageFormat.trim(); + } + public void setId(String id) { this.id = id; } - + public List getResources() { return resources; } @@ -144,69 +140,75 @@ public void setAttributes(Map attributes) { public String getId() { return id; - } - + } + public Link getLink() { return link; } public void setLink(Link link) { this.link = link; - } - + } + public static class Link { - + private static final String NAME_LINK = "Link:"; - + private String name; - private Map attributes; - + private Map attributes; + public Link() { } - + public Link(String name, Map attributes) { this.name = name; this.attributes = attributes; } - - public static Link parseLink(String line){ + + public static Link parseLink(String line) { Link link = new Link(); - Map itens = new HashMap(); - + Map itens = new LinkedHashMap(); + String[] blockLine = line.split(";"); for (String block : blockLine) { - if(block.contains(NAME_LINK)){ + if (block.contains(NAME_LINK)) { String[] blockValues = block.split(":"); - link.setName(blockValues[1].replace("\"", "").trim()); - }else{ + link.setName(blockValues[1].replace("\"", "").trim()); + } else { String[] blockValues = block.split("="); - itens.put(blockValues[0].replace("\"", "").trim(), blockValues[1].replace("\"", "").trim()); + itens.put(blockValues[0].replace("\"", "").trim(), + blockValues[1].replace("\"", "").trim()); } } link.setAttributes(itens); return link; } - - public String toOCCIMessageFormatLink(){ + + public String toOCCIMessageFormatLink() { String itensMessageFormat = ""; + int cont = 0; for (String key : this.attributes.keySet()) { - itensMessageFormat += " " + key + "=\"" + this.attributes.get(key) + "\";"; + itensMessageFormat += " " + key + "=\"" + this.attributes.get(key) + "\""; + if(cont < this.attributes.keySet().size() - 1){ + itensMessageFormat += ";"; + } + cont++; } return NAME_LINK + " " + this.name + ";" + itensMessageFormat; } - + public void setName(String name) { this.name = name; } - + public String getName() { return name; } - - public void setAttributes(Map attributes){ + + public void setAttributes(Map attributes) { this.attributes = attributes; } - + public Map getAttributes() { return attributes; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java index f97fc1b0..64e71dd6 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java @@ -6,6 +6,7 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.Resource; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.instance.Instance.Link; @@ -26,9 +27,17 @@ public GetInstanceHandler(ManagerFacade facade) { public IQ handle(IQ query) { String instanceId = query.getElement().element("query") .element("instance").elementText("id"); - Instance instance = facade.getInstanceForRemoteMember(instanceId); + Instance instance = null; IQ response = IQ.createResultIQ(query); + + try { + instance = facade.getInstanceForRemoteMember(instanceId); + } catch (OCCIException e) { + response.setError(ManagerPacketHelper.getCondition(e)); + return response; + } + if (instance == null) { response.setError(Condition.item_not_found); return response; @@ -74,7 +83,8 @@ public IQ handle(IQ query) { attributeEl.addAttribute("val", instanceAtt.getKey()); attributeEl.setText(instanceAtt.getValue()); } - + + System.out.println(response.toString()); return response; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 378a740f..feb645b8 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -141,11 +141,19 @@ public static Instance getRemoteInstance(Request request, Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.GETINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); - instanceEl.addElement("id").setText(request.getInstanceId()); + try { + instanceEl.addElement("id").setText(request.getInstanceId()); + } catch (Exception e) { + // TODO: handle exception + } IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - return null; + if (response.getError().getCondition().equals( + Condition.item_not_found)) { + return null; + } + raiseException(response.getError()); } return parseInstance(response.getElement().element("query") @@ -184,7 +192,7 @@ private static Instance parseInstance(Element instanceEl) { String id = instanceEl.element("id").getText(); Element linkEl = instanceEl.element("link"); - String linkName = linkEl.elementText("name"); + String linkName = linkEl.element("link").getText(); Iterator linkAttributeIterator = linkEl.elementIterator("attribute"); Map attributesLink = new HashMap(); @@ -205,14 +213,14 @@ private static Instance parseInstance(Element instanceEl) { String classCategory = itemResourseEl.element("category").element("class").getText(); Category category = new Category(termCategory, schemeCategory, classCategory); - Iterator resourceAttributeIterator = instanceEl.elementIterator("attribute"); + Iterator resourceAttributeIterator = itemResourseEl.element("category").elementIterator("attribute"); List resourceAttributes = new ArrayList(); while (resourceAttributeIterator.hasNext()) { Element itemResourseAttributeEl = (Element) resourceAttributeIterator.next(); resourceAttributes.add(itemResourseAttributeEl.getText()); } - Iterator resourceActionsIterator = instanceEl.elementIterator("action"); + Iterator resourceActionsIterator = itemResourseEl.element("category").elementIterator("action"); List resourceActions = new ArrayList(); while (resourceActionsIterator.hasNext()) { Element itemResourseActionEl = (Element) resourceActionsIterator.next(); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java index f91defd3..7b3ab8f0 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java @@ -38,7 +38,7 @@ public IQ handle(IQ query) { Map xOCCIAtt = new HashMap(); List attributesEl = queryEl.elements("attribute"); for (Element attributeEl : attributesEl) { - xOCCIAtt.put(attributeEl.attributeValue("var"), attributeEl.getText()); + xOCCIAtt.put(attributeEl.attributeValue("var"), attributeEl.element("value").getText()); } IQ response = IQ.createResultIQ(query); diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java index 4b207444..9e1c1c25 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java @@ -8,14 +8,14 @@ public class TestInstance { @Test - public void testParteId() { - String textResponse = "X-OCCI-Location: http://localhost:8787/compute/c1490207-6be7-4303-a41c-f8a4b1b9c25d"; + public void testParseIdOneValue() { + String textResponse = "X-OCCI-Location: http://localhost:8787/compute/c1490"; Instance instance = Instance.parseInstance(textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatLocation()); } - - @Ignore + + //TODO refatoring @Test public void testParseDetails() { String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infrastructure#\"; class=\"kind\"; " @@ -23,12 +23,22 @@ public void testParseDetails() { + "location=\"http://localhost:8787/compute/\"; " + "attributes=\"occi.compute.architecture occi.compute.state{immutable} " + "occi.compute.speed occi.compute.memory occi.compute.cores occi.compute.hostname\"; " - + "actions=\"http://schemas.ogf.org/occi/infrastructure/compute/action#start http://schemas.ogf.org/occi/infrastructure/compute/action#stop " + + "actions=\"http://schemas.ogf.org/occi/infrastructure/compute/action#start http://sc" + + "hemas.ogf.org/occi/infrastructure/compute/action#stop " + "http://schemas.ogf.org/occi/infrastructure/compute/action#restart " + "http://schemas.ogf.org/occi/infrastructure/compute/action#suspend\"\n" - + "Category: os_vms; scheme=\"http://schemas.openstack.org/compute/instance#\"; class=\"mixin\"; location=\"http://localhost:8787/os_vms/\"; attributes=\"org.openstack.compute.console.vnc{immutable} org.openstack.compute.state{immutable}\"; actions=\"http://schemas.openstack.org/instance/action#chg_pwd http://schemas.openstack.org/instance/action#create_image\"\n" - + "Category: b4c4322e-1f6c-4cf4-be02-34cc385a3b29; scheme=\"http://schemas.openstack.org/template/os#\"; class=\"mixin\"; title=\"Image: cirros-0.3.1-x86_64-uec\"; rel=\"http://schemas.ogf.org/occi/infrastructure#os_tpl\"; location=\"http://localhost:8787/b4c4322e-1f6c-4cf4-be02-34cc385a3b29/\"\n" - + "Link: ; rel=\"http://schemas.ogf.org/occi/infrastructure#network\"; self=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"; category=\"http://schemas.ogf.org/occi/infrastructure#networkinterface http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface\"; occi.networkinterface.gateway=\"10.0.0.1\"; occi.networkinterface.mac=\"fa:16:3e:5b:9d:4d\"; occi.networkinterface.interface=\"eth0\"; occi.networkinterface.state=\"active\"; occi.networkinterface.allocation=\"static\"; occi.networkinterface.address=\"0.0.0.0\"; occi.core.source=\"/compute/c1490207-6be7-4303-a41c-f8a4b1b9c25d\"; occi.core.target=\"/network/admin\"; occi.core.id=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"\n" +// + "Category: os_vms; scheme=\"http://schemas.openstack.org/compute/instance#\"; class=\"mixin\"; location=\"http://localhost:8787/os_vms/\"; attributes=\"org.openstack.compute.console.vnc{immutable} org.openstack.compute.state{immutable}\"; actions=\"http://schemas.openstack.org/instance/action#chg_pwd http://schemas.openstack.org/instance/action#create_image\"\n" +// + "Category: b4c4322e-1f6c-4cf4-be02-34cc385a3b29; scheme=\"http://schemas.openstack.org/template/os#\"; class=\"mixin\"; title=\"Image: cirros-0.3.1-x86_64-uec\"; rel=\"http://schemas.ogf.org/occi/infrastructure#os_tpl\"; location=\"http://localhost:8787/b4c4322e-1f6c-4cf4-be02-34cc385a3b29/\"\n" + + "Link: ; rel=\"http://schemas.ogf.org/occi/infrastructure#network\"; " + + "self=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"; " + + "category=\"http://schemas.ogf.org/occi/infrastructure#networkinterface " + + "http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface\"; " + + "occi.networkinterface.gateway=\"10.0.0.1\"; " + + "occi.networkinterface.mac=\"fa:16:3e:5b:9d:4d\"; occi.networkinterface.interface=\"et" + + "h0\"; occi.networkinterface.state=\"active\"; occi.networkinterface.allocation=\"stat" + + "ic\"; occi.networkinterface.address=\"0.0.0.0\"; occi.core.source=\"/compute/c14902" + + "07-6be7-4303-a41c-f8a4b1b9c25d\"; occi.core.target=\"/network/admin\"; occi.core.id=" + + "\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"\n" + "X-OCCI-Attribute: org.openstack.compute.console.vnc=\"N/A\"\n" + "X-OCCI-Attribute: occi.compute.architecture=\"x86\"\n" + "X-OCCI-Attribute: occi.compute.state=\"inactive\"\n" @@ -36,9 +46,10 @@ public void testParseDetails() { + "X-OCCI-Attribute: org.openstack.compute.state=\"errorz\"\n" + "X-OCCI-Attribute: occi.compute.memory=\"0.125\"\n" + "X-OCCI-Attribute: occi.compute.cores=\"1\"\n" - + "X-OCCI-Attribute: occi.compute.hostname=\"server-c1490207-6be7-4303-a41c-f8a4b1b9c25d\"\n" + + "X-OCCI-Attribute: occi.compute.hostname=\"server-c1490207-6be7-4303-a41c-f" + + "8a4b1b9c25d\"\n" + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; - Instance instance = Instance.parseInstance(textResponse); + Instance instance = Instance.parseInstance("id", textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestResource.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestResource.java index e9ff1191..cc5eb436 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestResource.java @@ -55,9 +55,9 @@ public void testToHeader() { Resource resource = new Resource("term", "scheme", "class", attributes, actions, "location", "title", "rel"); - String testString = "term; scheme=\"scheme\"; class=\"class\" " - + "attributes=\"attribute1 attribute2\" actions=\"action1 action2\" " - + "location=\"location\" title=\"title\" rel=\"rel\""; + String testString = "term; scheme=\"scheme\"; class=\"class\"; title=\"title\"; " + + "rel=\"rel\"; location=\"location\"; " + + "attributes=\"attribute1 attribute2\"; actions=\"action1 action2\""; Assert.assertEquals(testString, resource.toHeader()); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java new file mode 100644 index 00000000..4a3da563 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -0,0 +1,76 @@ +package org.fogbowcloud.manager.xmpp; + +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.jivesoftware.smack.XMPPException; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestDeleteRemoteInstance { + + private static final String TOKEN = "token"; + private static final String WRONG_TOKEN = "wrong"; + + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; + + public static final String USER_DEFAULT = "user"; + public static final String INSTANCE_DEFAULT = "instance"; + public static final String INSTANCE_OTHER_USER = "otherUser"; + + private ManagerTestHelper managerTestHelper; + + @Before + public void setUp() throws XMPPException { + this.managerTestHelper = new ManagerTestHelper(); + } + + @After + public void tearDown() throws Exception { + this.managerTestHelper.shutdown(); + } + + @Test + public void testDeleteRemoteInstance() throws Exception { + Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, null, null); + request.setInstanceId(INSTANCE_DEFAULT); + + managerTestHelper.initializeXMPPManagerComponent(false); + ManagerPacketHelper.deleteRemoteInstace(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + } + + @Test(expected = OCCIException.class) + public void testDeleteRemoteInstaceNotFound() throws Exception { + Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + request.setInstanceId(INSTANCE_DEFAULT); + + managerTestHelper.initializeXMPPManagerComponent(false); + + Mockito.doThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)) + .when(this.managerTestHelper.getComputePlugin()) + .removeInstance(Mockito.anyString(), Mockito.anyString()); + + ManagerPacketHelper.deleteRemoteInstace(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + } + + @Test(expected = OCCIException.class) + public void testDeleteRemoteInstanceUnauthorized() throws Exception { + Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + request.setInstanceId(INSTANCE_OTHER_USER); + + managerTestHelper.initializeXMPPManagerComponent(false); + + Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) + .when(this.managerTestHelper.getComputePlugin()) + .removeInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_OTHER_USER)); + + ManagerPacketHelper.deleteRemoteInstace(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java new file mode 100644 index 00000000..4977dd89 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -0,0 +1,121 @@ +package org.fogbowcloud.manager.xmpp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.instance.Instance; +import org.fogbowcloud.manager.occi.instance.Instance.Link; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.jivesoftware.smack.XMPPException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestGetRemoteInstance { + + private static final String TOKEN = "token"; + private static final String WRONG_TOKEN = "wrong"; + + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; + public static final String MANAGER_COMPONENT_PASS = "password"; + + public static final String USER_DEFAULT = "user"; + public static final String INSTANCE_DEFAULT = "instance"; + public static final String INSTANCE_OTHER_USER = "otherUser"; + + private ManagerTestHelper managerTestHelper; + + @Before + public void setUp() throws XMPPException { + this.managerTestHelper = new ManagerTestHelper(); + } + + @After + public void tearDown() throws Exception { + this.managerTestHelper.shutdown(); + } + + private Instance createInstance() { + Category category = new Category("term", "schema", "class"); + + List supportedAtt = new ArrayList(); + supportedAtt.add("att1"); + + List actions = new ArrayList(); + actions.add("actions1"); + + List resources = new ArrayList(); + resources.add(new Resource(category, supportedAtt, actions, "location", "title", "rel")); + + Map attributes = new HashMap(); + attributes.put("key", "value"); + + Link link = new Link("linkname", attributes); + + return new Instance(INSTANCE_DEFAULT, resources, attributes, link); + } + + @Test + public void testGetRemoteInstance() throws Exception { + managerTestHelper.initializeXMPPManagerComponent(false); + Instance instance = createInstance(); + + Mockito.when(managerTestHelper.getComputePlugin() + .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_DEFAULT))) + .thenReturn(instance); + + Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, null, null); + request.setInstanceId(INSTANCE_DEFAULT); + + Instance remoteInstance = ManagerPacketHelper.getRemoteInstance(request, + MANAGER_COMPONENT_URL, managerTestHelper.createPacketSender()); + + Assert.assertEquals(instance.getId(), remoteInstance.getId()); + Assert.assertEquals(instance.getAttributes(), remoteInstance.getAttributes()); + Assert.assertEquals(instance.getResources().get(0).toHeader(), + remoteInstance.getResources().get(0).toHeader()); + Assert.assertEquals(instance.getLink().getName(), + remoteInstance.getLink().getName()); + } + + @Test + public void testGetRemoteInstaceNotFound() throws Exception { + Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + request.setInstanceId(INSTANCE_DEFAULT); + + managerTestHelper.initializeXMPPManagerComponent(false); + + Mockito.doThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)) + .when(this.managerTestHelper.getComputePlugin()) + .getInstance(Mockito.anyString(), Mockito.anyString()); + + Assert.assertNull(ManagerPacketHelper.getRemoteInstance(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender())); + } + + @Test(expected=OCCIException.class) + public void testGetRemoteInstanceUnauthorized() throws Exception { + Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + request.setInstanceId(INSTANCE_OTHER_USER); + + managerTestHelper.initializeXMPPManagerComponent(false); + + Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) + .when(this.managerTestHelper.getComputePlugin()) + .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_OTHER_USER)); + + ManagerPacketHelper.getRemoteInstance(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + } +} \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java similarity index 57% rename from src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java rename to src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 42f16ea2..8af5de73 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestManagerComponent.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -22,7 +22,7 @@ import org.xmpp.packet.IQ; import org.xmpp.packet.Packet; -public class TestManagerComponent { +public class TestIAmAlive { private ManagerTestHelper managerTestHelper; private ManagerXmppComponent managerXmppComponent; @@ -84,58 +84,7 @@ public boolean accept(Packet packet) { xmppClient.disconnect(); } - - @Test - public void testWhoIsAlive() throws Exception { - managerXmppComponent = managerTestHelper - .initializeXMPPManagerComponent(false); - final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); - final BlockingQueue blockingQueue = new LinkedBlockingQueue( - 1); - - final PacketListener callback = new PacketListener() { - public void processPacket(Packet packet) { - IQ whoIsAlive = (IQ) packet; - try { - blockingQueue.put(packet); - } catch (InterruptedException e) { - e.printStackTrace(); - } - List aliveIds = new ArrayList(); - aliveIds.add(new FederationMember(managerTestHelper - .getResources())); - IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); - xmppClient.send(iq); - } - }; - - xmppClient.on(new PacketFilter() { - @Override - public boolean accept(Packet packet) { - if (packet.getFrom() == null) { - return false; - } - return packet.getFrom().toBareJID() - .equals(ManagerTestHelper.MANAGER_COMPONENT_URL); - } - }, callback); - managerXmppComponent.whoIsalive(); - - Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); - Element element = packet.getElement().element("query"); - Assert.assertEquals(element.getNamespaceURI(), - ManagerTestHelper.WHOISALIVE_NAMESPACE); - - Assert.assertEquals(1, managerXmppComponent.getManagerFacade() - .getMembers().size()); - Assert.assertEquals(2, managerXmppComponent.getManagerFacade() - .getMembers().get(0).getResourcesInfo().getFlavours().size()); - Assert.assertEquals("small", managerXmppComponent.getManagerFacade() - .getMembers().get(0).getResourcesInfo().getFlavours().get(0).getName()); - xmppClient.disconnect(); - } - + @Test public void testCallIAmAlive() throws Exception { final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); @@ -196,49 +145,6 @@ public boolean accept(Packet packet) { xmppClient.disconnect(); } - @Test - public void testCallWhoIsAlive() throws Exception { - final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); - final Semaphore semaphore = new Semaphore(0); - final PacketListener callbackWhoIsAlive = new PacketListener() { - public void processPacket(Packet packet) { - IQ whoIsAlive = (IQ) packet; - List aliveIds = new ArrayList(); - aliveIds.add(new FederationMember(managerTestHelper - .getResources())); - IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); - try { - xmppClient.syncSend(iq); - } catch (XMPPException e) { - // No problem if exception is throwed - } - semaphore.release(); - } - }; - xmppClient.on(new PacketFilter() { - @Override - public boolean accept(Packet packet) { - Element element = packet.getElement().element("query"); - if (element == null) { - return false; - } - return element.getNamespaceURI().equals( - ManagerTestHelper.WHOISALIVE_NAMESPACE); - } - }, callbackWhoIsAlive); - - managerXmppComponent = managerTestHelper - .initializeXMPPManagerComponent(true); - Assert.assertTrue(semaphore.tryAcquire(20000, TimeUnit.MILLISECONDS)); - Assert.assertEquals(1, managerXmppComponent.getManagerFacade() - .getMembers().size()); - Assert.assertEquals("small", managerXmppComponent.getManagerFacade() - .getMembers().get(0).getResourcesInfo().getFlavours().get(0) - .getName()); - xmppClient.disconnect(); - } - @After public void tearDown() throws ComponentException { managerTestHelper.shutdown(); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java new file mode 100644 index 00000000..934f4530 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -0,0 +1,85 @@ +package org.fogbowcloud.manager.xmpp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.jivesoftware.smack.XMPPException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestRequestRemoteInstance { + + private static final String TOKEN = "token"; + private static final String WRONG_TOKEN = "wrong"; + + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; + + public static final String USER_DEFAULT = "user"; + public static final String INSTANCE_DEFAULT = "instance"; + public static final String INSTANCE_OTHER_USER = "otherUser"; + + private ManagerTestHelper managerTestHelper; + + @Before + public void setUp() throws XMPPException { + this.managerTestHelper = new ManagerTestHelper(); + } + + @After + public void tearDown() throws Exception { + this.managerTestHelper.shutdown(); + } + + @Test + public void testRequestRemote() throws Exception{ + managerTestHelper.initializeXMPPManagerComponent(false); + + Request request = createRequest(); + Mockito.when(managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString() + , Mockito.any(List.class), Mockito.any(Map.class))).thenReturn(INSTANCE_DEFAULT); + + String instanceId = ManagerPacketHelper.remoteRequest(request, + MANAGER_COMPONENT_URL, managerTestHelper.createPacketSender()); + + Assert.assertEquals(INSTANCE_DEFAULT, instanceId); + } + + private Request createRequest() { + List categories = new ArrayList(); + categories.add(new Category("term1", "scheme1", "class1")); + Map attributes = new HashMap(); + attributes.put("key1", "value1"); + attributes.put("key2", "value2"); + Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, categories, attributes); + request.setInstanceId(INSTANCE_DEFAULT); + return request; + } + + @Ignore + @Test(expected = OCCIException.class) + public void testRequestRemoteInstaceNotFound() throws Exception { + managerTestHelper.initializeXMPPManagerComponent(false); + + Request request = createRequest(); + Mockito.doThrow(new OCCIException(ErrorType.BAD_REQUEST, + ResponseConstants.CLOUD_NOT_SUPPORT_CATEGORY)) + .when(this.managerTestHelper.getComputePlugin()) + .requestInstance(Mockito.anyString(), Mockito.anyList(), Mockito.anyMap()); + + String remoteRequest = ManagerPacketHelper.remoteRequest(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + Assert.assertNull(remoteRequest); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java new file mode 100644 index 00000000..8056fc77 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java @@ -0,0 +1,133 @@ +package org.fogbowcloud.manager.xmpp; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import org.dom4j.Element; +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.jamppa.client.XMPPClient; +import org.jivesoftware.smack.PacketListener; +import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.filter.PacketFilter; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.xmpp.component.ComponentException; +import org.xmpp.packet.IQ; +import org.xmpp.packet.Packet; + +public class TestWhoIsAlive { + + private ManagerTestHelper managerTestHelper; + private ManagerXmppComponent managerXmppComponent; + + @Before + public void setUp() throws ComponentException { + managerTestHelper = new ManagerTestHelper(); + } + + @Test + public void testWhoIsAlive() throws Exception { + managerXmppComponent = managerTestHelper + .initializeXMPPManagerComponent(false); + final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); + final BlockingQueue blockingQueue = new LinkedBlockingQueue( + 1); + + final PacketListener callback = new PacketListener() { + public void processPacket(Packet packet) { + IQ whoIsAlive = (IQ) packet; + try { + blockingQueue.put(packet); + } catch (InterruptedException e) { + e.printStackTrace(); + } + List aliveIds = new ArrayList(); + aliveIds.add(new FederationMember(managerTestHelper + .getResources())); + IQ iq = managerTestHelper.createWhoIsAliveResponse( + (ArrayList) aliveIds, whoIsAlive); + xmppClient.send(iq); + } + }; + + xmppClient.on(new PacketFilter() { + @Override + public boolean accept(Packet packet) { + if (packet.getFrom() == null) { + return false; + } + return packet.getFrom().toBareJID() + .equals(ManagerTestHelper.MANAGER_COMPONENT_URL); + } + }, callback); + managerXmppComponent.whoIsalive(); + + Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); + Element element = packet.getElement().element("query"); + Assert.assertEquals(element.getNamespaceURI(), + ManagerTestHelper.WHOISALIVE_NAMESPACE); + + Assert.assertEquals(1, managerXmppComponent.getManagerFacade() + .getMembers().size()); + Assert.assertEquals(2, managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().size()); + Assert.assertEquals("small", managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().get(0).getName()); + xmppClient.disconnect(); + } + + @Test + public void testCallWhoIsAlive() throws Exception { + final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); + final Semaphore semaphore = new Semaphore(0); + final PacketListener callbackWhoIsAlive = new PacketListener() { + public void processPacket(Packet packet) { + IQ whoIsAlive = (IQ) packet; + List aliveIds = new ArrayList(); + aliveIds.add(new FederationMember(managerTestHelper + .getResources())); + IQ iq = managerTestHelper.createWhoIsAliveResponse( + (ArrayList) aliveIds, whoIsAlive); + try { + xmppClient.syncSend(iq); + } catch (XMPPException e) { + // No problem if exception is throwed + } + semaphore.release(); + } + }; + xmppClient.on(new PacketFilter() { + @Override + public boolean accept(Packet packet) { + Element element = packet.getElement().element("query"); + if (element == null) { + return false; + } + return element.getNamespaceURI().equals( + ManagerTestHelper.WHOISALIVE_NAMESPACE); + } + }, callbackWhoIsAlive); + + managerXmppComponent = managerTestHelper + .initializeXMPPManagerComponent(true); + Assert.assertTrue(semaphore.tryAcquire(20000, TimeUnit.MILLISECONDS)); + Assert.assertEquals(1, managerXmppComponent.getManagerFacade() + .getMembers().size()); + Assert.assertEquals("small", managerXmppComponent.getManagerFacade() + .getMembers().get(0).getResourcesInfo().getFlavours().get(0) + .getName()); + xmppClient.disconnect(); + } + + @After + public void tearDown() throws ComponentException { + managerTestHelper.shutdown(); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index b31db2be..f10ba758 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -17,7 +17,11 @@ import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; import org.jamppa.client.plugin.xep0077.XEP0077; +import org.jamppa.component.PacketSender; +import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.filter.PacketFilter; +import org.jivesoftware.smack.filter.PacketIDFilter; import org.mockito.Mockito; import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; @@ -43,6 +47,8 @@ public class ManagerTestHelper { public static final int TIMEOUT_GRACE = 500; private ManagerXmppComponent managerXmppComponent; + private ComputePlugin computePlugin; + private IdentityPlugin identityPlugin; public ResourcesInfo getResources() { List flavours = new LinkedList(); @@ -106,16 +112,47 @@ public XMPPClient createXMPPClient() throws XMPPException { return xmppClient; } + + public PacketSender createPacketSender() throws XMPPException { + final XMPPClient xmppClient = createXMPPClient(); + PacketSender sender = new PacketSender() { + @Override + public Packet syncSendPacket(Packet packet) { + PacketFilter responseFilter = new PacketIDFilter(packet.getID()); + PacketCollector response = xmppClient.getConnection() + .createPacketCollector(responseFilter); + xmppClient.getConnection().sendPacket(packet); + Packet result = response.nextResult(5000); + response.cancel(); + return result; + } + + @Override + public void sendPacket(Packet packet) { + xmppClient.send(packet); + } + }; + return sender; + } + + + public ComputePlugin getComputePlugin() { + return computePlugin; + } + + public IdentityPlugin getIdentityPlugin() { + return identityPlugin; + } public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Exception { - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); Properties properties = new Properties(); - properties.put("federation.user.name", "fogbow"); - properties.put("federation.user.password", "fogbow"); + properties.put("federation_user_name", "fogbow"); + properties.put("federation_user_password", "fogbow"); properties.put("xmpp_jid", "manager.test.com"); ManagerFacade managerFacade = new ManagerFacade(properties); @@ -140,6 +177,37 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) } return managerXmppComponent; } + + public ManagerXmppComponent initializeLocalXMPPManagerComponent() + throws Exception { + + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); + + Properties properties = new Properties(); + properties.put("federation_user_name", "fogbow"); + properties.put("federation_user_password", "fogbow"); + properties.put("xmpp_jid", "manager.test.com"); + + ManagerFacade managerFacade = new ManagerFacade(properties); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setIdentityPlugin(identityPlugin); + + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, + managerFacade); + Mockito.when(computePlugin.getResourcesInfo(TOKEN)).thenReturn( + getResources()); + Mockito.when(identityPlugin.getToken("fogbow", "fogbow")).thenReturn( + TOKEN); + + managerXmppComponent.setDescription("Manager Component"); + managerXmppComponent.setName("Manager"); + managerXmppComponent.setRendezvousAddress(CLIENT_ADRESS + SMACK_ENDING); + managerXmppComponent.connect(); + managerXmppComponent.process(); + return managerXmppComponent; + } public IQ CreateImAliveResponse(IQ iq) { IQ response = IQ.createResultIQ(iq); From a9d3d8c712135f8a20f886dfd86f5f9341b88621 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 28 Apr 2014 11:12:19 -0300 Subject: [PATCH 051/185] Fixing xmpp tests --- .../manager/core/ManagerFacade.java | 6 +- .../manager/occi/core/Resource.java | 24 ++++++-- .../manager/occi/instance/Instance.java | 19 ------ .../manager/xmpp/GetInstanceHandler.java | 1 - .../manager/xmpp/ManagerPacketHelper.java | 6 +- .../manager/occi/core/TestInstance.java | 51 ++++++++++++---- .../manager/xmpp/TestGetRemoteInstance.java | 1 - .../xmpp/TestRequestRemoteInstance.java | 59 ++++++++++++++----- 8 files changed, 112 insertions(+), 55 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 6abee80a..6e022bf2 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -188,8 +188,10 @@ public String createRequestForRemoteMember(List categories, Map suppor public String toHeader() { String title = ""; - if (!getTitle().equals(null) || !getTitle().equals("")) { + String rel = ""; + String location = ""; + String actions = ""; + String attributes = ""; + if (!getTitle().equals("")) { title = "\"; title=\"" + getTitle(); } + if (!getRel().equals("")) { + rel = "\"; rel=\"" + getRel(); + } + if (!getLocation().equals("")) { + location = "\"; location=\"" + getLocation(); + } + if(getActions().size() != 0 ){ + actions = "\"; actions=\"" + actionsToHeader(); + } + if(getAttributes().size() != 0){ + attributes = "\"; attributes=\"" + attributesToHeader(); + } + return category.getTerm() + "; scheme=\"" + category.getScheme() + "\"; class=\"" - + category.getCatClass() + title + "\"; rel=\"" + getRel() + "\"; location=\"" - + getLocation() + "\"; attributes=\"" + attributesToHeader() + "\"; actions=\"" - + actionsToHeader() + "\""; + + category.getCatClass() + title + rel + location + + attributes + actions + "\""; } private String actionsToHeader() { diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 1a6e6b03..1b743120 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -19,9 +19,6 @@ public class Instance { private Link link; private Map attributes; - public Instance() { - } - public Instance(String id) { this.id = id; } @@ -118,26 +115,14 @@ public String toOCCIMassageFormatDetails() { return messageFormat.trim(); } - public void setId(String id) { - this.id = id; - } - public List getResources() { return resources; } - public void setResources(List resources) { - this.resources = resources; - } - public Map getAttributes() { return attributes; } - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - public String getId() { return id; } @@ -146,10 +131,6 @@ public Link getLink() { return link; } - public void setLink(Link link) { - this.link = link; - } - public static class Link { private static final String NAME_LINK = "Link:"; diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java index 64e71dd6..21dbd9a8 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java @@ -84,7 +84,6 @@ public IQ handle(IQ query) { attributeEl.setText(instanceAtt.getValue()); } - System.out.println(response.toString()); return response; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index feb645b8..200d8205 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -126,7 +126,11 @@ public static String remoteRequest(Request request, } IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - return null; + if (response.getError().getCondition().equals( + Condition.item_not_found)) { + return null; + } + raiseException(response.getError()); } return response.getElement().element("query") .element("instance") diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java index 9e1c1c25..c97c3f13 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java @@ -2,7 +2,6 @@ import org.fogbowcloud.manager.occi.instance.Instance; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; public class TestInstance { @@ -14,11 +13,11 @@ public void testParseIdOneValue() { Assert.assertEquals(textResponse, instance.toOCCIMassageFormatLocation()); } - - //TODO refatoring + @Test public void testParseDetails() { - String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infrastructure#\"; class=\"kind\"; " + String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infras" + + "tructure#\"; class=\"kind\"; " + "title=\"Compute Resource\"; rel=\"http://schemas.ogf.org/occi/core#resource\"; " + "location=\"http://localhost:8787/compute/\"; " + "attributes=\"occi.compute.architecture occi.compute.state{immutable} " @@ -27,17 +26,19 @@ public void testParseDetails() { + "hemas.ogf.org/occi/infrastructure/compute/action#stop " + "http://schemas.ogf.org/occi/infrastructure/compute/action#restart " + "http://schemas.ogf.org/occi/infrastructure/compute/action#suspend\"\n" -// + "Category: os_vms; scheme=\"http://schemas.openstack.org/compute/instance#\"; class=\"mixin\"; location=\"http://localhost:8787/os_vms/\"; attributes=\"org.openstack.compute.console.vnc{immutable} org.openstack.compute.state{immutable}\"; actions=\"http://schemas.openstack.org/instance/action#chg_pwd http://schemas.openstack.org/instance/action#create_image\"\n" -// + "Category: b4c4322e-1f6c-4cf4-be02-34cc385a3b29; scheme=\"http://schemas.openstack.org/template/os#\"; class=\"mixin\"; title=\"Image: cirros-0.3.1-x86_64-uec\"; rel=\"http://schemas.ogf.org/occi/infrastructure#os_tpl\"; location=\"http://localhost:8787/b4c4322e-1f6c-4cf4-be02-34cc385a3b29/\"\n" + "Link: ; rel=\"http://schemas.ogf.org/occi/infrastructure#network\"; " + "self=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"; " + "category=\"http://schemas.ogf.org/occi/infrastructure#networkinterface " + "http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface\"; " + "occi.networkinterface.gateway=\"10.0.0.1\"; " - + "occi.networkinterface.mac=\"fa:16:3e:5b:9d:4d\"; occi.networkinterface.interface=\"et" - + "h0\"; occi.networkinterface.state=\"active\"; occi.networkinterface.allocation=\"stat" - + "ic\"; occi.networkinterface.address=\"0.0.0.0\"; occi.core.source=\"/compute/c14902" - + "07-6be7-4303-a41c-f8a4b1b9c25d\"; occi.core.target=\"/network/admin\"; occi.core.id=" + + "occi.networkinterface.mac=\"fa:16:3e:5b:9d:4d\";" + + " occi.networkinterface.interface=\"et" + + "h0\"; occi.networkinterface.state=\"active\";" + + " occi.networkinterface.allocation=\"stat" + + "ic\"; occi.networkinterface.address=\"0.0.0.0\";" + + " occi.core.source=\"/compute/c14902" + + "07-6be7-4303-a41c-f8a4b1b9c25d\"; occi.core.target=\"/network/admin\";" + + " occi.core.id=" + "\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"\n" + "X-OCCI-Attribute: org.openstack.compute.console.vnc=\"N/A\"\n" + "X-OCCI-Attribute: occi.compute.architecture=\"x86\"\n" @@ -50,7 +51,35 @@ public void testParseDetails() { + "8a4b1b9c25d\"\n" + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; Instance instance = Instance.parseInstance("id", textResponse); - + + Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); + } + + @Test + public void testParseDetailsOnlyAttributes() { + String textResponse = "" + + "X-OCCI-Attribute: org.openstack.compute.console.vnc=\"N/A\"\n" + + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; + Instance instance = Instance.parseInstance("id", textResponse); + + Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); + } + + @Test + public void testParseDetailsOnlyCategory() { + String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infras" + + "tructure#\"; class=\"kind\"; " + + "title=\"Compute Resource\"; rel=\"http://schemas.ogf.org/occi/core#resource\"; " + + "location=\"http://localhost:8787/compute/\"; " + + "attributes=\"occi.compute.architecture occi.compute.state{immutable} " + + "occi.compute.speed occi.compute.memory occi.compute.cores" + + " occi.compute.hostname\"; " + + "actions=\"http://schemas.ogf.org/occi/infrastructure/compute/action#start" + + " http://schemas.ogf.org/occi/infrastructure/compute/action#stop " + + "http://schemas.ogf.org/occi/infrastructure/compute/action#restart " + + "http://schemas.ogf.org/occi/infrastructure/compute/action#suspend\""; + Instance instance = Instance.parseInstance("id", textResponse); + Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); } } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 4977dd89..609dd161 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -18,7 +18,6 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index 934f4530..15d77ee9 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -15,15 +15,11 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.mockito.Mockito; public class TestRequestRemoteInstance { - private static final String TOKEN = "token"; - private static final String WRONG_TOKEN = "wrong"; - public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String USER_DEFAULT = "user"; @@ -41,17 +37,20 @@ public void setUp() throws XMPPException { public void tearDown() throws Exception { this.managerTestHelper.shutdown(); } - + + @SuppressWarnings("unchecked") @Test - public void testRequestRemote() throws Exception{ + public void testRequestRemote() throws Exception { managerTestHelper.initializeXMPPManagerComponent(false); - Request request = createRequest(); - Mockito.when(managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString() - , Mockito.any(List.class), Mockito.any(Map.class))).thenReturn(INSTANCE_DEFAULT); - - String instanceId = ManagerPacketHelper.remoteRequest(request, - MANAGER_COMPONENT_URL, managerTestHelper.createPacketSender()); + Request request = createRequest(); + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenReturn( + INSTANCE_DEFAULT); + + String instanceId = ManagerPacketHelper.remoteRequest(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); Assert.assertEquals(INSTANCE_DEFAULT, instanceId); } @@ -67,14 +66,42 @@ private Request createRequest() { return request; } - @Ignore + @Test + public void testRequestRemoteRequestCloundNotSupport() throws Exception { + managerTestHelper.initializeXMPPManagerComponent(false); + + Request request = createRequest(); + Mockito.doThrow( + new OCCIException(ErrorType.BAD_REQUEST, + ResponseConstants.CLOUD_NOT_SUPPORT_CATEGORY)) + .when(this.managerTestHelper.getComputePlugin()) + .requestInstance(Mockito.anyString(), Mockito.anyList(), Mockito.anyMap()); + + String remoteRequest = ManagerPacketHelper.remoteRequest(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + Assert.assertNull(remoteRequest); + } + + @Test + public void testRequestRemoteRequestNotFound() throws Exception { + managerTestHelper.initializeXMPPManagerComponent(false); + + Request request = createRequest(); + Mockito.doThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)) + .when(this.managerTestHelper.getComputePlugin()) + .requestInstance(Mockito.anyString(), Mockito.anyList(), Mockito.anyMap()); + + String remoteRequest = ManagerPacketHelper.remoteRequest(request, MANAGER_COMPONENT_URL, + managerTestHelper.createPacketSender()); + Assert.assertNull(remoteRequest); + } + @Test(expected = OCCIException.class) - public void testRequestRemoteInstaceNotFound() throws Exception { + public void testRequestRemoteRequestUnauthorized() throws Exception { managerTestHelper.initializeXMPPManagerComponent(false); Request request = createRequest(); - Mockito.doThrow(new OCCIException(ErrorType.BAD_REQUEST, - ResponseConstants.CLOUD_NOT_SUPPORT_CATEGORY)) + Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) .requestInstance(Mockito.anyString(), Mockito.anyList(), Mockito.anyMap()); From 709536b7af9b657fed9e6197ec0a1741b735e8f8 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 28 Apr 2014 14:51:16 -0300 Subject: [PATCH 052/185] Implementing MemberServerResource --- .../manager/core/ManagerFacade.java | 6 +- .../manager/occi/MemberServerResource.java | 64 +++++++++++ .../manager/occi/OCCIApplication.java | 6 + .../occi/TestMemberServerResource.java | 106 ++++++++++++++++++ .../manager/occi/util/OCCITestHelper.java | 16 +++ 5 files changed, 197 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java create mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 6e022bf2..e267d25e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -51,7 +51,7 @@ public ManagerFacade(Properties properties) { throw new IllegalArgumentException(); } } - + public void setComputePlugin(ComputePlugin computePlugin) { this.computePlugin = computePlugin; } @@ -70,6 +70,10 @@ public void updateMembers(List members) { public List getMembers() { return members; } + + public void setMembers(List members) { + this.members = members; + } public ResourcesInfo getResourcesInfo() { String token = getFederationUserToken(); diff --git a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java new file mode 100644 index 00000000..21f5c1bc --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java @@ -0,0 +1,64 @@ +package org.fogbowcloud.manager.occi; + +import java.util.List; + +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.Flavor; +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +public class MemberServerResource extends ServerResource { + + @Get + public String fetch() { + OCCIApplication application = (OCCIApplication) getApplication(); + + List federationMembers = application.getFederationMembers(); + if (federationMembers == null) { + return " "; + } + + return generateResponse(federationMembers); + } + + private String generateResponse(List federationMembers) { + String response = ""; + for (FederationMember federationMember : federationMembers) { + String id = federationMember.getResourcesInfo().getId(); + String cpuIdle = federationMember.getResourcesInfo().getCpuIdle(); + String cpuInUse = federationMember.getResourcesInfo().getCpuInUse(); + String memIdle = federationMember.getResourcesInfo().getMemIdle(); + String memInUse = federationMember.getResourcesInfo().getMemInUse(); + + String flavorStr = ""; + if (federationMember.getResourcesInfo().getFlavours() != null){ + for (Flavor flavor : federationMember.getResourcesInfo().getFlavours()) { + String nameFlavor = flavor.getName(); + Integer capacityFlavor = flavor.getCapacity(); + flavorStr = "flavour : \"" + nameFlavor + ", capacity=\"" + capacityFlavor + ""; + } + } + + if (!cpuIdle.equals("")) { + cpuIdle = " ; " + "cpuIdle=\"" + cpuIdle ; + } + if (!cpuInUse.equals("")) { + cpuInUse = "\" ; " + "cpuInUse=\"" + cpuInUse; + } + if (!memIdle.equals("")) { + memIdle = "\" ; " + "menIdle=\"" + memIdle; + } + if (!memInUse.equals("")) { + memInUse = "\" ; " + "menInUse=\"" + memInUse; + } + if (!flavorStr.equals("")) { + flavorStr = "\" ; " + flavorStr + "\""; + } + + response += "id=\"" + id + "\"" + cpuIdle + cpuInUse + memIdle + + memInUse + flavorStr + "\"\n"; + } + + return response.trim(); + } +} diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index f8536c19..d350e79f 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -4,6 +4,7 @@ import java.util.Map; import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.instance.ComputeServerResource; import org.fogbowcloud.manager.occi.instance.Instance; @@ -28,8 +29,13 @@ public Restlet createInboundRoot() { router.attach("/request/{requestId}", RequestServerResource.class); router.attach("/compute/", ComputeServerResource.class); router.attach("/compute/{instanceId}", ComputeServerResource.class); + router.attach("/members", MemberServerResource.class); return router; } + + public List getFederationMembers() { + return managerFacade.getMembers(); + } public Request getRequest(String authToken, String requestId) { return managerFacade.getRequest(authToken, requestId); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java new file mode 100644 index 00000000..09922900 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -0,0 +1,106 @@ +package org.fogbowcloud.manager.occi; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.codec.Charsets; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.Flavor; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestMemberServerResource { + + private final String FLAVOUR_1 = "flavour1"; + private final String FLAVOUR_2 = "flavour1"; + private final String ID_RESOURCEINFO1 = "id1"; + private final String ID_RESOURCEINFO2 = "id2"; + + private OCCITestHelper helper; + + @Before + public void setup() throws Exception { + this.helper = new OCCITestHelper(); + } + + @After + public void tearDown() throws Exception { + this.helper.stopComponent(); + } + + @Test + public void testGetMember() throws Exception { + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + + List federationMembers = new ArrayList(); + List flavours = new ArrayList(); + flavours.add(new Flavor(FLAVOUR_1, "3", "135", 2)); + flavours.add(new Flavor(FLAVOUR_2, "3", "135", 2)); + ResourcesInfo resourcesInfo = new ResourcesInfo(ID_RESOURCEINFO1, "2", "1", "100", "35", + flavours); + ResourcesInfo resourcesInfo2 = new ResourcesInfo(ID_RESOURCEINFO2, "2", "1", "100", "35", + null); + federationMembers.add(new FederationMember(resourcesInfo)); + federationMembers.add(new FederationMember(resourcesInfo)); + federationMembers.add(new FederationMember(resourcesInfo2)); + + this.helper.initializeComponentMember(computePlugin, identityPlugin, federationMembers); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + + Assert.assertTrue(checkResponse(responseStr)); + Assert.assertTrue(responseStr.contains(FLAVOUR_1)); + Assert.assertTrue(responseStr.contains(FLAVOUR_2)); + Assert.assertTrue(responseStr.contains(ID_RESOURCEINFO1)); + Assert.assertTrue(responseStr.contains(ID_RESOURCEINFO2)); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Test + public void testGetMemberWrong() throws Exception { + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + + this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(" ", responseStr); + } + + private boolean checkResponse(String response) { + String[] tokens = response.split("\n"); + for (String token : tokens) { + if (!token.contains("id=")) { + return false; + } + } + return true; + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 3fa0f37f..615e08fe 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -13,6 +13,7 @@ import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; @@ -29,6 +30,7 @@ public class OCCITestHelper { public static final String CONTENT_TYPE_OCCI = "text/occi"; public static final String URI_FOGBOW_REQUEST = "http://localhost:8182/request"; public static final String URI_FOGBOW_COMPUTE = "http://localhost:8182/compute/"; + public static final String URI_FOGBOW_MEMBER = "http://localhost:8182/members"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; @@ -62,6 +64,20 @@ public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlug requests.addRequest(OCCITestHelper.USER_MOCK, request); } + component.getDefaultHost().attach(new OCCIApplication(facade)); + component.start(); + } + + public void initializeComponentMember(ComputePlugin computePlugin, IdentityPlugin identityPlugin, + List federationMembers) throws Exception { + component = new Component(); + component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); + + ManagerFacade facade = new ManagerFacade(new Properties()); + facade.setComputePlugin(computePlugin); + facade.setIdentityPlugin(identityPlugin); + facade.setMembers(federationMembers); + component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); } From 82956e232507b7acd5aeb1c199a2b40d2ca824b7 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 28 Apr 2014 15:20:21 -0300 Subject: [PATCH 053/185] Fixing MemberServerResource and tests --- .../manager/occi/MemberServerResource.java | 6 +++++- .../occi/TestMemberServerResource.java | 21 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java index 21f5c1bc..b5821188 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java @@ -4,6 +4,8 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; @@ -12,7 +14,9 @@ public class MemberServerResource extends ServerResource { @Get public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); - + HttpRequest req = (HttpRequest) getRequest(); + HeaderUtils.checkOCCIContentType(req.getHeaders()); + List federationMembers = application.getFederationMembers(); if (federationMembers == null) { return " "; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java index 09922900..46f063c6 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -15,6 +15,8 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; @@ -62,6 +64,7 @@ public void testGetMember() throws Exception { this.helper.initializeComponentMember(computePlugin, identityPlugin, federationMembers); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); @@ -77,13 +80,14 @@ public void testGetMember() throws Exception { } @Test - public void testGetMemberWrong() throws Exception { + public void testGetMemberEmpty() throws Exception { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); this.helper.initializeComponentMember(computePlugin, identityPlugin, null); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); @@ -94,6 +98,21 @@ public void testGetMemberWrong() throws Exception { Assert.assertEquals(" ", responseStr); } + @Test + public void testGetMemberWrongContentType() throws Exception { + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + + this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); + get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); + } + private boolean checkResponse(String response) { String[] tokens = response.split("\n"); for (String token : tokens) { From 691c8f912f2bd4d6c7d2d7e81354e5f2de54c3b1 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 28 Apr 2014 21:53:21 +0200 Subject: [PATCH 054/185] Added cli interface --- pom.xml | 7 +- .../org/fogbowcloud/manager/cli/Main.java | 180 ++++++++++++++++++ 2 files changed, 186 insertions(+), 1 deletion(-) create mode 100644 src/main/java/org/fogbowcloud/manager/cli/Main.java diff --git a/pom.xml b/pom.xml index 551bfa87..fdff65ca 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,11 @@ org.json json 20090211 - + + + com.beust + jcommander + 1.35 + diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java new file mode 100644 index 00000000..10fd649c --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -0,0 +1,180 @@ +package org.fogbowcloud.manager.cli; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.HashSet; +import java.util.Set; + +import org.apache.http.HttpException; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; + +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; + +public class Main { + + public static void main(String[] args) throws Exception { + JCommander jc = new JCommander(); + + MemberCommand member = new MemberCommand(); + jc.addCommand("member", member); + RequestCommand request = new RequestCommand(); + jc.addCommand("request", request); + InstanceCommand instance = new InstanceCommand(); + jc.addCommand("instance", instance); + + jc.setProgramName("fogbow-cli"); + jc.parse(args); + + String parsedCommand = jc.getParsedCommand(); + + if (parsedCommand == null) { + jc.usage(); + return; + } + + if (parsedCommand.equals("member")) { + String url = member.url; + doRequest("get", url + "/members", null); + } else if (parsedCommand.equals("request")) { + String url = request.url; + if (request.get) { + if (request.create || request.delete || request.requestId == null) { + jc.usage(); + return; + } + doRequest("get", url + "/request/" + request.requestId, + request.authToken); + } else if (request.delete) { + if (request.create || request.get || request.requestId == null) { + jc.usage(); + return; + } + doRequest("delete", url + "/request/" + request.requestId, + request.authToken); + } else if (request.create) { + if (request.delete || request.get || request.requestId != null) { + jc.usage(); + return; + } + Set headers = new HashSet(); + headers.add("Category: fogbow-request; scheme=\"http://schemas.fogbowcloud.org/template/request#\"; class=\"mixin\""); + headers.add("X-OCCI-Attribute: fogbow.request.maxinstance = " + request.instanceCount); + headers.add("X-OCCI-Attribute: fogbow.request.type = one-time"); + headers.add("Category: " + request.flavor + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); + headers.add("Category: " + request.image + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); + doRequest("post", url + "/request", request.authToken, headers); + } + } else if (parsedCommand.equals("instance")) { + String url = instance.url; + if (instance.delete && instance.get) { + jc.usage(); + return; + } + if (instance.instanceId == null) { + jc.usage(); + return; + } + if (instance.get) { + doRequest("get", url + "/compute/" + instance.instanceId, + instance.authToken); + } else if (instance.delete) { + doRequest("delete", url + "/compute/" + instance.instanceId, + instance.authToken); + } + } + } + + private static void doRequest(String method, String endpoint, String authToken) + throws URISyntaxException, HttpException, IOException { + doRequest(method, endpoint, authToken, new HashSet()); + } + + private static void doRequest(String method, String endpoint, String authToken, + Set additionalHeaders) + throws URISyntaxException, HttpException, IOException { + HttpUriRequest request = null; + if (method.equals("get")) { + request = new HttpGet(endpoint); + } else if (method.equals("delete")) { + request = new HttpDelete(endpoint); + } else if (method.equals("post")) { + request = new HttpPost(endpoint); + } + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + if (authToken != null) { + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + } + for (String header : additionalHeaders) { + String[] splitHeader = header.split(":"); + request.addHeader(splitHeader[0].trim(), splitHeader[1].trim()); + } + + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(request); + + System.out.println(EntityUtils.toString(response.getEntity())); + } + + private static class Command { + @Parameter(names = "--url", required = true, description = "fogbow manager url") + String url = null; + } + + private static class AuthedCommand extends Command { + @Parameter(names = "--auth-token", required = true, description = "auth token") + String authToken = null; + } + + @Parameters(separators = "=", commandDescription = "Members operations") + private static class MemberCommand extends Command { + @Parameter(names = "--get", description = "List federation members") + Boolean get = true; + } + + @Parameters(separators = "=", commandDescription = "Request operations") + private static class RequestCommand extends AuthedCommand { + @Parameter(names = "--get", description = "Get request") + Boolean get = false; + + @Parameter(names = "--create", description = "Create request") + Boolean create = false; + + @Parameter(names = "--delete", description = "Delete request") + Boolean delete = false; + + @Parameter(names = "--id", description = "Request id") + String requestId = null; + + @Parameter(names = "--n", description = "Instance count") + int instanceCount = 0; + + @Parameter(names = "--image", description = "Instance image") + String image = null; + + @Parameter(names = "--flavor", description = "Instance flavor") + String flavor = null; + } + + @Parameters(separators = "=", commandDescription = "Instance operations") + private static class InstanceCommand extends AuthedCommand { + @Parameter(names = "--get", description = "Get instance data") + Boolean get = false; + + @Parameter(names = "--delete", description = "Delete instance") + Boolean delete = false; + + @Parameter(names = "--id", description = "Instance id") + String instanceId = null; + } + +} From 43ffc0d6b6f14eb6d8f10728e820bb60a6dfb875 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 28 Apr 2014 22:22:00 +0200 Subject: [PATCH 055/185] Moving default image setting to configuration file. --- manager.conf.example | 21 +++++++++++++++++++ .../openstack/OpenStackComputePlugin.java | 4 ++-- .../occi/plugins/TestComputeOpenStack.java | 2 ++ .../manager/occi/util/ComputeApplication.java | 2 +- 4 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 manager.conf.example diff --git a/manager.conf.example b/manager.conf.example new file mode 100644 index 00000000..698e0eaa --- /dev/null +++ b/manager.conf.example @@ -0,0 +1,21 @@ +xmpp_jid=manager.test.com +xmpp_password=password +xmpp_host=127.0.0.1 +xmpp_port=5347 + +compute_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackComputePlugin +compute_openstack_occi_url=http://localhost:8182 +compute_openstack_v2api_url=http://localhost:8182 +compute_openstack_flavor_small=m1-small +compute_openstack_flavor_medium=m1-medium +compute_openstack_flavor_large=m1-large +compute_openstack_default_cirros_image=cadf2e29-7216-4a5e-9364-cf6513d5f1fd + +identity_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackIdentityPlugin +identity_openstack_url=http://localhost:5000 + +federation_user_name=fogbow +federation_user_password=fogbow +federation_user_tenant_id=$tenantId + +scheduler_period=30000 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 3e60b945..048a9aa6 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -45,7 +45,6 @@ public class OpenStackComputePlugin implements ComputePlugin { private final String COMPUTE_V2_API_ENDEPOINT = "/v2/"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; - public static final String CIRROS_IMAGE_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; private static final String MAX_TOTAL_CORES_ATT = "maxTotalCores"; private static final String TOTAL_CORES_USED_ATT = "totalCoresUsed"; private static final String MAX_TOTAL_RAM_SIZE_ATT = "maxTotalRAMSize"; @@ -69,7 +68,8 @@ public OpenStackComputePlugin(Properties properties) { fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, createFlavorCategory("compute_openstack_flavor_large", properties)); fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category( - CIRROS_IMAGE_TERM, OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); + properties.getProperty("compute_openstack_default_cirros_image"), + OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); } private static Category createFlavorCategory(String flavorPropName, Properties properties) { diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 331326e6..b1fe6480 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -23,6 +23,7 @@ public class TestComputeOpenStack { + private static final String CIRROS_IMAGE_TERM = "cadf2e29-7216-4a5e-9364-cf6513d5f1fd"; private static final String FIRST_INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String FIFTH_INSTANCE_ID = "hla256kh-43ar-67ww-ao90-fa8d456fce9f"; private static final String FOURTH_INSTANCE_ID = "qwuif8ad-19a3-4afg-1l77-tred90crei0q"; @@ -44,6 +45,7 @@ public void setUp() throws Exception { properties.put("compute_openstack_flavor_small", ComputeApplication.SMALL_FLAVOR_TERM); properties.put("compute_openstack_flavor_medium", ComputeApplication.MEDIUM_FLAVOR_TERM); properties.put("compute_openstack_flavor_large", ComputeApplication.MEDIUM_FLAVOR_TERM); + properties.put("compute_openstack_default_cirros_image", CIRROS_IMAGE_TERM); computeOpenStack = new OpenStackComputePlugin(properties); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index be3714f0..aba985c4 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -75,7 +75,7 @@ private void normalizeDefaultAttributes() { Map attributesToValueUbuntu = new HashMap(); attributesToValueUbuntu.put(ARCHITECTURE_ATTRIBUTE_OCCI, "64"); - this.termToAttributes.put(OpenStackComputePlugin.CIRROS_IMAGE_TERM, attributesToValueUbuntu); + this.termToAttributes.put("cadf2e29-7216-4a5e-9364-cf6513d5f1fd", attributesToValueUbuntu); } @Override From ce97321d5738eb48f1fb58c4a3e5d66c1a44b960 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 29 Apr 2014 05:27:19 +0200 Subject: [PATCH 056/185] Adding SSH tunnelling into user data --- manager.conf.example | 6 +- pom.xml | 5 ++ .../manager/core/ManagerFacade.java | 6 ++ .../fogbowcloud/manager/core/SSHTunnel.java | 76 +++++++++++++++++++ .../openstack/OpenStackComputePlugin.java | 15 +++- .../manager/occi/core/ResponseConstants.java | 1 + .../occi/request/RequestConstants.java | 3 + 7 files changed, 107 insertions(+), 5 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java diff --git a/manager.conf.example b/manager.conf.example index 698e0eaa..ff2cc486 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -18,4 +18,8 @@ federation_user_name=fogbow federation_user_password=fogbow federation_user_tenant_id=$tenantId -scheduler_period=30000 \ No newline at end of file +scheduler_period=30000 + +ssh_tunnel_host=10.0.0.1 +ssh_tunnel_user=fogbow +ssh_tunnel_port_range=50000:59999 diff --git a/pom.xml b/pom.xml index fdff65ca..9cc85038 100644 --- a/pom.xml +++ b/pom.xml @@ -86,5 +86,10 @@ jcommander 1.35 + + commons-io + commons-io + 2.4 + diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index e267d25e..7abe9f53 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -232,6 +232,12 @@ public List createRequests(String authToken, List categories, .getValue())); LOGGER.info("Request " + instanceCount + " instances"); + try { + SSHTunnel.create(properties, categories, xOCCIAtt); + } catch (Exception e) { + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.NOT_FOUND); + } + List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); diff --git a/src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java new file mode 100644 index 00000000..82a9af99 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java @@ -0,0 +1,76 @@ +package org.fogbowcloud.manager.core; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.DatagramSocket; +import java.net.ServerSocket; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.codec.Charsets; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.request.RequestConstants; + +public class SSHTunnel { + + public static final String USER_DATA_ATT = "org.fogbowcloud.request.user-data"; + + public static void create(Properties properties, List categories, + Map xOCCIAtt) throws FileNotFoundException, IOException { + + categories.add(new Category(RequestConstants.USER_DATA_TERM, + RequestConstants.SCHEME, RequestConstants.MIXIN_CLASS)); + String sshTunnelCmd = IOUtils.toString(new FileInputStream("bin/fogbow-inject-tunnel")); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_USER#", properties.getProperty("ssh_tunnel_user")); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", properties.getProperty("ssh_tunnel_host")); + String[] portRange = properties.getProperty("ssh_tunnel_port_range").split(":"); + + Integer portFloor = Integer.parseInt(portRange[0]); + Integer portCeiling = Integer.parseInt(portRange[1]); + + Integer sshPort = null; + + for (Integer i = portFloor; i <= portCeiling; i++) { + if (available(i)) { + sshPort = i; + break; + } + } + if (sshPort == null) { + throw new IllegalStateException("No SSH port available for reverse tunnelling"); + } + + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_PORT#", sshPort.toString()); + xOCCIAtt.put(USER_DATA_ATT, Base64.encodeBase64URLSafeString( + sshTunnelCmd.getBytes(Charsets.UTF_8))); + } + + private static boolean available(int port) { + ServerSocket ss = null; + DatagramSocket ds = null; + try { + ss = new ServerSocket(port); + ss.setReuseAddress(true); + ds = new DatagramSocket(port); + ds.setReuseAddress(true); + return true; + } catch (IOException e) { + } finally { + if (ds != null) { + ds.close(); + } + if (ss != null) { + try { + ss.close(); + } catch (IOException e) { + /* should not be thrown */ + } + } + } + return false; + } +} diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 048a9aa6..9dfaf700 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -19,6 +19,7 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.SSHTunnel; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -34,17 +35,19 @@ public class OpenStackComputePlugin implements ComputePlugin { + private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; + private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; + public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; + private static final String ABSOLUTE = "absolute"; private static final String LIMITS = "limits"; private static final Logger LOGGER = Logger.getLogger(OpenStackComputePlugin.class); private static final String TERM_COMPUTE = "compute"; - private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; private static final String CLASS_COMPUTE = "kind"; private static final String COMPUTE_ENDPOINT = "/compute/"; private final String federationTenantId; private final String COMPUTE_V2_API_ENDEPOINT = "/v2/"; - public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; private static final String MAX_TOTAL_CORES_ATT = "maxTotalCores"; private static final String TOTAL_CORES_USED_ATT = "totalCoresUsed"; private static final String MAX_TOTAL_RAM_SIZE_ATT = "maxTotalRAMSize"; @@ -70,6 +73,8 @@ public OpenStackComputePlugin(Properties properties) { fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category( properties.getProperty("compute_openstack_default_cirros_image"), OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.USER_DATA_TERM, + new Category("user_data", INSTANCE_SCHEME, OCCIHeaders.MIXIN_CLASS)); } private static Category createFlavorCategory(String flavorPropName, Properties properties) { @@ -92,8 +97,10 @@ public String requestInstance(String authToken, List categories, } openStackCategories.add(fogTermToOpensStackCategory.get(category.getTerm())); } + + xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(SSHTunnel.USER_DATA_ATT)); - HttpClient httpCLient = new DefaultHttpClient(); + HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost; try { httpPost = new HttpPost(computeOCCIEndpoint); @@ -106,7 +113,7 @@ public String requestInstance(String authToken, List categories, httpPost.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, attName + "=" + "\"" + xOCCIAtt.get(attName) + "\""); } - HttpResponse response = httpCLient.execute(httpPost); + HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, EntityUtils.toString( response.getEntity(), String.valueOf(Charsets.UTF_8))); diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java index 2283cda3..8d14e15a 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java @@ -8,6 +8,7 @@ public class ResponseConstants { public static final String UNSUPPORTED_ATTRIBUTES = "There are unsupported attributes in the request."; public static final String OK = "Ok"; public static final String CLOUD_NOT_SUPPORT_CATEGORY = "The cloud does not support category: "; + public static final String COULD_NOT_CREATE_TUNNEL = "SSH tunnel could not be created."; public static final String INVALID_OS_TEMPLATE = "Please provide a valid OS Template."; public static final String QUOTA_EXCEEDED_FOR_INSTANCES = "Quota exceeded for instances."; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java index 9916debb..03a512bf 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestConstants.java @@ -21,4 +21,7 @@ public class RequestConstants { // general public static final String MIXIN_CLASS = "mixin"; + + // ssh + public static final String USER_DATA_TERM = "fogbow-userdata"; } \ No newline at end of file From 114c210c054789b869c16c7c2663b3ce39fe1bc0 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 29 Apr 2014 15:48:47 +0200 Subject: [PATCH 057/185] Added bin folder. --- .gitignore | 1 - bin/fogbow-cli | 3 +++ bin/fogbow-inject-tunnel | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) create mode 100755 bin/fogbow-cli create mode 100644 bin/fogbow-inject-tunnel diff --git a/.gitignore b/.gitignore index 37d539ac..4874fbf3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ /target -/bin .classpath .project .settings diff --git a/bin/fogbow-cli b/bin/fogbow-cli new file mode 100755 index 00000000..7b3c80b0 --- /dev/null +++ b/bin/fogbow-cli @@ -0,0 +1,3 @@ +#!/bin/bash + +java -cp .:./lib/* org.fogbowcloud.manager.cli.Main $@ \ No newline at end of file diff --git a/bin/fogbow-inject-tunnel b/bin/fogbow-inject-tunnel new file mode 100644 index 00000000..2a8c7af2 --- /dev/null +++ b/bin/fogbow-inject-tunnel @@ -0,0 +1,2 @@ +#!/bin/sh +/usr/sbin/ssh -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# \ No newline at end of file From 977af4dd62d0857caf6dbf56c879a90eabe95e7d Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 29 Apr 2014 16:49:26 +0200 Subject: [PATCH 058/185] Added SSHTunnel. Fixing tests. --- .../manager/core/ManagerFacade.java | 77 ++++++++++++------- .../openstack/OpenStackComputePlugin.java | 4 +- .../DefaultSSHTunnel.java} | 37 ++++++--- .../manager/core/ssh/SSHTunnel.java | 13 ++++ .../manager/occi/instance/Instance.java | 8 ++ .../manager/occi/request/Request.java | 21 ++++- .../manager/xmpp/ManagerPacketHelper.java | 11 ++- .../manager/xmpp/RequestInstanceHandler.java | 2 +- .../occi/TestMemberServerResource.java | 1 - .../manager/occi/util/OCCITestHelper.java | 4 + .../xmpp/TestDeleteRemoteInstance.java | 12 +-- .../manager/xmpp/TestGetRemoteInstance.java | 11 ++- .../xmpp/TestRequestRemoteInstance.java | 3 + 13 files changed, 144 insertions(+), 60 deletions(-) rename src/main/java/org/fogbowcloud/manager/core/{SSHTunnel.java => ssh/DefaultSSHTunnel.java} (61%) create mode 100644 src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 7abe9f53..2c93a84e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -15,6 +15,8 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.ssh.DefaultSSHTunnel; +import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; @@ -44,6 +46,8 @@ public class ManagerFacade { private IdentityPlugin identityPlugin; private Properties properties; private PacketSender packetSender; + + private SSHTunnel sshTunnel = new DefaultSSHTunnel(); public ManagerFacade(Properties properties) { this.properties = properties; @@ -52,6 +56,10 @@ public ManagerFacade(Properties properties) { } } + public void setSSHTunnel(SSHTunnel sshTunnel) { + this.sshTunnel = sshTunnel; + } + public void setComputePlugin(ComputePlugin computePlugin) { this.computePlugin = computePlugin; } @@ -115,25 +123,35 @@ public List getInstances(String authToken) { if (instanceId == null) { continue; } - if (isLocal(request)) { - instances.add(this.computePlugin.getInstance(authToken, instanceId)); - } else { - instances.add(getRemoteInstance(request)); - } + instances.add(getInstance(authToken, instanceId, request)); } return instances; } public Instance getInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); + return getInstance(authToken, instanceId, request); + } + + private Instance getInstance(String authToken, String instanceId, + Request request) { + Instance instance = null; if (isLocal(request)) { - return this.computePlugin.getInstance(authToken, instanceId); - } - return getRemoteInstance(request); + instance = this.computePlugin.getInstance(authToken, instanceId); + } else { + instance = getRemoteInstance(request); + } + String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); + if (sshAddress != null) { + instance.addAttribute(DefaultSSHTunnel.SSH_ADDRESS_ATT, + sshAddress); + } + + return instance; } private Instance getRemoteInstance(Request request) { - return null; + return ManagerPacketHelper.getRemoteInstance(request, packetSender); } public void removeInstances(String authToken) { @@ -142,16 +160,18 @@ public void removeInstances(String authToken) { if (instanceId == null) { continue; } - if (isLocal(request)) { - this.computePlugin.removeInstance(authToken, instanceId); - } else { - removeRemoteInstance(request); - } + removeInstance(authToken, instanceId, request); } } public void removeInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); + removeInstance(authToken, instanceId, request); + } + + private void removeInstance(String authToken, String instanceId, + Request request) { + sshTunnel.release(request); if (isLocal(request)) { this.computePlugin.removeInstance(authToken, instanceId); } else { @@ -160,7 +180,7 @@ public void removeInstance(String authToken, String instanceId) { } private void removeRemoteInstance(Request request) { - // TODO Auto-generated method stub + ManagerPacketHelper.deleteRemoteInstace(request, packetSender); } public Request getRequestFromInstance(String authToken, String instanceId) { @@ -187,7 +207,7 @@ public Request getRequest(String authToken, String requestId) { return requests.get(requestId); } - public String createRequestForRemoteMember(List categories, Map xOCCIAtt) { + public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { String token = getFederationUserToken(); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); @@ -232,16 +252,16 @@ public List createRequests(String authToken, List categories, .getValue())); LOGGER.info("Request " + instanceCount + " instances"); - try { - SSHTunnel.create(properties, categories, xOCCIAtt); - } catch (Exception e) { - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.NOT_FOUND); - } List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); Request request = new Request(requestId, authToken, user, categories, xOCCIAtt); + try { + sshTunnel.create(properties, request); + } catch (Exception e) { + request.setState(RequestState.FAILED); + } currentRequests.add(request); requests.addRequest(user, request); } @@ -255,7 +275,8 @@ public List createRequests(String authToken, List categories, private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(getMembers()); String memberAddress = member.getResourcesInfo().getId(); - + request.setMemberId(memberAddress); + String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, memberAddress, packetSender); if (remoteInstanceId == null) { @@ -268,15 +289,11 @@ private boolean submitRemoteRequest(Request request) { } private boolean submitLocalRequest(Request request) { - Map xOCCIAtt = request.getxOCCIAtt(); - for (String keyAttributes : RequestAttribute.getValues()) { - xOCCIAtt.remove(keyAttributes); - } - + request.setMemberId(null); String instanceLocation = null; try { instanceLocation = computePlugin.requestInstance(request.getAuthToken(), - request.getCategories(), xOCCIAtt); + request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { if (e.getStatus().equals(ErrorType.BAD_REQUEST) && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { @@ -313,6 +330,10 @@ public void run() { private void checkAndSubmitOpenRequests() { boolean allFulfilled = true; for (Request request : requests.get(RequestState.OPEN)) { + Map xOCCIAtt = request.getxOCCIAtt(); + for (String keyAttributes : RequestAttribute.getValues()) { + xOCCIAtt.remove(keyAttributes); + } allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); } if (allFulfilled) { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 9dfaf700..e5cf721d 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -19,10 +19,10 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -import org.fogbowcloud.manager.core.SSHTunnel; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.ssh.DefaultSSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -98,7 +98,7 @@ public String requestInstance(String authToken, List categories, openStackCategories.add(fogTermToOpensStackCategory.get(category.getTerm())); } - xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(SSHTunnel.USER_DATA_ATT)); + xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(DefaultSSHTunnel.USER_DATA_ATT)); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost; diff --git a/src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java similarity index 61% rename from src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java rename to src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index 82a9af99..1c7a4476 100644 --- a/src/main/java/org/fogbowcloud/manager/core/SSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -1,32 +1,37 @@ -package org.fogbowcloud.manager.core; +package org.fogbowcloud.manager.core.ssh; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; -import java.util.List; -import java.util.Map; +import java.util.HashSet; import java.util.Properties; +import java.util.Set; import org.apache.commons.codec.Charsets; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestConstants; -public class SSHTunnel { +public class DefaultSSHTunnel implements SSHTunnel { public static final String USER_DATA_ATT = "org.fogbowcloud.request.user-data"; + public static final String SSH_ADDRESS_ATT = "org.fogbowcloud.request.ssh-address"; + private Set takenPorts = new HashSet(); - public static void create(Properties properties, List categories, - Map xOCCIAtt) throws FileNotFoundException, IOException { + public void create(Properties properties, Request request) throws FileNotFoundException, IOException { - categories.add(new Category(RequestConstants.USER_DATA_TERM, + request.addCategory(new Category(RequestConstants.USER_DATA_TERM, RequestConstants.SCHEME, RequestConstants.MIXIN_CLASS)); + String sshTunnelCmd = IOUtils.toString(new FileInputStream("bin/fogbow-inject-tunnel")); + String sshHost = properties.getProperty("ssh_tunnel_host"); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_USER#", properties.getProperty("ssh_tunnel_user")); - sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", properties.getProperty("ssh_tunnel_host")); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", sshHost); String[] portRange = properties.getProperty("ssh_tunnel_port_range").split(":"); Integer portFloor = Integer.parseInt(portRange[0]); @@ -35,8 +40,9 @@ public static void create(Properties properties, List categories, Integer sshPort = null; for (Integer i = portFloor; i <= portCeiling; i++) { - if (available(i)) { + if (!takenPorts.contains(i) && available(i)) { sshPort = i; + takenPorts.add(i); break; } } @@ -45,8 +51,19 @@ public static void create(Properties properties, List categories, } sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_PORT#", sshPort.toString()); - xOCCIAtt.put(USER_DATA_ATT, Base64.encodeBase64URLSafeString( + request.putAttValue(USER_DATA_ATT, Base64.encodeBase64URLSafeString( sshTunnelCmd.getBytes(Charsets.UTF_8))); + request.putAttValue(SSH_ADDRESS_ATT, sshHost + ":" + sshPort); + } + + public void release(Request request) { + String sshAddress = request.getAttValue(SSH_ADDRESS_ATT); + if (sshAddress == null) { + return; + } + String[] sshAddressSplit = sshAddress.split(":"); + int sshPort = Integer.parseInt(sshAddressSplit[1]); + takenPorts.remove(sshPort); } private static boolean available(int port) { diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java new file mode 100644 index 00000000..05bfcd1d --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java @@ -0,0 +1,13 @@ +package org.fogbowcloud.manager.core.ssh; + +import java.util.Properties; + +import org.fogbowcloud.manager.occi.request.Request; + +public interface SSHTunnel { + + public void create(Properties properties, Request request) throws Exception; + + public void release(Request request); + +} diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java index 1b743120..f59bf4dd 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/Instance.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.occi.instance; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -122,6 +123,13 @@ public List getResources() { public Map getAttributes() { return attributes; } + + public void addAttribute(String key, String value) { + if (attributes == null) { + attributes = new HashMap(); + } + attributes.put(key, value); + } public String getId() { return id; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 4ecf77fd..d5bbd219 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.occi.request; +import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -29,6 +31,13 @@ public Request(String id, String authToken, String user, public List getCategories() { return categories; } + + public void addCategory(Category category) { + if (categories == null) { + categories = new LinkedList(); + } + categories.add(category); + } public String getUser() { return user; @@ -55,19 +64,27 @@ public String getId() { } public String getAttValue(String attributeName){ + if (xOCCIAtt == null) { + return null; + } return xOCCIAtt.get(attributeName); } + public void putAttValue(String attributeName, String attributeValue){ + if (xOCCIAtt == null) { + xOCCIAtt = new HashMap(); + } + xOCCIAtt.put(attributeName, attributeValue); + } + public String toHttpMessageFormat() { return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; } - public String getAuthToken() { return this.authToken; } - public Map getxOCCIAtt() { return this.xOCCIAtt; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 200d8205..1758cc08 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -137,10 +137,9 @@ public static String remoteRequest(Request request, .elementText("id"); } - public static Instance getRemoteInstance(Request request, - String memberAddress, PacketSender packetSender) { + public static Instance getRemoteInstance(Request request, PacketSender packetSender) { IQ iq = new IQ(); - iq.setTo(memberAddress); + iq.setTo(request.getMemberId()); iq.setType(Type.get); Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.GETINSTANCE_NAMESPACE); @@ -164,10 +163,10 @@ public static Instance getRemoteInstance(Request request, .element("instance")); } - public static void deleteRemoteInstace(Request request, - String memberAddress, PacketSender packetSender) { + public static void deleteRemoteInstace(Request request, + PacketSender packetSender) { IQ iq = new IQ(); - iq.setTo(memberAddress); + iq.setTo(request.getMemberId()); iq.setType(Type.set); Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java index 7b3ab8f0..a0092635 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java @@ -43,7 +43,7 @@ public IQ handle(IQ query) { IQ response = IQ.createResultIQ(query); try { - String instanceId = facade.createRequestForRemoteMember(categories, xOCCIAtt); + String instanceId = facade.submitRequestForRemoteMember(categories, xOCCIAtt); if (instanceId == null) { response.setError(Condition.item_not_found); } else { diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java index 46f063c6..f830d4af 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -15,7 +15,6 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 615e08fe..8fceca1a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -16,10 +16,12 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestRepository; +import org.mockito.Mockito; import org.restlet.Component; import org.restlet.data.Protocol; @@ -44,6 +46,7 @@ public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin iden ManagerFacade facade = new ManagerFacade(new Properties()); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); + facade.setSSHTunnel(Mockito.mock(SSHTunnel.class)); component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); @@ -57,6 +60,7 @@ public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlug ManagerFacade facade = new ManagerFacade(new Properties()); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); + facade.setSSHTunnel(Mockito.mock(SSHTunnel.class)); requests = new RequestRepository(); facade.setRequests(requests); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java index 4a3da563..988cfa53 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -38,16 +38,17 @@ public void tearDown() throws Exception { public void testDeleteRemoteInstance() throws Exception { Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); + request.setMemberId(MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); - ManagerPacketHelper.deleteRemoteInstace(request, MANAGER_COMPONENT_URL, - managerTestHelper.createPacketSender()); + ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); } @Test(expected = OCCIException.class) public void testDeleteRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); + request.setMemberId(MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -55,14 +56,14 @@ public void testDeleteRemoteInstaceNotFound() throws Exception { .when(this.managerTestHelper.getComputePlugin()) .removeInstance(Mockito.anyString(), Mockito.anyString()); - ManagerPacketHelper.deleteRemoteInstace(request, MANAGER_COMPONENT_URL, - managerTestHelper.createPacketSender()); + ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); } @Test(expected = OCCIException.class) public void testDeleteRemoteInstanceUnauthorized() throws Exception { Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_OTHER_USER); + request.setMemberId(MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -70,7 +71,6 @@ public void testDeleteRemoteInstanceUnauthorized() throws Exception { .when(this.managerTestHelper.getComputePlugin()) .removeInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_OTHER_USER)); - ManagerPacketHelper.deleteRemoteInstace(request, MANAGER_COMPONENT_URL, - managerTestHelper.createPacketSender()); + ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); } } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 609dd161..511d7188 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -76,9 +76,10 @@ public void testGetRemoteInstance() throws Exception { Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); + request.setMemberId(MANAGER_COMPONENT_URL); - Instance remoteInstance = ManagerPacketHelper.getRemoteInstance(request, - MANAGER_COMPONENT_URL, managerTestHelper.createPacketSender()); + Instance remoteInstance = ManagerPacketHelper.getRemoteInstance(request, + managerTestHelper.createPacketSender()); Assert.assertEquals(instance.getId(), remoteInstance.getId()); Assert.assertEquals(instance.getAttributes(), remoteInstance.getAttributes()); @@ -92,6 +93,7 @@ public void testGetRemoteInstance() throws Exception { public void testGetRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); + request.setMemberId(MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -99,7 +101,7 @@ public void testGetRemoteInstaceNotFound() throws Exception { .when(this.managerTestHelper.getComputePlugin()) .getInstance(Mockito.anyString(), Mockito.anyString()); - Assert.assertNull(ManagerPacketHelper.getRemoteInstance(request, MANAGER_COMPONENT_URL, + Assert.assertNull(ManagerPacketHelper.getRemoteInstance(request, managerTestHelper.createPacketSender())); } @@ -107,6 +109,7 @@ public void testGetRemoteInstaceNotFound() throws Exception { public void testGetRemoteInstanceUnauthorized() throws Exception { Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_OTHER_USER); + request.setMemberId(MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -114,7 +117,7 @@ public void testGetRemoteInstanceUnauthorized() throws Exception { .when(this.managerTestHelper.getComputePlugin()) .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_OTHER_USER)); - ManagerPacketHelper.getRemoteInstance(request, MANAGER_COMPONENT_URL, + ManagerPacketHelper.getRemoteInstance(request, managerTestHelper.createPacketSender()); } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index 15d77ee9..a0b31554 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -66,6 +66,7 @@ private Request createRequest() { return request; } + @SuppressWarnings("unchecked") @Test public void testRequestRemoteRequestCloundNotSupport() throws Exception { managerTestHelper.initializeXMPPManagerComponent(false); @@ -82,6 +83,7 @@ public void testRequestRemoteRequestCloundNotSupport() throws Exception { Assert.assertNull(remoteRequest); } + @SuppressWarnings("unchecked") @Test public void testRequestRemoteRequestNotFound() throws Exception { managerTestHelper.initializeXMPPManagerComponent(false); @@ -96,6 +98,7 @@ public void testRequestRemoteRequestNotFound() throws Exception { Assert.assertNull(remoteRequest); } + @SuppressWarnings("unchecked") @Test(expected = OCCIException.class) public void testRequestRemoteRequestUnauthorized() throws Exception { managerTestHelper.initializeXMPPManagerComponent(false); From 09576d95463d169edacc3a0f751d18fc5ceffea3 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 29 Apr 2014 18:46:49 +0200 Subject: [PATCH 059/185] Fixes OCCI tests. --- .../org/fogbowcloud/manager/occi/TestOCCIApplication.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 35f27231..74dd6798 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -9,6 +9,7 @@ import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; @@ -62,8 +63,11 @@ public void setUp() { Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + managerFacade.setIdentityPlugin(identityPlugin); managerFacade.setComputePlugin(computePlugin); + managerFacade.setSSHTunnel(sshTunnel); } @Test From bb9a0b78de1a07d3891d24a0860e18684d73f1a1 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Tue, 29 Apr 2014 15:08:28 -0300 Subject: [PATCH 060/185] Adding certificate to iqs --- .../core/CertificateHandlerHelper.java | 4 +- .../manager/core/model/ResourcesInfo.java | 13 +- .../openstack/OpenStackComputePlugin.java | 2 +- .../manager/xmpp/ManagerPacketHelper.java | 121 +++++++++++------- .../manager/xmpp/ManagerXmppComponent.java | 20 ++- .../core/TestCertificateOperations.java | 14 +- .../manager/core/TestManagerFacade.java | 6 +- .../occi/TestMemberServerResource.java | 4 +- .../manager/xmpp/TestFederationMember.java | 24 ++-- .../manager/xmpp/TestIAmAlive.java | 25 +++- .../manager/xmpp/TestWhoIsAlive.java | 50 ++++++-- .../manager/xmpp/util/ManagerTestHelper.java | 38 ++++-- 12 files changed, 209 insertions(+), 112 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java index eb0ee12f..61df180f 100644 --- a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java +++ b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java @@ -16,7 +16,7 @@ public class CertificateHandlerHelper { private static final String CERTIFICATE_KEY = "certificate"; private final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; - public static String ConvertToSendingFormat() throws CertificateException, + public static String convertToSendingFormat() throws CertificateException, IOException { Certificate cert = getCertificate(); byte[] base64Certificate = Base64.encodeBase64(cert.getEncoded()); @@ -39,7 +39,7 @@ public static Certificate getCertificate() throws IOException, return cert; } - public static Certificate ConvertToCertificateFormat( + public static Certificate convertToCertificateFormat( String base64StringCertificate) throws CertificateException { byte[] base64BytesCertificate = base64StringCertificate.getBytes(); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index cf1151ac..f054a25d 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.core.model; +import java.security.cert.Certificate; import java.util.List; public class ResourcesInfo { @@ -10,9 +11,11 @@ public class ResourcesInfo { private String memIdle; private String memInUse; private List flavours; + private Certificate cert; public ResourcesInfo(String id, String cpuIdle, String cpuInUse, - String memIdle, String memInUse, List flavours) { + String memIdle, String memInUse, List flavours, Certificate cert) { + this.setCert(cert); setId(id); setCpuIdle(cpuIdle); setCpuInUse(cpuInUse); @@ -87,4 +90,12 @@ public List getFlavours() { public void setFlavours(List flavours) { this.flavours = flavours; } + + public Certificate getCert() { + return cert; + } + + public void setCert(Certificate cert) { + this.cert = cert; + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index e5cf721d..61e811a3 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -271,7 +271,7 @@ public ResourcesInfo getResourcesInfo(String authToken) { int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); return new ResourcesInfo(null, String.valueOf(cpuIdle), cpuInUse, - String.valueOf(memIdle), memInUse, getFlavors(cpuIdle, memIdle)); + String.valueOf(memIdle), memInUse, getFlavors(cpuIdle, memIdle), null); } catch (URISyntaxException e) { LOGGER.error(e); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 1758cc08..1a0c17f6 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -1,5 +1,8 @@ package org.fogbowcloud.manager.xmpp; +import java.io.IOException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -11,6 +14,7 @@ import org.apache.http.HttpStatus; import org.dom4j.Attribute; import org.dom4j.Element; +import org.fogbowcloud.manager.core.CertificateHandlerHelper; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; @@ -31,13 +35,15 @@ public class ManagerPacketHelper { public static void iAmAlive(ResourcesInfo resourcesInfo, - String rendezvousAddress, PacketSender packetSender) { + String rendezvousAddress, PacketSender packetSender) + throws CertificateException, IOException { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); Element statusEl = iq.getElement() .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE) .addElement("status"); - iq.getElement().element("query").addElement("cert"); + iq.getElement().element("query").addElement("cert") + .setText(CertificateHandlerHelper.convertToSendingFormat()); statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); @@ -55,7 +61,7 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, } public static List whoIsalive(String rendezvousAddress, - PacketSender packetSender) { + PacketSender packetSender) throws CertificateException { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); iq.getElement().addElement("query", @@ -67,7 +73,7 @@ public static List whoIsalive(String rendezvousAddress, @SuppressWarnings("unchecked") private static ArrayList getMembersFromIQ( - IQ responseFromWhoIsAliveIQ) { + IQ responseFromWhoIsAliveIQ) throws CertificateException { Element queryElement = responseFromWhoIsAliveIQ.getElement().element( "query"); Iterator itemIterator = queryElement.elementIterator("item"); @@ -76,7 +82,9 @@ private static ArrayList getMembersFromIQ( while (itemIterator.hasNext()) { Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); - //TODO get certificate + Certificate cert = CertificateHandlerHelper + .convertToCertificateFormat(itemEl.element("cert") + .getText()); Element statusEl = itemEl.element("status"); String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); @@ -98,15 +106,15 @@ private static ArrayList getMembersFromIQ( } ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse, flavoursList); + cpuInUse, memIdle, memInUse, flavoursList, cert); FederationMember item = new FederationMember(resources); aliveItems.add(item); } return aliveItems; } - public static String remoteRequest(Request request, - String memberAddress, PacketSender packetSender) { + public static String remoteRequest(Request request, String memberAddress, + PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(memberAddress); iq.setType(Type.set); @@ -126,18 +134,18 @@ public static String remoteRequest(Request request, } IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - if (response.getError().getCondition().equals( - Condition.item_not_found)) { + if (response.getError().getCondition() + .equals(Condition.item_not_found)) { return null; } raiseException(response.getError()); } - return response.getElement().element("query") - .element("instance") + return response.getElement().element("query").element("instance") .elementText("id"); } - - public static Instance getRemoteInstance(Request request, PacketSender packetSender) { + + public static Instance getRemoteInstance(Request request, + PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(request.getMemberId()); iq.setType(Type.get); @@ -145,25 +153,25 @@ public static Instance getRemoteInstance(Request request, PacketSender packetSen ManagerXmppComponent.GETINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); try { - instanceEl.addElement("id").setText(request.getInstanceId()); + instanceEl.addElement("id").setText(request.getInstanceId()); } catch (Exception e) { // TODO: handle exception } - + IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - if (response.getError().getCondition().equals( - Condition.item_not_found)) { + if (response.getError().getCondition() + .equals(Condition.item_not_found)) { return null; } raiseException(response.getError()); } - + return parseInstance(response.getElement().element("query") .element("instance")); } - public static void deleteRemoteInstace(Request request, + public static void deleteRemoteInstace(Request request, PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(request.getMemberId()); @@ -172,73 +180,88 @@ public static void deleteRemoteInstace(Request request, ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); instanceEl.addElement("id").setText(request.getInstanceId()); - + IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { raiseException(response.getError()); } } - + private static void raiseException(PacketError error) { Condition condition = error.getCondition(); if (condition.equals(Condition.item_not_found)) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + throw new OCCIException(ErrorType.NOT_FOUND, + ResponseConstants.NOT_FOUND); } if (condition.equals(Condition.not_authorized)) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + throw new OCCIException(ErrorType.UNAUTHORIZED, + ResponseConstants.UNAUTHORIZED); } - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + throw new OCCIException(ErrorType.BAD_REQUEST, + ResponseConstants.IRREGULAR_SYNTAX); } @SuppressWarnings("unchecked") private static Instance parseInstance(Element instanceEl) { String id = instanceEl.element("id").getText(); - Element linkEl = instanceEl.element("link"); + Element linkEl = instanceEl.element("link"); String linkName = linkEl.element("link").getText(); - Iterator linkAttributeIterator = linkEl.elementIterator("attribute"); - + Iterator linkAttributeIterator = linkEl + .elementIterator("attribute"); + Map attributesLink = new HashMap(); while (linkAttributeIterator.hasNext()) { Element itemAttributeEl = (Element) linkAttributeIterator.next(); String key = itemAttributeEl.attributeValue("val"); String value = itemAttributeEl.getText(); attributesLink.put(key, value); - } + } Link link = new Link(linkName, attributesLink); - - Iterator resourceIterator = instanceEl.elementIterator("resource"); + + Iterator resourceIterator = instanceEl + .elementIterator("resource"); List resources = new ArrayList(); while (resourceIterator.hasNext()) { Element itemResourseEl = (Element) resourceIterator.next(); - String termCategory = itemResourseEl.element("category").element("term").getText(); - String schemeCategory = itemResourseEl.element("category").element("scheme").getText(); - String classCategory = itemResourseEl.element("category").element("class").getText(); - Category category = new Category(termCategory, schemeCategory, classCategory); + String termCategory = itemResourseEl.element("category") + .element("term").getText(); + String schemeCategory = itemResourseEl.element("category") + .element("scheme").getText(); + String classCategory = itemResourseEl.element("category") + .element("class").getText(); + Category category = new Category(termCategory, schemeCategory, + classCategory); - Iterator resourceAttributeIterator = itemResourseEl.element("category").elementIterator("attribute"); + Iterator resourceAttributeIterator = itemResourseEl + .element("category").elementIterator("attribute"); List resourceAttributes = new ArrayList(); while (resourceAttributeIterator.hasNext()) { - Element itemResourseAttributeEl = (Element) resourceAttributeIterator.next(); + Element itemResourseAttributeEl = (Element) resourceAttributeIterator + .next(); resourceAttributes.add(itemResourseAttributeEl.getText()); } - - Iterator resourceActionsIterator = itemResourseEl.element("category").elementIterator("action"); + + Iterator resourceActionsIterator = itemResourseEl.element( + "category").elementIterator("action"); List resourceActions = new ArrayList(); while (resourceActionsIterator.hasNext()) { - Element itemResourseActionEl = (Element) resourceActionsIterator.next(); + Element itemResourseActionEl = (Element) resourceActionsIterator + .next(); resourceActions.add(itemResourseActionEl.getText()); - } - + } + String location = itemResourseEl.element("location").getText(); String title = itemResourseEl.element("title").getText(); String rel = itemResourseEl.element("rel").getText(); - - resources.add(new Resource(category, resourceAttributes, resourceActions, location, title, rel)); - } - - Iterator attributesIterator = instanceEl.elementIterator("attribute"); - + + resources.add(new Resource(category, resourceAttributes, + resourceActions, location, title, rel)); + } + + Iterator attributesIterator = instanceEl + .elementIterator("attribute"); + Map attributes = new HashMap(); while (attributesIterator.hasNext()) { Element attributeEl = (Element) attributesIterator.next(); @@ -246,7 +269,7 @@ private static Instance parseInstance(Element instanceEl) { String value = attributeEl.getText(); attributes.put(key, value); } - + return new Instance(id, resources, attributes, link); } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 1ea8fb21..2aefc454 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.xmpp; +import java.io.IOException; +import java.security.cert.CertificateException; import java.util.Timer; import java.util.TimerTask; @@ -33,7 +35,7 @@ public void init() { scheduleIamAlive(); } - public void iAmAlive() { + public void iAmAlive() throws CertificateException, IOException { ManagerPacketHelper.iAmAlive(managerFacade.getResourcesInfo(), rendezvousAddress, this); } @@ -44,7 +46,7 @@ protected void send(Packet packet) { super.send(packet); } - public void whoIsalive() { + public void whoIsalive() throws CertificateException { managerFacade.updateMembers(ManagerPacketHelper.whoIsalive( rendezvousAddress, this)); } @@ -53,8 +55,18 @@ private void scheduleIamAlive() { timer.schedule(new TimerTask() { @Override public void run() { - iAmAlive(); - whoIsalive(); + try { + iAmAlive(); + } catch (CertificateException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + try { + whoIsalive(); + } catch (CertificateException e) { + e.printStackTrace(); + } } }, 0, PERIOD); } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java index a8cf187f..875d4ab1 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java @@ -1,30 +1,20 @@ package org.fogbowcloud.manager.core; -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.security.cert.Certificate; import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.Properties; -import org.apache.commons.codec.binary.Base64; import org.junit.Assert; import org.junit.Test; public class TestCertificateOperations { - private static final String CERTIFICATE_KEY = "certificate"; - private final String DEFAULT_PATH_TEST_VALUE_EMPTY = "src/test/resources/manager.conf.test"; - @Test public void testGetCertificate() throws IOException, CertificateException { Certificate cert = CertificateHandlerHelper.getCertificate(); Certificate result = CertificateHandlerHelper - .ConvertToCertificateFormat(CertificateHandlerHelper - .ConvertToSendingFormat()); + .convertToCertificateFormat(CertificateHandlerHelper + .convertToSendingFormat()); Assert.assertEquals(cert, result); } } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java index 2d32b35e..5a0fe1f6 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.core; +import java.io.IOException; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; @@ -35,7 +37,7 @@ public void testGet0ItemsFromIQ() { } @Test - public void testGet1ItemFromIQ() { + public void testGet1ItemFromIQ() throws CertificateException, IOException { FederationMember managerItem = new FederationMember(managerTestHelper.getResources()); List items = new LinkedList(); items.add(managerItem); @@ -48,7 +50,7 @@ public void testGet1ItemFromIQ() { } @Test - public void testGetManyItemsFromIQ() { + public void testGetManyItemsFromIQ() throws CertificateException, IOException { ArrayList items = new ArrayList(); for (int i = 0; i < 10; i++) { items.add(new FederationMember(managerTestHelper.getResources())); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java index f830d4af..7c834d41 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -53,9 +53,9 @@ public void testGetMember() throws Exception { flavours.add(new Flavor(FLAVOUR_1, "3", "135", 2)); flavours.add(new Flavor(FLAVOUR_2, "3", "135", 2)); ResourcesInfo resourcesInfo = new ResourcesInfo(ID_RESOURCEINFO1, "2", "1", "100", "35", - flavours); + flavours, null); ResourcesInfo resourcesInfo2 = new ResourcesInfo(ID_RESOURCEINFO2, "2", "1", "100", "35", - null); + null, null); federationMembers.add(new FederationMember(resourcesInfo)); federationMembers.add(new FederationMember(resourcesInfo)); federationMembers.add(new FederationMember(resourcesInfo2)); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java index 3d8ed5fe..9924e788 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.xmpp; +import java.io.IOException; +import java.security.cert.CertificateException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @@ -20,7 +22,7 @@ public class TestFederationMember { ManagerTestHelper managerTestHelper; @Before - public void setUp() { + public void setUp() throws CertificateException, IOException { managerTestHelper = new ManagerTestHelper(); resources = managerTestHelper.getResources(); } @@ -31,33 +33,33 @@ public void testInvalidResources() { } @Test(expected = IllegalArgumentException.class) - public void testNullResourceId() { + public void testNullResourceId() throws CertificateException, IOException { new ResourcesInfo(null, "cpuIdle", - "cpuInUse", "memIdle", "memInUse", new LinkedList()); + "cpuInUse", "memIdle", "memInUse", new LinkedList(), managerTestHelper.getCertificate()); } @Test(expected = IllegalArgumentException.class) - public void testNullResourcesCpuIdle() { + public void testNullResourcesCpuIdle() throws CertificateException, IOException { new ResourcesInfo("id", null, - "cpuInUse", "memIdle", "memInUse", new LinkedList()); + "cpuInUse", "memIdle", "memInUse", new LinkedList(), managerTestHelper.getCertificate()); } @Test(expected = IllegalArgumentException.class) - public void testNullResourcesCpuInUse() { + public void testNullResourcesCpuInUse() throws CertificateException, IOException { new ResourcesInfo("id", "CpuIdle", - null, "memIdle", "memInUse", new LinkedList()); + null, "memIdle", "memInUse", new LinkedList(), managerTestHelper.getCertificate()); } @Test(expected = IllegalArgumentException.class) - public void testNullResourcesMemIdle() { + public void testNullResourcesMemIdle() throws CertificateException, IOException { new ResourcesInfo("id", "CpuIdle", - "cpuInUse", null, "memInUse", new LinkedList()); + "cpuInUse", null, "memInUse", new LinkedList(), managerTestHelper.getCertificate()); } @Test(expected = IllegalArgumentException.class) - public void testNullResourcesMemInUse() { + public void testNullResourcesMemInUse() throws CertificateException, IOException { new ResourcesInfo("id", "CpuIdle", - "cpuInUse", "memIdle", null, new LinkedList()); + "cpuInUse", "memIdle", null, new LinkedList(), managerTestHelper.getCertificate()); } @Test diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 8af5de73..9c46eeba 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.xmpp; +import java.io.IOException; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -84,7 +86,7 @@ public boolean accept(Packet packet) { xmppClient.disconnect(); } - + @Test public void testCallIAmAlive() throws Exception { final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); @@ -102,10 +104,23 @@ public void processPacket(Packet packet) { public void processPacket(Packet packet) { IQ whoIsAlive = (IQ) packet; List aliveIds = new ArrayList(); - aliveIds.add(new FederationMember(managerTestHelper - .getResources())); - IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); + try { + aliveIds.add(new FederationMember(managerTestHelper + .getResources())); + } catch (CertificateException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } + IQ iq = null; + try { + iq = managerTestHelper.createWhoIsAliveResponse( + (ArrayList) aliveIds, whoIsAlive); + } catch (CertificateException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } try { xmppClient.syncSend(iq); } catch (XMPPException e) { diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java index 8056fc77..6a76f2c2 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.xmpp; +import java.io.IOException; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -49,10 +51,23 @@ public void processPacket(Packet packet) { e.printStackTrace(); } List aliveIds = new ArrayList(); - aliveIds.add(new FederationMember(managerTestHelper - .getResources())); - IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); + try { + aliveIds.add(new FederationMember(managerTestHelper + .getResources())); + } catch (CertificateException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + IQ iq = null; + try { + iq = managerTestHelper.createWhoIsAliveResponse( + (ArrayList) aliveIds, whoIsAlive); + } catch (CertificateException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } xmppClient.send(iq); } }; @@ -79,7 +94,8 @@ public boolean accept(Packet packet) { Assert.assertEquals(2, managerXmppComponent.getManagerFacade() .getMembers().get(0).getResourcesInfo().getFlavours().size()); Assert.assertEquals("small", managerXmppComponent.getManagerFacade() - .getMembers().get(0).getResourcesInfo().getFlavours().get(0).getName()); + .getMembers().get(0).getResourcesInfo().getFlavours().get(0) + .getName()); xmppClient.disconnect(); } @@ -91,10 +107,23 @@ public void testCallWhoIsAlive() throws Exception { public void processPacket(Packet packet) { IQ whoIsAlive = (IQ) packet; List aliveIds = new ArrayList(); - aliveIds.add(new FederationMember(managerTestHelper - .getResources())); - IQ iq = managerTestHelper.createWhoIsAliveResponse( - (ArrayList) aliveIds, whoIsAlive); + try { + aliveIds.add(new FederationMember(managerTestHelper + .getResources())); + } catch (CertificateException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } + IQ iq = null; + try { + iq = managerTestHelper.createWhoIsAliveResponse( + (ArrayList) aliveIds, whoIsAlive); + } catch (CertificateException e1) { + e1.printStackTrace(); + } catch (IOException e1) { + e1.printStackTrace(); + } try { xmppClient.syncSend(iq); } catch (XMPPException e) { @@ -123,6 +152,9 @@ public boolean accept(Packet packet) { Assert.assertEquals("small", managerXmppComponent.getManagerFacade() .getMembers().get(0).getResourcesInfo().getFlavours().get(0) .getName()); + Assert.assertEquals(managerTestHelper.getCertificate(), + managerXmppComponent.getManagerFacade().getMembers().get(0) + .getResourcesInfo().getCert()); xmppClient.disconnect(); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index f10ba758..4023c830 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -1,5 +1,8 @@ package org.fogbowcloud.manager.xmpp.util; +import java.io.IOException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; @@ -8,6 +11,7 @@ import org.dom4j.Attribute; import org.dom4j.Element; +import org.fogbowcloud.manager.core.CertificateHandlerHelper; import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; @@ -50,24 +54,26 @@ public class ManagerTestHelper { private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; - public ResourcesInfo getResources() { + public ResourcesInfo getResources() throws CertificateException, + IOException { List flavours = new LinkedList(); flavours.add(new Flavor("small", "cpu", "mem", 2)); flavours.add(new Flavor("small", "cpu", "mem", 3)); ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", - "value3", "value4", flavours); + "value3", "value4", flavours, getCertificate()); return resources; } public IQ createWhoIsAliveResponse(ArrayList aliveIds, - IQ iq) { + IQ iq) throws CertificateException, IOException { IQ resultIQ = IQ.createResultIQ(iq); Element queryElement = resultIQ.getElement().addElement("query", WHOISALIVE_NAMESPACE); for (FederationMember rendezvousItem : aliveIds) { Element itemEl = queryElement.addElement("item"); itemEl.addAttribute("id", rendezvousItem.getResourcesInfo().getId()); - + itemEl.addElement("cert").setText( + CertificateHandlerHelper.convertToSendingFormat()); Element statusEl = itemEl.addElement("status"); statusEl.addElement("cpu-idle").setText( rendezvousItem.getResourcesInfo().getCpuIdle()); @@ -112,7 +118,7 @@ public XMPPClient createXMPPClient() throws XMPPException { return xmppClient; } - + public PacketSender createPacketSender() throws XMPPException { final XMPPClient xmppClient = createXMPPClient(); PacketSender sender = new PacketSender() { @@ -126,7 +132,7 @@ public Packet syncSendPacket(Packet packet) { response.cancel(); return result; } - + @Override public void sendPacket(Packet packet) { xmppClient.send(packet); @@ -134,12 +140,11 @@ public void sendPacket(Packet packet) { }; return sender; } - - + public ComputePlugin getComputePlugin() { return computePlugin; } - + public IdentityPlugin getIdentityPlugin() { return identityPlugin; } @@ -177,7 +182,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) } return managerXmppComponent; } - + public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Exception { @@ -219,7 +224,7 @@ public void shutdown() throws ComponentException { } @SuppressWarnings("unchecked") - public List getItemsFromIQ(Packet response) { + public List getItemsFromIQ(Packet response) throws CertificateException, IOException { Element queryElement = response.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); ArrayList aliveItems = new ArrayList(); @@ -228,11 +233,11 @@ public List getItemsFromIQ(Packet response) { Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); Element statusEl = itemEl.element("status"); - String cpuIdle = statusEl.element("cpu-idle").getText(); + Certificate cert = CertificateHandlerHelper.convertToCertificateFormat(itemEl.element("cert").getText()); + String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); - List flavoursList = new LinkedList(); Iterator flavourIterator = itemEl .elementIterator("flavor"); @@ -248,13 +253,18 @@ public List getItemsFromIQ(Packet response) { } ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse, flavoursList); + cpuInUse, memIdle, memInUse, flavoursList, cert); FederationMember item = new FederationMember(resources); aliveItems.add(item); } return aliveItems; } + public Certificate getCertificate() throws CertificateException, + IOException { + return CertificateHandlerHelper.getCertificate(); + } + /* * public static IQ createIAmAliveIQ() { IQ iq = new IQ(Type.get); * iq.setTo(RENDEZVOUS_COMPONENT_URL); Element statusEl = iq.getElement() From 3279ab2ae6657d1072218df04e8787f1636209d1 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 29 Apr 2014 15:32:33 -0300 Subject: [PATCH 061/185] Implementing TokenServerResource --- .../org/fogbowcloud/manager/cli/Main.java | 28 ++++++++++++++++--- .../manager/core/ManagerFacade.java | 4 +++ .../openstack/OpenStackIdentityPlugin.java | 13 +++++---- .../manager/occi/OCCIApplication.java | 5 ++++ .../manager/occi/TokenServerResource.java | 21 ++++++++++++++ .../request/TestRequestServerResource.java | 3 -- 6 files changed, 62 insertions(+), 12 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 10fd649c..07665072 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -31,6 +31,8 @@ public static void main(String[] args) throws Exception { jc.addCommand("request", request); InstanceCommand instance = new InstanceCommand(); jc.addCommand("instance", instance); + TokenCommand token = new TokenCommand(); + jc.addCommand("token", token); jc.setProgramName("fogbow-cli"); jc.parse(args); @@ -67,9 +69,9 @@ public static void main(String[] args) throws Exception { return; } Set headers = new HashSet(); - headers.add("Category: fogbow-request; scheme=\"http://schemas.fogbowcloud.org/template/request#\"; class=\"mixin\""); - headers.add("X-OCCI-Attribute: fogbow.request.maxinstance = " + request.instanceCount); - headers.add("X-OCCI-Attribute: fogbow.request.type = one-time"); + headers.add("Category: fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\""); + headers.add("X-OCCI-Attribute: org.fogbowcloud.request.instance-count = " + request.instanceCount); + headers.add("X-OCCI-Attribute: org.fogbowcloud.request.type = one-time"); headers.add("Category: " + request.flavor + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); headers.add("Category: " + request.image + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); doRequest("post", url + "/request", request.authToken, headers); @@ -91,6 +93,13 @@ public static void main(String[] args) throws Exception { doRequest("delete", url + "/compute/" + instance.instanceId, instance.authToken); } + } else if (parsedCommand.equals("token")) { + String url = token.url; + Set headers = new HashSet(); + headers.add("password: " + token.password); + headers.add("username: " + token.username); + + doRequest("get", url + "/token", null, headers); } } @@ -115,7 +124,7 @@ private static void doRequest(String method, String endpoint, String authToken, request.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); } for (String header : additionalHeaders) { - String[] splitHeader = header.split(":"); + String[] splitHeader = header.split(": "); request.addHeader(splitHeader[0].trim(), splitHeader[1].trim()); } @@ -177,4 +186,15 @@ private static class InstanceCommand extends AuthedCommand { String instanceId = null; } + @Parameters(separators = "=", commandDescription = "Token operations") + private static class TokenCommand extends Command { + @Parameter(names = "--get", description = "Get token") + Boolean get = false; + + @Parameter(names = "--password", description = "Password") + String password = null; + + @Parameter(names = "--username", description = "Username") + String username = null; + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 2c93a84e..f33e3871 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -349,4 +349,8 @@ public void setPacketSender(PacketSender packetSender) { public void setRequests(RequestRepository requests) { this.requests = requests; } + + public String getToken(String username, String password) { + return identityPlugin.getToken(username, password); + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 75518efb..fa0f2fc0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -28,7 +28,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String AUTH_KEYSTONE = "auth"; public static final String TOKEN_KEYSTONE = "token"; public static final String ID_KEYSTONE = "id"; - public static final String ACCESS_KEYSTONE = "Access"; + public static final String ACCESS_KEYSTONE = "access"; public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; @@ -47,12 +47,10 @@ public OpenStackIdentityPlugin(Properties properties) { public String getUser(String authToken) { try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.v2Endpoint); + HttpGet httpGet = new HttpGet(this.v3Endpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); @@ -60,6 +58,9 @@ public String getUser(String authToken) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } + + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); return getUserNameUserFromJson(responseStr); } catch (Exception e) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); @@ -70,7 +71,7 @@ public String getUser(String authToken) { public String getToken(String username, String password) { try { HttpClient httpClient = new DefaultHttpClient(); - HttpPost httpPost = new HttpPost(this.v3Endpoint); + HttpPost httpPost = new HttpPost(this.v2Endpoint); httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); @@ -93,6 +94,7 @@ public String getToken(String username, String password) { return getTokenFromJson(responseStr); } catch (Exception e) { + e.printStackTrace(); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } } @@ -113,6 +115,7 @@ private String getTokenFromJson(String responseStr) { return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) .getString(ID_KEYSTONE); } catch (JSONException e) { + e.printStackTrace(); return null; } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index d350e79f..45846423 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -30,9 +30,14 @@ public Restlet createInboundRoot() { router.attach("/compute/", ComputeServerResource.class); router.attach("/compute/{instanceId}", ComputeServerResource.class); router.attach("/members", MemberServerResource.class); + router.attach("/token", TokenServerResource.class); return router; } + public String getToken(String username, String password) { + return managerFacade.getToken(username, password); + } + public List getFederationMembers() { return managerFacade.getMembers(); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java new file mode 100644 index 00000000..c1211e59 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java @@ -0,0 +1,21 @@ +package org.fogbowcloud.manager.occi; + +import org.restlet.engine.adapter.HttpRequest; +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +public class TokenServerResource extends ServerResource { + + @Get + public String fetch() { + OCCIApplication application = (OCCIApplication) getApplication(); + HttpRequest req = (HttpRequest) getRequest(); + HeaderUtils.checkOCCIContentType(req.getHeaders()); + + String username = req.getHeaders().getValues("username"); + String password = req.getHeaders().getValues("password"); + + return application.getToken(username, password); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java index f57a6fc6..3c9cb629 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/request/TestRequestServerResource.java @@ -6,9 +6,6 @@ import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; -import org.fogbowcloud.manager.occi.request.RequestAttribute; -import org.fogbowcloud.manager.occi.request.RequestConstants; -import org.fogbowcloud.manager.occi.request.RequestServerResource; import org.junit.Assert; import org.junit.Before; import org.junit.Test; From 3e69b57b88be04eeb447cb618d7d1f48dcd19f51 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 29 Apr 2014 16:02:08 -0300 Subject: [PATCH 062/185] Fixing MemberServerResource --- .../java/org/fogbowcloud/manager/occi/MemberServerResource.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java index b5821188..322a9350 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java @@ -18,7 +18,7 @@ public String fetch() { HeaderUtils.checkOCCIContentType(req.getHeaders()); List federationMembers = application.getFederationMembers(); - if (federationMembers == null) { + if (federationMembers.size() == 0) { return " "; } From f4ae08e838ef611ed6978d5a6fa98d0c8c0ae52a Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 29 Apr 2014 16:20:33 -0300 Subject: [PATCH 063/185] Fixing TestMemberServerResource --- .../fogbowcloud/manager/occi/TestMemberServerResource.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java index 7c834d41..0baec3a6 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -83,7 +83,9 @@ public void testGetMemberEmpty() throws Exception { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + List federationMembers = new ArrayList(); + + this.helper.initializeComponentMember(computePlugin, identityPlugin, federationMembers); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); From 8caaa345672d8b93130f302c51892ca3d526500a Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 03:45:08 +0200 Subject: [PATCH 064/185] Changing pom.xml for triggering exec --- pom.xml | 245 +++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 155 insertions(+), 90 deletions(-) diff --git a/pom.xml b/pom.xml index 9cc85038..e2909740 100644 --- a/pom.xml +++ b/pom.xml @@ -1,95 +1,160 @@ - 4.0.0 - org.fogbowcloud - manager - 0.0.1-SNAPSHOT + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + org.fogbowcloud + manager + 0.0.1-SNAPSHOT - - - maven-restlet - Public online Restlet repository - http://maven.restlet.org - - + + + maven-restlet + Public online Restlet repository + http://maven.restlet.org + + - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.4 - - - xml - html - - - - - clean - clean - - clean - - - - instrument - package - - instrument - cobertura - - - - - - + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + java + + -Dlog4j.configuration=file:log4j.cfg.xml + -cp + ${project.build.directory}/${project.artifactId}-${project.version}.jar:${project.build.directory}/lib/* + org.fogbowcloud.manager.Main + manager.conf + + + + + + exec + + + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.4 + + + xml + html + + + + + clean + clean + + clean + + + + instrument + package + + instrument + + + + + + maven-dependency-plugin + + + install + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + [1.0.0,) + + copy-dependencies + + + + + + + + + + + + + - - - org.jamppa - jamppa - 0.1.1 - - - org.mockito - mockito-all - 1.8.4 - - - org.restlet.jee - org.restlet - 2.2.0 - - - org.apache.httpcomponents - httpclient - 4.0-alpha4 - - - org.json - json - 20090211 - - - com.beust - jcommander - 1.35 - - - commons-io - commons-io - 2.4 - - + + + org.jamppa + jamppa + 0.1.1 + + + org.mockito + mockito-all + 1.8.4 + + + org.restlet.jee + org.restlet + 2.2.0 + + + org.apache.httpcomponents + httpclient + 4.0-alpha4 + + + org.json + json + 20090211 + + + com.beust + jcommander + 1.35 + + + commons-io + commons-io + 2.4 + + From bcdf726c7da1bffaf3868a8a0bbb42f269e72222 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 03:46:00 +0200 Subject: [PATCH 065/185] s/log4j.cfg.xml/log4j.properties --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index e2909740..39b97826 100644 --- a/pom.xml +++ b/pom.xml @@ -31,7 +31,7 @@ java - -Dlog4j.configuration=file:log4j.cfg.xml + -Dlog4j.configuration=file:log4j.properties -cp ${project.build.directory}/${project.artifactId}-${project.version}.jar:${project.build.directory}/lib/* org.fogbowcloud.manager.Main From 9473aaf3e491085af08ce003c5f6012a99c2dfae Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 03:49:02 +0200 Subject: [PATCH 066/185] pointing fogbow-cli to target --- bin/fogbow-cli | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/fogbow-cli b/bin/fogbow-cli index 7b3c80b0..3ac63ec2 100755 --- a/bin/fogbow-cli +++ b/bin/fogbow-cli @@ -1,3 +1,4 @@ #!/bin/bash - -java -cp .:./lib/* org.fogbowcloud.manager.cli.Main $@ \ No newline at end of file +DIRNAME=`dirname $0` +cd $DIRNAME/.. +java -cp target/manager-0.0.1-SNAPSHOT.jar:target/lib/* org.fogbowcloud.manager.cli.Main $@ \ No newline at end of file From 461b5c58abfa7f8b6ce18744cb45cc92175116c9 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 04:11:03 +0200 Subject: [PATCH 067/185] initializing xmpp component thread for iAmAlive --- src/main/java/org/fogbowcloud/manager/Main.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 1dbdfdf9..077f8771 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -34,6 +34,7 @@ public static void main(String[] args) throws Exception { facade); xmpp.connect(); xmpp.process(false); + xmpp.init(); facade.setPacketSender(xmpp); OCCIApplication application = new OCCIApplication(facade); From 61a6d2ce6cccc59f5af0a4e841c82f9f8354c381 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 05:23:03 +0200 Subject: [PATCH 068/185] Using project name header for auth --- manager.conf.example | 3 ++- .../core/plugins/openstack/OpenStackComputePlugin.java | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/manager.conf.example b/manager.conf.example index ff2cc486..1d314c4c 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -16,7 +16,8 @@ identity_openstack_url=http://localhost:5000 federation_user_name=fogbow federation_user_password=fogbow -federation_user_tenant_id=$tenantId +federation_user_tenant_id=d39e3c9bba294e3d9c47b8df9e29d81e +federation_user_tenant_name=demo scheduler_period=30000 diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 61e811a3..51ba6a53 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -35,6 +35,7 @@ public class OpenStackComputePlugin implements ComputePlugin { + private static final String X_AUTH_PROJECT_ID = "X-Auth-Project-Id"; private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; @@ -46,6 +47,7 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String CLASS_COMPUTE = "kind"; private static final String COMPUTE_ENDPOINT = "/compute/"; private final String federationTenantId; + private final String federationTenantName; private final String COMPUTE_V2_API_ENDEPOINT = "/v2/"; private static final String MAX_TOTAL_CORES_ATT = "maxTotalCores"; @@ -63,6 +65,7 @@ public OpenStackComputePlugin(Properties properties) { this.computeV2APIEndepoint = properties.getProperty("compute_openstack_v2api_url") + COMPUTE_V2_API_ENDEPOINT; this.federationTenantId = properties.getProperty("federation_user_tenant_id"); + this.federationTenantName = properties.getProperty("federation_user_tenant_name"); fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory("compute_openstack_flavor_small", properties)); @@ -252,6 +255,7 @@ public ResourcesInfo getResourcesInfo(String authToken) { try { httpGet = new HttpGet(computeV2APIEndepoint + federationTenantId + "/limits"); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + httpGet.addHeader(X_AUTH_PROJECT_ID, federationTenantName); HttpResponse response = httpCLient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { From 50e55c0f698a90116b8354520b2f4b8556a782e1 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 05:58:49 +0200 Subject: [PATCH 069/185] Asking token for an specific tenant. Should move parameter to interface. --- .../openstack/OpenStackComputePlugin.java | 4 ++-- .../openstack/OpenStackIdentityPlugin.java | 22 +++++++++++-------- .../manager/occi/core/OCCIHeaders.java | 2 +- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 51ba6a53..265837ff 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -48,7 +48,7 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String COMPUTE_ENDPOINT = "/compute/"; private final String federationTenantId; private final String federationTenantName; - private final String COMPUTE_V2_API_ENDEPOINT = "/v2/"; + private final String COMPUTE_V2_API_ENDPOINT = "/v2/"; private static final String MAX_TOTAL_CORES_ATT = "maxTotalCores"; private static final String TOTAL_CORES_USED_ATT = "totalCoresUsed"; @@ -63,7 +63,7 @@ public OpenStackComputePlugin(Properties properties) { this.computeOCCIEndpoint = properties.getProperty("compute_openstack_occi_url") + COMPUTE_ENDPOINT; this.computeV2APIEndepoint = properties.getProperty("compute_openstack_v2api_url") - + COMPUTE_V2_API_ENDEPOINT; + + COMPUTE_V2_API_ENDPOINT; this.federationTenantId = properties.getProperty("federation_user_tenant_id"); this.federationTenantName = properties.getProperty("federation_user_tenant_name"); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index fa0f2fc0..2fc1ca81 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -22,6 +22,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { + private static final String TENANT_NAME = "tenantName"; public static final String USERNAME_KEYSTONE = "username"; public static final String PASSWORD_KEYSTONE = "password"; public static final String PASSWORD_CREDENTIALS_KEYSTONE = "passwordCredentials"; @@ -37,9 +38,11 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { private String v2Endpoint; private String v3Endpoint; + private String federationTenantName; public OpenStackIdentityPlugin(Properties properties) { String keystoneUrl = properties.getProperty("identity_openstack_url"); + this.federationTenantName = properties.getProperty("federation_user_tenant_name"); this.v3Endpoint = keystoneUrl + V3_ENDPOINT_PATH; this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } @@ -49,7 +52,7 @@ public String getUser(String authToken) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(this.v3Endpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - httpGet.addHeader(OCCIHeaders.X_SUBJEC_TOKEN, authToken); + httpGet.addHeader(OCCIHeaders.X_SUBJECT_TOKEN, authToken); HttpResponse response = httpCLient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { @@ -76,14 +79,15 @@ public String getToken(String username, String password) { httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); - JSONObject rootCredentials = new JSONObject(); - rootCredentials.put(USERNAME_KEYSTONE, username); - rootCredentials.put(PASSWORD_KEYSTONE, password); - JSONObject rootAuth = new JSONObject(); - rootAuth.put(PASSWORD_CREDENTIALS_KEYSTONE, rootCredentials); - JSONObject rootMain = new JSONObject(); - rootMain.put(AUTH_KEYSTONE, rootAuth); - httpPost.setEntity(new StringEntity(rootMain.toString(), HTTP.UTF_8)); + JSONObject passwordCredentials = new JSONObject(); + passwordCredentials.put(USERNAME_KEYSTONE, username); + passwordCredentials.put(PASSWORD_KEYSTONE, password); + JSONObject auth = new JSONObject(); + auth.put(PASSWORD_CREDENTIALS_KEYSTONE, passwordCredentials); + auth.put(TENANT_NAME, this.federationTenantName); + JSONObject root = new JSONObject(); + root.put(AUTH_KEYSTONE, auth); + httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); HttpResponse response = httpClient.execute(httpPost); String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java index 6307e82f..f1abbbc7 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java @@ -5,7 +5,7 @@ public class OCCIHeaders { // header constants public static final String CONTENT_TYPE = "Content-Type"; public static final String X_AUTH_TOKEN = "X-Auth-Token"; - public static final String X_SUBJEC_TOKEN = "X-Subject-Token"; + public static final String X_SUBJECT_TOKEN = "X-Subject-Token"; // occi constants public static final String CATEGORY = "Category"; From 503393721c639acd3fc2f6c2f44a6cf620b7c240 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 06:08:23 +0200 Subject: [PATCH 070/185] resources info: id can be null --- .../fogbowcloud/manager/core/model/ResourcesInfo.java | 11 ++++++++--- .../plugins/openstack/OpenStackComputePlugin.java | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index f054a25d..fbfc9fd5 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -15,13 +15,18 @@ public class ResourcesInfo { public ResourcesInfo(String id, String cpuIdle, String cpuInUse, String memIdle, String memInUse, List flavours, Certificate cert) { - this.setCert(cert); + setCert(cert); setId(id); setCpuIdle(cpuIdle); setCpuInUse(cpuInUse); setMemIdle(memIdle); setMemInUse(memInUse); - this.setFlavours(flavours); + setFlavours(flavours); + } + + public ResourcesInfo(String cpuIdle, String cpuInUse, + String memIdle, String memInUse, List flavours, Certificate cert) { + this(null, cpuIdle, cpuInUse, memIdle, memInUse, flavours, cert); } public String getId() { @@ -29,7 +34,7 @@ public String getId() { } public void setId(String id) { - if (id == null || id.isEmpty()) { + if (id.isEmpty()) { throw new IllegalArgumentException("ResourceInfo id is invalid."); } this.id = id; diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 265837ff..02cc857d 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -274,7 +274,7 @@ public ResourcesInfo getResourcesInfo(String authToken) { int cpuIdle = Integer.parseInt(maxCpu) - Integer.parseInt(cpuInUse); int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); - return new ResourcesInfo(null, String.valueOf(cpuIdle), cpuInUse, + return new ResourcesInfo(String.valueOf(cpuIdle), cpuInUse, String.valueOf(memIdle), memInUse, getFlavors(cpuIdle, memIdle), null); } catch (URISyntaxException e) { From baa292a0b97f1292aecf7ebec78f2919cf2c7398 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 06:10:20 +0200 Subject: [PATCH 071/185] Removing any validation for setting ids --- .../java/org/fogbowcloud/manager/core/model/ResourcesInfo.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index fbfc9fd5..ccfceb1b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -34,9 +34,6 @@ public String getId() { } public void setId(String id) { - if (id.isEmpty()) { - throw new IllegalArgumentException("ResourceInfo id is invalid."); - } this.id = id; } From ee3002d993c45b0ab6ca92944bdd345084fe6129 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 06:20:20 +0200 Subject: [PATCH 072/185] Retrieving rendezvous address from conf file --- manager.conf.example | 2 ++ src/main/java/org/fogbowcloud/manager/Main.java | 1 + .../java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/manager.conf.example b/manager.conf.example index 1d314c4c..4483f2f4 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -3,6 +3,8 @@ xmpp_password=password xmpp_host=127.0.0.1 xmpp_port=5347 +rendezvous_jid=rendezvous.test.com + compute_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackComputePlugin compute_openstack_occi_url=http://localhost:8182 compute_openstack_v2api_url=http://localhost:8182 diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 077f8771..3e6734e7 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -32,6 +32,7 @@ public static void main(String[] args) throws Exception { properties.getProperty("xmpp_host"), Integer.parseInt(properties.getProperty("xmpp_port")), facade); + xmpp.setRendezvousAddress(properties.getProperty("rendezvous_jid")); xmpp.connect(); xmpp.process(false); xmpp.init(); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 2aefc454..a97e2336 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -17,7 +17,7 @@ public class ManagerXmppComponent extends XMPPComponent { public static final String GETINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/getinstance"; public static final String REMOVEINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/removeinstance"; - private static long PERIOD = 100; + private static long PERIOD = 30000; private ManagerFacade managerFacade; private final Timer timer = new Timer(); private String rendezvousAddress; From 7223abb256631c28d917a3b4c5e2894dc58cd607 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 06:40:57 +0200 Subject: [PATCH 073/185] Handling exceptions inside scheduleIamAlive --- .../manager/xmpp/ManagerXmppComponent.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index a97e2336..4ce5d60d 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -5,6 +5,7 @@ import java.util.Timer; import java.util.TimerTask; +import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.ManagerFacade; import org.jamppa.component.XMPPComponent; import org.xmpp.packet.Packet; @@ -18,6 +19,7 @@ public class ManagerXmppComponent extends XMPPComponent { public static final String REMOVEINSTANCE_NAMESPACE = "http://fogbowcloud.org/manager/removeinstance"; private static long PERIOD = 30000; + private static Logger LOGGER = Logger.getLogger(ManagerXmppComponent.class); private ManagerFacade managerFacade; private final Timer timer = new Timer(); private String rendezvousAddress; @@ -57,15 +59,13 @@ private void scheduleIamAlive() { public void run() { try { iAmAlive(); - } catch (CertificateException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); + } catch (Exception e) { + LOGGER.error(e); } try { whoIsalive(); - } catch (CertificateException e) { - e.printStackTrace(); + } catch (Exception e) { + LOGGER.error(e); } } }, 0, PERIOD); From ee55cd68c50898f36d43ec5eba7bf8937f3d01db Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 07:19:10 +0200 Subject: [PATCH 074/185] refactoring member resource --- .../manager/occi/MemberServerResource.java | 39 +++++++------------ .../manager/xmpp/ManagerXmppComponent.java | 4 +- 2 files changed, 15 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java index 322a9350..de4dc14c 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/MemberServerResource.java @@ -19,50 +19,37 @@ public String fetch() { List federationMembers = application.getFederationMembers(); if (federationMembers.size() == 0) { - return " "; + return new String(); } return generateResponse(federationMembers); } private String generateResponse(List federationMembers) { - String response = ""; + StringBuilder response = new StringBuilder(); for (FederationMember federationMember : federationMembers) { String id = federationMember.getResourcesInfo().getId(); + response.append("id=").append(id).append(";"); String cpuIdle = federationMember.getResourcesInfo().getCpuIdle(); + response.append("cpuIdle=").append(cpuIdle).append(";"); String cpuInUse = federationMember.getResourcesInfo().getCpuInUse(); + response.append("cpuInUse=").append(cpuInUse).append(";"); String memIdle = federationMember.getResourcesInfo().getMemIdle(); + response.append("memIdle=").append(memIdle).append(";"); String memInUse = federationMember.getResourcesInfo().getMemInUse(); - - String flavorStr = ""; - if (federationMember.getResourcesInfo().getFlavours() != null){ + response.append("memInUse=").append(memInUse).append(";"); + + if (federationMember.getResourcesInfo().getFlavours() != null) { for (Flavor flavor : federationMember.getResourcesInfo().getFlavours()) { String nameFlavor = flavor.getName(); Integer capacityFlavor = flavor.getCapacity(); - flavorStr = "flavour : \"" + nameFlavor + ", capacity=\"" + capacityFlavor + ""; + response.append("flavor: '").append(nameFlavor).append(", capacity=\"") + .append(capacityFlavor).append("\"';"); } } - - if (!cpuIdle.equals("")) { - cpuIdle = " ; " + "cpuIdle=\"" + cpuIdle ; - } - if (!cpuInUse.equals("")) { - cpuInUse = "\" ; " + "cpuInUse=\"" + cpuInUse; - } - if (!memIdle.equals("")) { - memIdle = "\" ; " + "menIdle=\"" + memIdle; - } - if (!memInUse.equals("")) { - memInUse = "\" ; " + "menInUse=\"" + memInUse; - } - if (!flavorStr.equals("")) { - flavorStr = "\" ; " + flavorStr + "\""; - } - - response += "id=\"" + id + "\"" + cpuIdle + cpuInUse + memIdle - + memInUse + flavorStr + "\"\n"; + response.append("\n"); } - return response.trim(); + return response.toString().trim(); } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 4ce5d60d..50ffaf1d 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -60,12 +60,12 @@ public void run() { try { iAmAlive(); } catch (Exception e) { - LOGGER.error(e); + LOGGER.error("Failure during IAmAlive()", e); } try { whoIsalive(); } catch (Exception e) { - LOGGER.error(e); + LOGGER.error("Failure during whoIsAlive()", e); } } }, 0, PERIOD); From 177bc231505025131b152442e8071a2fba8dcf8d Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 30 Apr 2014 09:56:20 -0300 Subject: [PATCH 075/185] Fixing Tests and ResourceRepository --- .../fogbowcloud/manager/occi/core/ResourceRepository.java | 2 +- .../fogbowcloud/manager/occi/TestMemberServerResource.java | 6 +----- .../org/fogbowcloud/manager/xmpp/TestFederationMember.java | 6 ------ 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java b/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java index 05d7fe26..740484d5 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ResourceRepository.java @@ -27,7 +27,7 @@ public static List getAll() { "Medium Flavor", ""); Resource fogbowLargeFlavor = new Resource(RequestConstants.LARGE_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS, - new ArrayList(), new ArrayList(), FOGBOWCLOUD_ENDPOINT + "/small", + new ArrayList(), new ArrayList(), FOGBOWCLOUD_ENDPOINT + "/large", "Large Flavor", ""); // image flavors Resource fogbowLinuxX86Flavor = new Resource(RequestConstants.LINUX_X86_TERM, diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java index 0baec3a6..34294e93 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -92,11 +92,7 @@ public void testGetMemberEmpty() throws Exception { HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); - - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - Assert.assertEquals(" ", responseStr); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); } @Test diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java index 9924e788..8733c446 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java @@ -31,12 +31,6 @@ public void setUp() throws CertificateException, IOException { public void testInvalidResources() { new FederationMember(null); } - - @Test(expected = IllegalArgumentException.class) - public void testNullResourceId() throws CertificateException, IOException { - new ResourcesInfo(null, "cpuIdle", - "cpuInUse", "memIdle", "memInUse", new LinkedList(), managerTestHelper.getCertificate()); - } @Test(expected = IllegalArgumentException.class) public void testNullResourcesCpuIdle() throws CertificateException, IOException { From 601c044f7d51405a1ac3422ec5fa016ce2136ec2 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 15:42:16 +0200 Subject: [PATCH 076/185] won't use X-Project header. --- .../core/plugins/openstack/OpenStackComputePlugin.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 02cc857d..b9d6b127 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -35,7 +35,6 @@ public class OpenStackComputePlugin implements ComputePlugin { - private static final String X_AUTH_PROJECT_ID = "X-Auth-Project-Id"; private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; @@ -47,7 +46,6 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String CLASS_COMPUTE = "kind"; private static final String COMPUTE_ENDPOINT = "/compute/"; private final String federationTenantId; - private final String federationTenantName; private final String COMPUTE_V2_API_ENDPOINT = "/v2/"; private static final String MAX_TOTAL_CORES_ATT = "maxTotalCores"; @@ -65,7 +63,6 @@ public OpenStackComputePlugin(Properties properties) { this.computeV2APIEndepoint = properties.getProperty("compute_openstack_v2api_url") + COMPUTE_V2_API_ENDPOINT; this.federationTenantId = properties.getProperty("federation_user_tenant_id"); - this.federationTenantName = properties.getProperty("federation_user_tenant_name"); fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory("compute_openstack_flavor_small", properties)); @@ -255,7 +252,6 @@ public ResourcesInfo getResourcesInfo(String authToken) { try { httpGet = new HttpGet(computeV2APIEndepoint + federationTenantId + "/limits"); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - httpGet.addHeader(X_AUTH_PROJECT_ID, federationTenantName); HttpResponse response = httpCLient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { From 9e5fc2f25939fe0dc4072e9b145d3d0ddf358788 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 11:14:26 -0300 Subject: [PATCH 077/185] Adding log --- .../manager/core/ManagerFacade.java | 57 +++++++++++-------- .../manager/occi/request/Request.java | 26 +++++---- 2 files changed, 48 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index f33e3871..b45ffe7c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -46,7 +46,7 @@ public class ManagerFacade { private IdentityPlugin identityPlugin; private Properties properties; private PacketSender packetSender; - + private SSHTunnel sshTunnel = new DefaultSSHTunnel(); public ManagerFacade(Properties properties) { @@ -55,11 +55,11 @@ public ManagerFacade(Properties properties) { throw new IllegalArgumentException(); } } - + public void setSSHTunnel(SSHTunnel sshTunnel) { this.sshTunnel = sshTunnel; } - + public void setComputePlugin(ComputePlugin computePlugin) { this.computePlugin = computePlugin; } @@ -78,7 +78,7 @@ public void updateMembers(List members) { public List getMembers() { return members; } - + public void setMembers(List members) { this.members = members; } @@ -133,8 +133,7 @@ public Instance getInstance(String authToken, String instanceId) { return getInstance(authToken, instanceId, request); } - private Instance getInstance(String authToken, String instanceId, - Request request) { + private Instance getInstance(String authToken, String instanceId, Request request) { Instance instance = null; if (isLocal(request)) { instance = this.computePlugin.getInstance(authToken, instanceId); @@ -143,10 +142,9 @@ private Instance getInstance(String authToken, String instanceId, } String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); if (sshAddress != null) { - instance.addAttribute(DefaultSSHTunnel.SSH_ADDRESS_ATT, - sshAddress); + instance.addAttribute(DefaultSSHTunnel.SSH_ADDRESS_ATT, sshAddress); } - + return instance; } @@ -169,8 +167,7 @@ public void removeInstance(String authToken, String instanceId) { removeInstance(authToken, instanceId, request); } - private void removeInstance(String authToken, String instanceId, - Request request) { + private void removeInstance(String authToken, String instanceId, Request request) { sshTunnel.release(request); if (isLocal(request)) { this.computePlugin.removeInstance(authToken, instanceId); @@ -189,8 +186,7 @@ public Request getRequestFromInstance(String authToken, String instanceId) { for (Request request : userRequests) { if (instanceId.equals(request.getInstanceId())) { if (!request.getUser().equals(user)) { - throw new OCCIException(ErrorType.UNAUTHORIZED, - ResponseConstants.UNAUTHORIZED); + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } return request; } @@ -207,7 +203,8 @@ public Request getRequest(String authToken, String requestId) { return requests.get(requestId); } - public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { + public String submitRequestForRemoteMember(List categories, + Map xOCCIAtt) { String token = getFederationUserToken(); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); @@ -219,10 +216,10 @@ public String submitRequestForRemoteMember(List categories, Map createRequests(String authToken, List categories, .getValue())); LOGGER.info("Request " + instanceCount + " instances"); - List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); @@ -260,8 +256,10 @@ public List createRequests(String authToken, List categories, try { sshTunnel.create(properties, request); } catch (Exception e) { + LOGGER.warn("Exception while creating ssh tunnel.", e); request.setState(RequestState.FAILED); } + LOGGER.debug("Updated request with tunnel properties : " + request); currentRequests.add(request); requests.addRequest(user, request); } @@ -276,7 +274,9 @@ private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(getMembers()); String memberAddress = member.getResourcesInfo().getId(); request.setMemberId(memberAddress); - + + LOGGER.info("Submiting request " + request.getId() + " to member " + memberAddress); + String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, memberAddress, packetSender); if (remoteInstanceId == null) { @@ -291,12 +291,16 @@ private boolean submitRemoteRequest(Request request) { private boolean submitLocalRequest(Request request) { request.setMemberId(null); String instanceLocation = null; + + LOGGER.info("Submiting local request " + request); + try { instanceLocation = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { if (e.getStatus().equals(ErrorType.BAD_REQUEST) && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + LOGGER.warn("Request failed locally for quota exceeded.", e); return false; } else { // TODO Think this through... @@ -309,16 +313,16 @@ private boolean submitLocalRequest(Request request) { instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); request.setInstanceId(instanceLocation); request.setState(RequestState.FULFILLED); + LOGGER.debug("Fulfilled Request: " + request); return true; } private void scheduleRequests() { scheduled = true; - String schedulerPeriodStr = properties.getProperty( - "scheduler_period"); - long schedulerPeriod = schedulerPeriodStr == null ? - DEFAULT_SCHEDULER_PERIOD : Long.valueOf(schedulerPeriodStr); - + String schedulerPeriodStr = properties.getProperty("scheduler_period"); + long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long + .valueOf(schedulerPeriodStr); + timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { @@ -329,6 +333,8 @@ public void run() { private void checkAndSubmitOpenRequests() { boolean allFulfilled = true; + LOGGER.debug("Checking and submiting requests."); + for (Request request : requests.get(RequestState.OPEN)) { Map xOCCIAtt = request.getxOCCIAtt(); for (String keyAttributes : RequestAttribute.getValues()) { @@ -337,6 +343,7 @@ private void checkAndSubmitOpenRequests() { allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); } if (allFulfilled) { + LOGGER.info("All request fulfilled."); timer.cancel(); scheduled = false; } @@ -349,7 +356,7 @@ public void setPacketSender(PacketSender packetSender) { public void setRequests(RequestRepository requests) { this.requests = requests; } - + public String getToken(String username, String password) { return identityPlugin.getToken(username, password); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index d5bbd219..845d6528 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -17,9 +17,9 @@ public class Request { private List categories; private Map xOCCIAtt; private String user; - - public Request(String id, String authToken, String user, - List categories, Map xOCCIAtt) { + + public Request(String id, String authToken, String user, List categories, + Map xOCCIAtt) { this.id = id; this.authToken = authToken; this.user = user; @@ -27,11 +27,11 @@ public Request(String id, String authToken, String user, this.xOCCIAtt = xOCCIAtt; setState(RequestState.OPEN); } - + public List getCategories() { return categories; } - + public void addCategory(Category category) { if (categories == null) { categories = new LinkedList(); @@ -42,7 +42,7 @@ public void addCategory(Category category) { public String getUser() { return user; } - + public String getInstanceId() { return instanceId; } @@ -63,20 +63,20 @@ public String getId() { return id; } - public String getAttValue(String attributeName){ + public String getAttValue(String attributeName) { if (xOCCIAtt == null) { return null; } return xOCCIAtt.get(attributeName); } - - public void putAttValue(String attributeName, String attributeValue){ + + public void putAttValue(String attributeName, String attributeValue) { if (xOCCIAtt == null) { xOCCIAtt = new HashMap(); } xOCCIAtt.put(attributeName, attributeValue); } - + public String toHttpMessageFormat() { return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; } @@ -96,4 +96,10 @@ public String getMemberId() { public void setMemberId(String memberId) { this.memberId = memberId; } + + public String toString() { + return "id: " + id + ", authToken: " + authToken + ", user: " + user + ", instanceId: " + + instanceId + ", memberId: " + memberId + ", state: " + state + ", categories: " + + categories + ", xOCCIAtt: " + xOCCIAtt; + } } \ No newline at end of file From 560e0819cfc4711134e64ae28467d893a427b599 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 11:30:10 -0300 Subject: [PATCH 078/185] Removing fogbow-request category --- .../core/plugins/openstack/OpenStackComputePlugin.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index b9d6b127..1a885f86 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -90,6 +90,10 @@ public String requestInstance(String authToken, List categories, Category categoryCompute = new Category(TERM_COMPUTE, SCHEME_COMPUTE, CLASS_COMPUTE); openStackCategories.add(categoryCompute); + //removing fogbow-request category + categories.remove(new Category(RequestConstants.TERM, RequestConstants.SCHEME, + RequestConstants.CLASS)); + for (Category category : categories) { if (fogTermToOpensStackCategory.get(category.getTerm()) == null) { throw new OCCIException(ErrorType.BAD_REQUEST, From f7561588664b90c15c168494f8f5a1f8303e5037 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 12:11:52 -0300 Subject: [PATCH 079/185] Implement instanceId header --- .../manager/core/plugins/openstack/OpenStackComputePlugin.java | 2 ++ .../org/fogbowcloud/manager/occi/util/ComputeApplication.java | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 1a885f86..eaa86b51 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -125,6 +125,8 @@ public String requestInstance(String authToken, List categories, throw new OCCIException(ErrorType.NOT_FOUND, EntityUtils.toString( response.getEntity(), String.valueOf(Charsets.UTF_8))); } + +// String instanceLocation = response.getFirstHeader("Location").getValue(); return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (URISyntaxException e) { LOGGER.error(e); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index aba985c4..f7437b5c 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -261,6 +261,8 @@ public String post() { String computeEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); String instanceId = application.newInstance(authToken, categories, xOCCIAtt); + + return HeaderUtils.X_OCCI_LOCATION + computeEndpoint + "/" + instanceId; } From e424489c94006ef0cef61b2d72d35cef708f8cbd Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 13:19:29 -0300 Subject: [PATCH 080/185] Implement Location header of OpenStackCompute Plugin --- .../openstack/OpenStackComputePlugin.java | 3 +- .../occi/plugins/TestComputeOpenStack.java | 37 ++++++++++--------- .../manager/occi/util/ComputeApplication.java | 4 +- 3 files changed, 23 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index eaa86b51..2e68eea7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -126,8 +126,7 @@ public String requestInstance(String authToken, List categories, response.getEntity(), String.valueOf(Charsets.UTF_8))); } -// String instanceLocation = response.getFirstHeader("Location").getValue(); - return EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); + return response.getFirstHeader("Location").getValue(); } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index b1fe6480..6d64bcfb 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -9,7 +9,6 @@ import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.instance.Instance; @@ -29,10 +28,9 @@ public class TestComputeOpenStack { private static final String FOURTH_INSTANCE_ID = "qwuif8ad-19a3-4afg-1l77-tred90crei0q"; private static final String THIRD_INSTANCE_ID = "cg2563ee-503c-6abr-54gl-ba8d12hf0pof"; private static final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; - + private static final String URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; - private static final String LOCATION_INSTANCE_PREFIX = HeaderUtils.X_OCCI_LOCATION - + URL + ComputeApplication.TARGET + "/"; + private static final String LOCATION_INSTANCE_PREFIX = URL + ComputeApplication.TARGET + "/"; private OpenStackComputePlugin computeOpenStack; private PluginHelper pluginHelper; @@ -46,7 +44,7 @@ public void setUp() throws Exception { properties.put("compute_openstack_flavor_medium", ComputeApplication.MEDIUM_FLAVOR_TERM); properties.put("compute_openstack_flavor_large", ComputeApplication.MEDIUM_FLAVOR_TERM); properties.put("compute_openstack_default_cirros_image", CIRROS_IMAGE_TERM); - + computeOpenStack = new OpenStackComputePlugin(properties); // five first generated instance ids @@ -78,17 +76,20 @@ public void testRequestAValidInstance() { computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); - Instance instance = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, - FIRST_INSTANCE_ID); + Instance instance = computeOpenStack + .getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); - Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), - ComputeApplication.CORE_ATTRIBUTE_OCCI))); - Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), - ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); - Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), + Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails( + instance.toOCCIMassageFormatDetails(), ComputeApplication.CORE_ATTRIBUTE_OCCI))); + Assert.assertEquals(2, Integer.parseInt(getAttValueFromDetails( + instance.toOCCIMassageFormatDetails(), ComputeApplication.MEMORY_ATTRIBUTE_OCCI))); + Assert.assertEquals(64, Integer.parseInt(getAttValueFromDetails( + instance.toOCCIMassageFormatDetails(), ComputeApplication.ARCHITECTURE_ATTRIBUTE_OCCI))); - Assert.assertEquals("server-" + FIRST_INSTANCE_ID, - getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); + Assert.assertEquals( + "server-" + FIRST_INSTANCE_ID, + getAttValueFromDetails(instance.toOCCIMassageFormatDetails(), + ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); } private String getAttValueFromDetails(String instanceDetails, String attName) { @@ -241,7 +242,8 @@ public void testGetAllInstanceIds() { instanceLocations = getInstanceLocations(computeOpenStack .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(1, instanceLocations.size()); - Assert.assertEquals(URL + ComputeApplication.TARGET + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); + Assert.assertEquals(URL + ComputeApplication.TARGET + "/" + FIRST_INSTANCE_ID, + instanceLocations.get(0)); } @Test @@ -266,14 +268,15 @@ public void testGetAllManyInstanceIds() { .getInstances(PluginHelper.AUTH_TOKEN)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); for (String expectedId : expectedInstanceIds) { - Assert.assertTrue(instanceLocations.contains(URL + ComputeApplication.TARGET + "/" + expectedId)); + Assert.assertTrue(instanceLocations.contains(URL + ComputeApplication.TARGET + "/" + + expectedId)); } } private List getInstanceLocations(List intances) { List locations = new ArrayList(); for (Instance instance : intances) { -// String instanceMessage = instance.toOCCIMassageFormatLocation(); + // String instanceMessage = instance.toOCCIMassageFormatLocation(); String[] lineTokens = instance.toOCCIMassageFormatLocation().split("Location:"); locations.add(lineTokens[1].trim()); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index f7437b5c..7485209e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -262,8 +262,8 @@ public String post() { String computeEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); String instanceId = application.newInstance(authToken, categories, xOCCIAtt); - - return HeaderUtils.X_OCCI_LOCATION + computeEndpoint + "/" + instanceId; + getResponse().setLocationRef(computeEndpoint + "/" + instanceId); + return ResponseConstants.OK; } @Delete From 3a387cec2215438bbe4f6328d2ae6b895a82a289 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 18:58:36 +0200 Subject: [PATCH 081/185] ssh tunnel: s/sbin/bin --- bin/fogbow-inject-tunnel | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/fogbow-inject-tunnel b/bin/fogbow-inject-tunnel index 2a8c7af2..85ed4622 100644 --- a/bin/fogbow-inject-tunnel +++ b/bin/fogbow-inject-tunnel @@ -1,2 +1,2 @@ #!/bin/sh -/usr/sbin/ssh -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# \ No newline at end of file +/usr/bin/ssh -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# \ No newline at end of file From cb10f8bddd4661bac6f349b33e21e9d0a499af11 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 20:17:33 +0200 Subject: [PATCH 082/185] Allowing for listing of all instances or requests --- .../org/fogbowcloud/manager/cli/Main.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 07665072..60d2c411 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -50,12 +50,16 @@ public static void main(String[] args) throws Exception { } else if (parsedCommand.equals("request")) { String url = request.url; if (request.get) { - if (request.create || request.delete || request.requestId == null) { + if (request.create || request.delete) { jc.usage(); return; } - doRequest("get", url + "/request/" + request.requestId, - request.authToken); + if (request.requestId != null) { + doRequest("get", url + "/request/" + request.requestId, + request.authToken); + } else { + doRequest("get", url + "/request", request.authToken); + } } else if (request.delete) { if (request.create || request.get || request.requestId == null) { jc.usage(); @@ -82,14 +86,18 @@ public static void main(String[] args) throws Exception { jc.usage(); return; } - if (instance.instanceId == null) { - jc.usage(); - return; - } if (instance.get) { - doRequest("get", url + "/compute/" + instance.instanceId, - instance.authToken); + if (instance.instanceId != null) { + doRequest("get", url + "/compute/" + instance.instanceId, + instance.authToken); + } else { + doRequest("get", url + "/compute", instance.authToken); + } } else if (instance.delete) { + if (instance.instanceId == null) { + jc.usage(); + return; + } doRequest("delete", url + "/compute/" + instance.instanceId, instance.authToken); } From b8358f2083ac62adbdfed0dbd12c2a1b47a41a40 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 15:41:25 -0300 Subject: [PATCH 083/185] Adding log --- .../java/org/fogbowcloud/manager/cli/Main.java | 7 ++++++- .../fogbowcloud/manager/core/ManagerFacade.java | 5 +++++ .../occi/instance/ComputeServerResource.java | 14 +++++++++++++- .../manager/occi/request/RequestRepository.java | 11 +++++++++++ 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 60d2c411..d0c5933d 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -7,6 +7,7 @@ import org.apache.http.HttpException; import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; @@ -139,7 +140,11 @@ private static void doRequest(String method, String endpoint, String authToken, HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); - System.out.println(EntityUtils.toString(response.getEntity())); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ + System.out.println(EntityUtils.toString(response.getEntity())); + } else { + System.out.println(response.getStatusLine().toString()); + } } private static class Command { diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index b45ffe7c..4decce13 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -112,6 +112,8 @@ public void removeRequest(String authToken, String requestId) { private void checkRequestId(String authToken, String requestId) { String user = getUser(authToken); if (requests.get(user, requestId) == null) { + LOGGER.warn("User " + user + " does not have requesId " + requestId); + LOGGER.warn("Throwing OCCIException at checkRequesId: " + ResponseConstants.NOT_FOUND); throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } } @@ -182,15 +184,18 @@ private void removeRemoteInstance(Request request) { public Request getRequestFromInstance(String authToken, String instanceId) { String user = getUser(authToken); + LOGGER.debug("Getting instance " + instanceId + " of user " + user); List userRequests = requests.getAll(); for (Request request : userRequests) { if (instanceId.equals(request.getInstanceId())) { if (!request.getUser().equals(user)) { + LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + ResponseConstants.UNAUTHORIZED); throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } return request; } } + LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + ResponseConstants.NOT_FOUND); throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java index fd426dd1..ddc49e00 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java @@ -2,9 +2,11 @@ import java.util.List; +import org.apache.log4j.Logger; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.request.RequestServerResource; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Delete; import org.restlet.resource.Get; @@ -13,6 +15,8 @@ public class ComputeServerResource extends ServerResource { + private static final Logger LOGGER = Logger.getLogger(ComputeServerResource.class); + @Get public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); @@ -22,8 +26,12 @@ public String fetch() { String instanceId = (String) getRequestAttributes().get("instanceId"); if (instanceId == null) { + LOGGER.info("Getting all instances of token :" + authToken); return generateResponse(application.getInstances(authToken)); - } + } + + LOGGER.info("Getting instance " + instanceId); + return application.getInstance(authToken, instanceId).toOCCIMassageFormatDetails(); } @@ -36,9 +44,13 @@ public String remove() { String instanceId = (String) getRequestAttributes().get("instanceId"); if (instanceId == null) { + LOGGER.info("Removing all instances of token :" + authToken); application.removeInstances(authToken); return ResponseConstants.OK; } + + LOGGER.info("Removing instance " + instanceId); + application.removeInstance(authToken, instanceId); return ResponseConstants.OK; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index 8eb37e28..b5ce61a6 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -6,11 +6,17 @@ import java.util.List; import java.util.Map; +import org.apache.log4j.Logger; +import org.fogbowcloud.manager.occi.instance.ComputeServerResource; + public class RequestRepository { + private static final Logger LOGGER = Logger.getLogger(RequestRepository.class); + private Map> requests = new HashMap>(); public void addRequest(String user, Request request) { + LOGGER.debug("Adding request " + request.getId() + " to user " + user); List userRequests = requests.get(user); if (userRequests == null) { userRequests = new LinkedList(); @@ -35,23 +41,28 @@ public Request get(String requestId) { for (List userRequests : requests.values()) { for (Request request : userRequests) { if (request.getId().equals(requestId)) { + LOGGER.debug("Getting request id " + request); return request; } } } + LOGGER.debug("Request id " + requestId + " was not found."); return null; } public Request get(String user, String requestId) { List userRequests = requests.get(user); if (userRequests == null) { + LOGGER.debug("User " + user + " does not have requests."); return null; } for (Request request : userRequests) { if (request.getId().equals(requestId)) { + LOGGER.debug("Getting request " + request + " owner by user " + user); return request; } } + LOGGER.debug("Request " + requestId + " owner by user " + user + " was not found."); return null; } From 773aa4c17e06350cad2006ed1e237d3d5b4eb99d Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Wed, 30 Apr 2014 20:30:28 +0200 Subject: [PATCH 084/185] compute endpoint has an ending slash --- src/main/java/org/fogbowcloud/manager/cli/Main.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index d0c5933d..6456eeaa 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -92,7 +92,7 @@ public static void main(String[] args) throws Exception { doRequest("get", url + "/compute/" + instance.instanceId, instance.authToken); } else { - doRequest("get", url + "/compute", instance.authToken); + doRequest("get", url + "/compute/", instance.authToken); } } else if (instance.delete) { if (instance.instanceId == null) { From d5fb200450eb69fd267a2c14d93993c63975ab52 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 16:12:25 -0300 Subject: [PATCH 085/185] Fixing OpenStackComputePlugin to return only instacneId instead instance location --- .../openstack/OpenStackComputePlugin.java | 10 ++++++++-- .../occi/plugins/TestComputeOpenStack.java | 19 +++++++++---------- .../manager/occi/util/ComputeApplication.java | 2 +- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 2e68eea7..3f815f88 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -125,8 +125,8 @@ public String requestInstance(String authToken, List categories, throw new OCCIException(ErrorType.NOT_FOUND, EntityUtils.toString( response.getEntity(), String.valueOf(Charsets.UTF_8))); } - - return response.getFirstHeader("Location").getValue(); + String instanceLocation = response.getFirstHeader("Location").getValue(); + return getInstanceId(instanceLocation); } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { @@ -137,6 +137,12 @@ public String requestInstance(String authToken, List categories, return null; } + private String getInstanceId(String instanceLocation) { + //location format: OCCI_URL + COMPUTE_ENDPOINT + instanceID + String[] tokens = instanceLocation.split(COMPUTE_ENDPOINT); + return tokens[1]; + } + public Instance getInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 6d64bcfb..4b6049e3 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -30,7 +30,6 @@ public class TestComputeOpenStack { private static final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; private static final String URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; - private static final String LOCATION_INSTANCE_PREFIX = URL + ComputeApplication.TARGET + "/"; private OpenStackComputePlugin computeOpenStack; private PluginHelper pluginHelper; @@ -72,7 +71,7 @@ public void testRequestAValidInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -120,7 +119,7 @@ public void testRequestWithoutSizeCateory() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -192,7 +191,7 @@ public void testSupportedOCCIAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, @@ -213,7 +212,7 @@ public void testMoreSupportedOCCIAtts() { xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); xOCCIAtt.put("occi.compute.state", "inactive"); - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, @@ -234,7 +233,7 @@ public void testGetAllInstanceIds() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -258,7 +257,7 @@ public void testGetAllManyInstanceIds() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + instanceId, computeOpenStack + Assert.assertEquals(instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -293,7 +292,7 @@ public void testGetInstanceDetails() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -338,7 +337,7 @@ public void testDeleteAllManyInstances() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + instanceId, computeOpenStack + Assert.assertEquals(instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -366,7 +365,7 @@ public void testDeleteOneInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(LOCATION_INSTANCE_PREFIX + instanceId, computeOpenStack + Assert.assertEquals(instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java index 7485209e..da323487 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/ComputeApplication.java @@ -262,7 +262,7 @@ public String post() { String computeEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); String instanceId = application.newInstance(authToken, categories, xOCCIAtt); - getResponse().setLocationRef(computeEndpoint + "/" + instanceId); + getResponse().setLocationRef(computeEndpoint + instanceId); return ResponseConstants.OK; } From fff5ca7c05133620263d8cd76c3479b15de7002e Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 16:17:04 -0300 Subject: [PATCH 086/185] Fixing timer bug: when timer is canceled, it can not be scheduled. Then, timer needs to be initialized every time it'll be scheduled. --- .../java/org/fogbowcloud/manager/core/ManagerFacade.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 4decce13..03bffd70 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -36,7 +36,7 @@ public class ManagerFacade { public static final long DEFAULT_SCHEDULER_PERIOD = 30000; private boolean scheduled = false; - private final Timer timer = new Timer(); + private Timer timer; private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); @@ -327,7 +327,8 @@ private void scheduleRequests() { String schedulerPeriodStr = properties.getProperty("scheduler_period"); long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long .valueOf(schedulerPeriodStr); - + + timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { From 5dc6e97a44193fc9fd3cfdfdb6bfac9f8ea06114 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 30 Apr 2014 20:13:52 -0300 Subject: [PATCH 087/185] Fixing some bugs and adding logs --- bin/fogbow-inject-tunnel | 2 +- manager.conf.example | 4 +-- .../manager/core/ManagerFacade.java | 33 ++++++++++++------- .../openstack/OpenStackComputePlugin.java | 30 +++++++++-------- .../manager/occi/OCCIApplication.java | 2 ++ .../occi/instance/ComputeServerResource.java | 3 +- .../manager/occi/request/Request.java | 2 +- .../occi/request/RequestRepository.java | 3 ++ 8 files changed, 48 insertions(+), 31 deletions(-) diff --git a/bin/fogbow-inject-tunnel b/bin/fogbow-inject-tunnel index 85ed4622..962d6ad0 100644 --- a/bin/fogbow-inject-tunnel +++ b/bin/fogbow-inject-tunnel @@ -1,2 +1,2 @@ #!/bin/sh -/usr/bin/ssh -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# \ No newline at end of file +/usr/bin/ssh -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# diff --git a/manager.conf.example b/manager.conf.example index 4483f2f4..f20fb164 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -5,7 +5,7 @@ xmpp_port=5347 rendezvous_jid=rendezvous.test.com -compute_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackComputePlugin +compute_class=org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin compute_openstack_occi_url=http://localhost:8182 compute_openstack_v2api_url=http://localhost:8182 compute_openstack_flavor_small=m1-small @@ -13,7 +13,7 @@ compute_openstack_flavor_medium=m1-medium compute_openstack_flavor_large=m1-large compute_openstack_default_cirros_image=cadf2e29-7216-4a5e-9364-cf6513d5f1fd -identity_class=org.fogbowcloud.manager.occi.plugins.openstack.OpenStackIdentityPlugin +identity_class=org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin identity_openstack_url=http://localhost:5000 federation_user_name=fogbow diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 03bffd70..19b63d18 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -19,7 +19,6 @@ import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; -import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.instance.Instance; @@ -119,13 +118,19 @@ private void checkRequestId(String authToken, String requestId) { } public List getInstances(String authToken) { + LOGGER.debug("Getting instances of token " + authToken); List instances = new ArrayList(); for (Request request : requests.getByUser(getUser(authToken))) { String instanceId = request.getInstanceId(); + LOGGER.debug("InstanceId " + instanceId); if (instanceId == null) { continue; } - instances.add(getInstance(authToken, instanceId, request)); + try { + instances.add(getInstance(authToken, instanceId, request)); + } catch (Exception e) { + LOGGER.warn("Exception thown while getting instance " + instanceId + ".", e); + } } return instances; } @@ -176,6 +181,11 @@ private void removeInstance(String authToken, String instanceId, Request request } else { removeRemoteInstance(request); } + request.setInstanceId(null); + request.setMemberId(null); + if (request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { + request.setState(RequestState.OPEN); + } } private void removeRemoteInstance(Request request) { @@ -189,13 +199,15 @@ public Request getRequestFromInstance(String authToken, String instanceId) { for (Request request : userRequests) { if (instanceId.equals(request.getInstanceId())) { if (!request.getUser().equals(user)) { - LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + ResponseConstants.UNAUTHORIZED); + LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + + ResponseConstants.UNAUTHORIZED); throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } return request; } } - LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + ResponseConstants.NOT_FOUND); + LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + + ResponseConstants.NOT_FOUND); throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } @@ -295,12 +307,12 @@ private boolean submitRemoteRequest(Request request) { private boolean submitLocalRequest(Request request) { request.setMemberId(null); - String instanceLocation = null; - + String instanceId = null; + LOGGER.info("Submiting local request " + request); - + try { - instanceLocation = computePlugin.requestInstance(request.getAuthToken(), + instanceId = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { if (e.getStatus().equals(ErrorType.BAD_REQUEST) @@ -315,8 +327,7 @@ private boolean submitLocalRequest(Request request) { } } - instanceLocation = instanceLocation.replace(HeaderUtils.X_OCCI_LOCATION, "").trim(); - request.setInstanceId(instanceLocation); + request.setInstanceId(instanceId); request.setState(RequestState.FULFILLED); LOGGER.debug("Fulfilled Request: " + request); return true; @@ -327,7 +338,7 @@ private void scheduleRequests() { String schedulerPeriodStr = properties.getProperty("scheduler_period"); long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long .valueOf(schedulerPeriodStr); - + timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 3f815f88..804b6d67 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -38,7 +38,7 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; - + private static final String ABSOLUTE = "absolute"; private static final String LIMITS = "limits"; private static final Logger LOGGER = Logger.getLogger(OpenStackComputePlugin.class); @@ -70,11 +70,11 @@ public OpenStackComputePlugin(Properties properties) { createFlavorCategory("compute_openstack_flavor_medium", properties)); fogTermToOpensStackCategory.put(RequestConstants.LARGE_TERM, createFlavorCategory("compute_openstack_flavor_large", properties)); - fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, new Category( - properties.getProperty("compute_openstack_default_cirros_image"), - OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); - fogTermToOpensStackCategory.put(RequestConstants.USER_DATA_TERM, - new Category("user_data", INSTANCE_SCHEME, OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.LINUX_X86_TERM, + new Category(properties.getProperty("compute_openstack_default_cirros_image"), + OS_SCHEME, OCCIHeaders.MIXIN_CLASS)); + fogTermToOpensStackCategory.put(RequestConstants.USER_DATA_TERM, new Category("user_data", + INSTANCE_SCHEME, OCCIHeaders.MIXIN_CLASS)); } private static Category createFlavorCategory(String flavorPropName, Properties properties) { @@ -90,10 +90,10 @@ public String requestInstance(String authToken, List categories, Category categoryCompute = new Category(TERM_COMPUTE, SCHEME_COMPUTE, CLASS_COMPUTE); openStackCategories.add(categoryCompute); - //removing fogbow-request category + // removing fogbow-request category categories.remove(new Category(RequestConstants.TERM, RequestConstants.SCHEME, RequestConstants.CLASS)); - + for (Category category : categories) { if (fogTermToOpensStackCategory.get(category.getTerm()) == null) { throw new OCCIException(ErrorType.BAD_REQUEST, @@ -101,8 +101,10 @@ public String requestInstance(String authToken, List categories, } openStackCategories.add(fogTermToOpensStackCategory.get(category.getTerm())); } - - xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(DefaultSSHTunnel.USER_DATA_ATT)); + + xOCCIAtt.put("org.openstack.compute.user_data", + xOCCIAtt.remove(DefaultSSHTunnel.USER_DATA_ATT)); + xOCCIAtt.remove(DefaultSSHTunnel.SSH_ADDRESS_ATT); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost; @@ -138,8 +140,8 @@ public String requestInstance(String authToken, List categories, } private String getInstanceId(String instanceLocation) { - //location format: OCCI_URL + COMPUTE_ENDPOINT + instanceID - String[] tokens = instanceLocation.split(COMPUTE_ENDPOINT); + // location format: OCCI_URL + COMPUTE_ENDPOINT + instanceID + String[] tokens = instanceLocation.split(COMPUTE_ENDPOINT); return tokens[1]; } @@ -281,8 +283,8 @@ public ResourcesInfo getResourcesInfo(String authToken) { int cpuIdle = Integer.parseInt(maxCpu) - Integer.parseInt(cpuInUse); int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); - return new ResourcesInfo(String.valueOf(cpuIdle), cpuInUse, - String.valueOf(memIdle), memInUse, getFlavors(cpuIdle, memIdle), null); + return new ResourcesInfo(String.valueOf(cpuIdle), cpuInUse, String.valueOf(memIdle), + memInUse, getFlavors(cpuIdle, memIdle), null); } catch (URISyntaxException e) { LOGGER.error(e); diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 45846423..78703170 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -25,8 +25,10 @@ public OCCIApplication(ManagerFacade facade) { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); + router.attach("/request/", RequestServerResource.class); router.attach("/request", RequestServerResource.class); router.attach("/request/{requestId}", RequestServerResource.class); + router.attach("/compute", ComputeServerResource.class); router.attach("/compute/", ComputeServerResource.class); router.attach("/compute/{instanceId}", ComputeServerResource.class); router.attach("/members", MemberServerResource.class); diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java index ddc49e00..6e7f68ae 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java @@ -6,7 +6,6 @@ import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.ResponseConstants; -import org.fogbowcloud.manager.occi.request.RequestServerResource; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Delete; import org.restlet.resource.Get; @@ -63,7 +62,7 @@ public String post() { protected static String generateResponse(List instances) { String response = ""; for (Instance intance : instances) { - response += HeaderUtils.X_OCCI_LOCATION + intance.toOCCIMassageFormatLocation() + "\n"; + response += intance.toOCCIMassageFormatLocation() + "\n"; } if (response.equals("")) { response = "Empty"; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 845d6528..7379e5a5 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -86,7 +86,7 @@ public String getAuthToken() { } public Map getxOCCIAtt() { - return this.xOCCIAtt; + return new HashMap(xOCCIAtt); } public String getMemberId() { diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index b5ce61a6..6a3a13da 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -67,6 +67,7 @@ public Request get(String user, String requestId) { } public List getByUser(String user) { + LOGGER.debug("Getting instances by user " + user ); List userRequests = requests.get(user); return userRequests == null ? new LinkedList() : new LinkedList(userRequests); @@ -77,6 +78,8 @@ public void removeByUser(String user) { } public void remove(String requestId) { + LOGGER.debug("Removing requestId " + requestId ); + for (List userRequests : requests.values()) { Iterator iterator = userRequests.iterator(); while (iterator.hasNext()) { From 4ff3b3e7b96e2ab294cfd8decdfb01ff730c699a Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 2 May 2014 17:08:35 -0300 Subject: [PATCH 088/185] Refatoring IdentityPlugin and ComputePlugin. Fixing Tests . Refatoring fogbow-cli. Fixing manager.conf.example. --- manager.conf.example | 3 +- .../java/org/fogbowcloud/manager/Main.java | 7 +- .../org/fogbowcloud/manager/cli/Main.java | 124 ++++++++++-------- .../manager/core/ManagerFacade.java | 32 +++-- .../manager/core/plugins/ComputePlugin.java | 3 +- .../manager/core/plugins/IdentityPlugin.java | 6 +- .../openstack/OpenStackComputePlugin.java | 25 ++-- .../openstack/OpenStackIdentityPlugin.java | 77 +++++++---- .../manager/occi/OCCIApplication.java | 7 +- .../manager/occi/TokenServerResource.java | 38 +++++- .../manager/occi/core/OCCIHeaders.java | 7 +- .../fogbowcloud/manager/occi/core/Token.java | 25 ++++ .../occi/instance/ComputeServerResource.java | 3 +- .../manager/occi/TestDeleteCompute.java | 2 +- .../manager/occi/TestOCCIApplication.java | 5 +- .../occi/plugins/TestComputeOpenStack.java | 21 +-- .../occi/plugins/TestIdentityOpenStack.java | 31 ++++- .../occi/util/KeystoneApplication.java | 29 ++-- .../manager/occi/util/PluginHelper.java | 12 +- .../manager/xmpp/TestGetRemoteInstance.java | 9 +- .../manager/xmpp/TestIAmAlive.java | 8 +- .../manager/xmpp/util/ManagerTestHelper.java | 99 +++++++------- 22 files changed, 356 insertions(+), 217 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/core/Token.java diff --git a/manager.conf.example b/manager.conf.example index f20fb164..227675a2 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -18,7 +18,6 @@ identity_openstack_url=http://localhost:5000 federation_user_name=fogbow federation_user_password=fogbow -federation_user_tenant_id=d39e3c9bba294e3d9c47b8df9e29d81e federation_user_tenant_name=demo scheduler_period=30000 @@ -26,3 +25,5 @@ scheduler_period=30000 ssh_tunnel_host=10.0.0.1 ssh_tunnel_user=fogbow ssh_tunnel_port_range=50000:59999 + +http_port = 8182 \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 3e6734e7..b8e34ad1 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -41,7 +41,8 @@ public static void main(String[] args) throws Exception { OCCIApplication application = new OCCIApplication(facade); Component http = new Component(); - http.getServers().add(Protocol.HTTP, 8182); + http.getServers().add(Protocol.HTTP, Integer + .parseInt(properties.getProperty("http_port"))); http.getDefaultHost().attach(application); http.start(); } @@ -51,6 +52,6 @@ private static Object createInstance(String propName, Properties properties) return Class.forName(properties.getProperty(propName)) .getConstructor(Properties.class).newInstance(properties); } - - + + } diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 6456eeaa..5d4324d6 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -23,9 +23,14 @@ public class Main { + private static String DEFAULT_URL = "http://localhost:8182"; + private static int DEFAULT_INTANCE_COUNT = 1; + private static String DEFAULT_FLAVOR = "fogbow-small"; + private static String DEFAULT_IMAGE = "fogbow-linux-x86"; + public static void main(String[] args) throws Exception { JCommander jc = new JCommander(); - + MemberCommand member = new MemberCommand(); jc.addCommand("member", member); RequestCommand request = new RequestCommand(); @@ -33,31 +38,30 @@ public static void main(String[] args) throws Exception { InstanceCommand instance = new InstanceCommand(); jc.addCommand("instance", instance); TokenCommand token = new TokenCommand(); - jc.addCommand("token", token); - + jc.addCommand("token", token); + jc.setProgramName("fogbow-cli"); jc.parse(args); - + String parsedCommand = jc.getParsedCommand(); - + if (parsedCommand == null) { jc.usage(); return; } - + if (parsedCommand.equals("member")) { String url = member.url; doRequest("get", url + "/members", null); } else if (parsedCommand.equals("request")) { - String url = request.url; + String url = member.url; if (request.get) { if (request.create || request.delete) { jc.usage(); return; } if (request.requestId != null) { - doRequest("get", url + "/request/" + request.requestId, - request.authToken); + doRequest("get", url + "/request/" + request.requestId, request.authToken); } else { doRequest("get", url + "/request", request.authToken); } @@ -66,31 +70,35 @@ public static void main(String[] args) throws Exception { jc.usage(); return; } - doRequest("delete", url + "/request/" + request.requestId, - request.authToken); + doRequest("delete", url + "/request/" + request.requestId, request.authToken); } else if (request.create) { if (request.delete || request.get || request.requestId != null) { jc.usage(); return; } + Set headers = new HashSet(); headers.add("Category: fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\""); - headers.add("X-OCCI-Attribute: org.fogbowcloud.request.instance-count = " + request.instanceCount); + headers.add("X-OCCI-Attribute: org.fogbowcloud.request.instance-count = " + + request.instanceCount); headers.add("X-OCCI-Attribute: org.fogbowcloud.request.type = one-time"); - headers.add("Category: " + request.flavor + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); - headers.add("Category: " + request.image + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); + headers.add("Category: " + + request.flavor + + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); + headers.add("Category: " + + request.image + + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); doRequest("post", url + "/request", request.authToken, headers); } } else if (parsedCommand.equals("instance")) { - String url = instance.url; + String url = member.url; if (instance.delete && instance.get) { jc.usage(); return; } if (instance.get) { if (instance.instanceId != null) { - doRequest("get", url + "/compute/" + instance.instanceId, - instance.authToken); + doRequest("get", url + "/compute/" + instance.instanceId, instance.authToken); } else { doRequest("get", url + "/compute/", instance.authToken); } @@ -99,27 +107,26 @@ public static void main(String[] args) throws Exception { jc.usage(); return; } - doRequest("delete", url + "/compute/" + instance.instanceId, - instance.authToken); + doRequest("delete", url + "/compute/" + instance.instanceId, instance.authToken); } } else if (parsedCommand.equals("token")) { - String url = token.url; + String url = member.url; Set headers = new HashSet(); - headers.add("password: " + token.password); - headers.add("username: " + token.username); - + headers.add(OCCIHeaders.X_TOKEN_USER + ": " + token.username); + headers.add(OCCIHeaders.X_TOKEN_PASS + ": " + token.password); + headers.add(OCCIHeaders.X_TOKEN_TENANT_NAME + ": " + token.tenantName); + doRequest("get", url + "/token", null, headers); } } - private static void doRequest(String method, String endpoint, String authToken) + private static void doRequest(String method, String endpoint, String authToken) throws URISyntaxException, HttpException, IOException { doRequest(method, endpoint, authToken, new HashSet()); } - - private static void doRequest(String method, String endpoint, String authToken, - Set additionalHeaders) - throws URISyntaxException, HttpException, IOException { + + private static void doRequest(String method, String endpoint, String authToken, + Set additionalHeaders) throws URISyntaxException, HttpException, IOException { HttpUriRequest request = null; if (method.equals("get")) { request = new HttpGet(endpoint); @@ -136,78 +143,81 @@ private static void doRequest(String method, String endpoint, String authToken, String[] splitHeader = header.split(": "); request.addHeader(splitHeader[0].trim(), splitHeader[1].trim()); } - + HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); - - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ + + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { System.out.println(EntityUtils.toString(response.getEntity())); } else { System.out.println(response.getStatusLine().toString()); } } - + private static class Command { - @Parameter(names = "--url", required = true, description = "fogbow manager url") - String url = null; + @Parameter(names = "--url", description = "fogbow manager url") + String url = Main.DEFAULT_URL; } - + private static class AuthedCommand extends Command { @Parameter(names = "--auth-token", required = true, description = "auth token") String authToken = null; } - + @Parameters(separators = "=", commandDescription = "Members operations") private static class MemberCommand extends Command { @Parameter(names = "--get", description = "List federation members") Boolean get = true; } - + @Parameters(separators = "=", commandDescription = "Request operations") private static class RequestCommand extends AuthedCommand { @Parameter(names = "--get", description = "Get request") Boolean get = false; - + @Parameter(names = "--create", description = "Create request") Boolean create = false; - + @Parameter(names = "--delete", description = "Delete request") Boolean delete = false; - + @Parameter(names = "--id", description = "Request id") String requestId = null; - + @Parameter(names = "--n", description = "Instance count") - int instanceCount = 0; - + int instanceCount = Main.DEFAULT_INTANCE_COUNT; + @Parameter(names = "--image", description = "Instance image") - String image = null; - + String image = Main.DEFAULT_IMAGE; + @Parameter(names = "--flavor", description = "Instance flavor") - String flavor = null; + String flavor = Main.DEFAULT_FLAVOR; } - + @Parameters(separators = "=", commandDescription = "Instance operations") private static class InstanceCommand extends AuthedCommand { @Parameter(names = "--get", description = "Get instance data") Boolean get = false; - + @Parameter(names = "--delete", description = "Delete instance") Boolean delete = false; - + @Parameter(names = "--id", description = "Instance id") String instanceId = null; } - + @Parameters(separators = "=", commandDescription = "Token operations") private static class TokenCommand extends Command { @Parameter(names = "--get", description = "Get token") Boolean get = false; - - @Parameter(names = "--password", description = "Password") + + @Parameter(names = "--password", required = true, description = "Password", password = true) String password = null; - - @Parameter(names = "--username", description = "Username") - String username = null; - } -} + + @Parameter(names = "--username", required = true, description = "Username") + String username = null; + + @Parameter(names = "--tenantName", required = true, description = "TenantName") + String tenantName = null; + } +} \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 19b63d18..dca3c7cb 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.core; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -20,7 +21,9 @@ import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; @@ -83,7 +86,7 @@ public void setMembers(List members) { } public ResourcesInfo getResourcesInfo() { - String token = getFederationUserToken(); + Token token = getFederationUserToken(); ResourcesInfo resourcesInfo = computePlugin.getResourcesInfo(token); resourcesInfo.setId(properties.getProperty("xmpp_jid")); return resourcesInfo; @@ -183,7 +186,8 @@ private void removeInstance(String authToken, String instanceId, Request request } request.setInstanceId(null); request.setMemberId(null); - if (request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { + if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null + && request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { request.setState(RequestState.OPEN); } } @@ -222,7 +226,7 @@ public Request getRequest(String authToken, String requestId) { public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { - String token = getFederationUserToken(); + String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); } catch (OCCIException e) { @@ -235,14 +239,20 @@ public String submitRequestForRemoteMember(List categories, // TODO Think about always get new federation user token or store a valid // one. - private String getFederationUserToken() { - String token = identityPlugin.getToken(properties.getProperty("federation_user_name"), - properties.getProperty("federation_user_password")); - return token; + private Token getFederationUserToken() { + Map tokenAttributes = new HashMap(); + String username = properties.getProperty("federation_user_name"); + String password = properties.getProperty("federation_user_password"); + String tenantName = properties.getProperty("federation_user_tenant_name"); + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, username); + tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); + + return identityPlugin.getToken(tokenAttributes); } public Instance getInstanceForRemoteMember(String instanceId) { - String token = getFederationUserToken(); + String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { @@ -254,7 +264,7 @@ public Instance getInstanceForRemoteMember(String instanceId) { } public void removeInstanceForRemoteMember(String instanceId) { - String token = getFederationUserToken(); + String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); computePlugin.removeInstance(token, instanceId); } @@ -374,7 +384,7 @@ public void setRequests(RequestRepository requests) { this.requests = requests; } - public String getToken(String username, String password) { - return identityPlugin.getToken(username, password); + public Token getToken(Map attributesToken) { + return identityPlugin.getToken(attributesToken); } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java index e4da1550..28a3f4ff 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/ComputePlugin.java @@ -5,6 +5,7 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; public interface ComputePlugin { @@ -19,5 +20,5 @@ public interface ComputePlugin { public void removeInstances(String authToken); - public ResourcesInfo getResourcesInfo(String authToken); + public ResourcesInfo getResourcesInfo(Token token); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index 34527985..22e6ec92 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -1,8 +1,12 @@ package org.fogbowcloud.manager.core.plugins; +import java.util.Map; + +import org.fogbowcloud.manager.occi.core.Token; + public interface IdentityPlugin { public String getUser(String token); - public String getToken(String username, String password); + public Token getToken(Map tokenAttributes); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 804b6d67..2c492e7e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -28,6 +28,7 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.json.JSONException; @@ -45,7 +46,6 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String TERM_COMPUTE = "compute"; private static final String CLASS_COMPUTE = "kind"; private static final String COMPUTE_ENDPOINT = "/compute/"; - private final String federationTenantId; private final String COMPUTE_V2_API_ENDPOINT = "/v2/"; private static final String MAX_TOTAL_CORES_ATT = "maxTotalCores"; @@ -54,15 +54,14 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String TOTAL_RAM_USED_ATT = "totalRAMUsed"; private String computeOCCIEndpoint; - private String computeV2APIEndepoint; + private String computeV2APIEndpoint; private Map fogTermToOpensStackCategory = new HashMap(); public OpenStackComputePlugin(Properties properties) { this.computeOCCIEndpoint = properties.getProperty("compute_openstack_occi_url") + COMPUTE_ENDPOINT; - this.computeV2APIEndepoint = properties.getProperty("compute_openstack_v2api_url") + this.computeV2APIEndpoint = properties.getProperty("compute_openstack_v2api_url") + COMPUTE_V2_API_ENDPOINT; - this.federationTenantId = properties.getProperty("federation_user_tenant_id"); fogTermToOpensStackCategory.put(RequestConstants.SMALL_TERM, createFlavorCategory("compute_openstack_flavor_small", properties)); @@ -104,7 +103,6 @@ public String requestInstance(String authToken, List categories, xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(DefaultSSHTunnel.USER_DATA_ATT)); - xOCCIAtt.remove(DefaultSSHTunnel.SSH_ADDRESS_ATT); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost; @@ -127,8 +125,8 @@ public String requestInstance(String authToken, List categories, throw new OCCIException(ErrorType.NOT_FOUND, EntityUtils.toString( response.getEntity(), String.valueOf(Charsets.UTF_8))); } - String instanceLocation = response.getFirstHeader("Location").getValue(); - return getInstanceId(instanceLocation); + + return response.getFirstHeader("Location").getValue(); } catch (URISyntaxException e) { LOGGER.error(e); } catch (HttpException e) { @@ -139,12 +137,6 @@ public String requestInstance(String authToken, List categories, return null; } - private String getInstanceId(String instanceLocation) { - // location format: OCCI_URL + COMPUTE_ENDPOINT + instanceID - String[] tokens = instanceLocation.split(COMPUTE_ENDPOINT); - return tokens[1]; - } - public Instance getInstance(String authToken, String instanceId) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; @@ -259,12 +251,13 @@ public void removeInstance(String authToken, String instanceId) { } @Override - public ResourcesInfo getResourcesInfo(String authToken) { + public ResourcesInfo getResourcesInfo(Token token) { HttpClient httpCLient = new DefaultHttpClient(); HttpGet httpGet; try { - httpGet = new HttpGet(computeV2APIEndepoint + federationTenantId + "/limits"); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + httpGet = new HttpGet(computeV2APIEndpoint + + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + "/limits"); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, token.get(OCCIHeaders.X_TOKEN)); HttpResponse response = httpCLient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 2fc1ca81..b4fbee9b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -1,8 +1,13 @@ package org.fogbowcloud.manager.core.plugins.openstack; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import org.apache.commons.codec.Charsets; +import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; @@ -17,18 +22,20 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.json.JSONException; import org.json.JSONObject; public class OpenStackIdentityPlugin implements IdentityPlugin { - private static final String TENANT_NAME = "tenantName"; - public static final String USERNAME_KEYSTONE = "username"; - public static final String PASSWORD_KEYSTONE = "password"; - public static final String PASSWORD_CREDENTIALS_KEYSTONE = "passwordCredentials"; + private static final String KEYSTONE_TENANT_NAME = "tenantName"; + public static final String KEYSTONE_USERNAME = "username"; + public static final String KEYSTONE_PASSWORD = "password"; + public static final String PASSWORD_CREDENTIALS = "passwordCredentials"; public static final String AUTH_KEYSTONE = "auth"; public static final String TOKEN_KEYSTONE = "token"; public static final String ID_KEYSTONE = "id"; + public static final String TENANT_KEYSTONE = "tenant"; public static final String ACCESS_KEYSTONE = "access"; public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; @@ -38,11 +45,9 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { private String v2Endpoint; private String v3Endpoint; - private String federationTenantName; public OpenStackIdentityPlugin(Properties properties) { String keystoneUrl = properties.getProperty("identity_openstack_url"); - this.federationTenantName = properties.getProperty("federation_user_tenant_name"); this.v3Endpoint = keystoneUrl + V3_ENDPOINT_PATH; this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } @@ -61,17 +66,21 @@ public String getUser(String authToken) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } - + String responseStr = EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); return getUserNameUserFromJson(responseStr); - } catch (Exception e) { + } catch (IOException e) { + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } catch (URISyntaxException e){ + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } catch (HttpException e){ throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } } @Override - public String getToken(String username, String password) { + public Token getToken(Map tokenAttributes) { try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(this.v2Endpoint); @@ -80,27 +89,34 @@ public String getToken(String username, String password) { httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); JSONObject passwordCredentials = new JSONObject(); - passwordCredentials.put(USERNAME_KEYSTONE, username); - passwordCredentials.put(PASSWORD_KEYSTONE, password); + passwordCredentials.put(KEYSTONE_USERNAME, + tokenAttributes.get(OCCIHeaders.X_TOKEN_USER)); + passwordCredentials.put(KEYSTONE_PASSWORD, + tokenAttributes.get(OCCIHeaders.X_TOKEN_PASS)); JSONObject auth = new JSONObject(); - auth.put(PASSWORD_CREDENTIALS_KEYSTONE, passwordCredentials); - auth.put(TENANT_NAME, this.federationTenantName); + auth.put(KEYSTONE_TENANT_NAME, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); + auth.put(PASSWORD_CREDENTIALS, passwordCredentials); JSONObject root = new JSONObject(); root.put(AUTH_KEYSTONE, auth); httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); - HttpResponse response = httpClient.execute(httpPost); - String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); - + + String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } - + return getTokenFromJson(responseStr); - } catch (Exception e) { - e.printStackTrace(); + } catch (IOException e) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } + } catch (URISyntaxException e){ + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } catch (HttpException e){ + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } catch (JSONException e) { + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } } private String getUserNameUserFromJson(String responseStr) { @@ -113,15 +129,18 @@ private String getUserNameUserFromJson(String responseStr) { } } - private String getTokenFromJson(String responseStr) { - try { - JSONObject root = new JSONObject(responseStr); - return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) - .getString(ID_KEYSTONE); - } catch (JSONException e) { - e.printStackTrace(); - return null; - } + private Token getTokenFromJson(String responseStr) throws JSONException { + Map attributes = new HashMap(); + JSONObject root = new JSONObject(responseStr); + JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE); + String token = tokenKeyStone.getString(ID_KEYSTONE); + String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE) + .getString(ID_KEYSTONE); + + attributes.put(OCCIHeaders.X_TOKEN, token); + attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); + + return new Token(attributes); } public void setEnd(String end) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 78703170..17faf6bb 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -6,6 +6,7 @@ import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.ComputeServerResource; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.Request; @@ -25,8 +26,8 @@ public OCCIApplication(ManagerFacade facade) { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); - router.attach("/request/", RequestServerResource.class); router.attach("/request", RequestServerResource.class); + router.attach("/request/", RequestServerResource.class); router.attach("/request/{requestId}", RequestServerResource.class); router.attach("/compute", ComputeServerResource.class); router.attach("/compute/", ComputeServerResource.class); @@ -36,8 +37,8 @@ public Restlet createInboundRoot() { return router; } - public String getToken(String username, String password) { - return managerFacade.getToken(username, password); + public Token getToken(Map attributesToken) { + return managerFacade.getToken(attributesToken); } public List getFederationMembers() { diff --git a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java index c1211e59..c2fec0ea 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java @@ -1,21 +1,45 @@ package org.fogbowcloud.manager.occi; -import org.restlet.engine.adapter.HttpRequest; +import java.util.HashMap; +import java.util.Map; + import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; +import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Get; import org.restlet.resource.ServerResource; public class TokenServerResource extends ServerResource { - + @Get public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); HeaderUtils.checkOCCIContentType(req.getHeaders()); + + String username = req.getHeaders().getValues(OCCIHeaders.X_TOKEN_USER); + String password = req.getHeaders().getValues(OCCIHeaders.X_TOKEN_PASS); + String tanantName = req.getHeaders().getValues(OCCIHeaders.X_TOKEN_TENANT_NAME); + + Map attributesToken = new HashMap(); + attributesToken.put(OCCIHeaders.X_TOKEN_USER, username); + attributesToken.put(OCCIHeaders.X_TOKEN_PASS, password); + attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tanantName); + + return generateResponse(application.getToken(attributesToken)); + } + + public String generateResponse(Token token) { + if(token == null || token.getAttributes().size() == 0) { + return new String(); + } - String username = req.getHeaders().getValues("username"); - String password = req.getHeaders().getValues("password"); - - return application.getToken(username, password); - } + Map tokenAttributes = token.getAttributes(); + String tokenId = tokenAttributes.get(OCCIHeaders.X_TOKEN); + String tenantId = tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_ID); + + return OCCIHeaders.X_TOKEN + ":" + tokenId + "\n" + OCCIHeaders.X_TOKEN_TENANT_ID + ":" + + tenantId; + } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java index f1abbbc7..f44ef291 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java @@ -6,7 +6,12 @@ public class OCCIHeaders { public static final String CONTENT_TYPE = "Content-Type"; public static final String X_AUTH_TOKEN = "X-Auth-Token"; public static final String X_SUBJECT_TOKEN = "X-Subject-Token"; - + public static final String X_TOKEN_USER = "X-Token-User"; + public static final String X_TOKEN_PASS = "X-Token-Pass"; + public static final String X_TOKEN_TENANT_NAME = "X-Token-Tenant-Name"; + public static final String X_TOKEN_TENANT_ID = "X-Token-Tenant-Id"; + public static final String X_TOKEN = "X-Token"; + // occi constants public static final String CATEGORY = "Category"; public static final String X_OCCI_ATTRIBUTE = "X-OCCI-Attribute"; diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java new file mode 100644 index 00000000..15c70c79 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -0,0 +1,25 @@ +package org.fogbowcloud.manager.occi.core; + +import java.util.Map; + +public class Token { + + private Map attributes; + + public Token(Map attributes) { + this.attributes = attributes; + } + + public String get(String attributeName) { + try { + return attributes.get(attributeName); + } catch (Exception e) { + return null; + } + + } + + public Map getAttributes() { + return attributes; + } +} diff --git a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java index 6e7f68ae..19295f70 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/instance/ComputeServerResource.java @@ -41,7 +41,6 @@ public String remove() { HeaderUtils.checkOCCIContentType(req.getHeaders()); String authToken = HeaderUtils.getAuthToken(req.getHeaders()); String instanceId = (String) getRequestAttributes().get("instanceId"); - if (instanceId == null) { LOGGER.info("Removing all instances of token :" + authToken); application.removeInstances(authToken); @@ -51,7 +50,7 @@ public String remove() { LOGGER.info("Removing instance " + instanceId); application.removeInstance(authToken, instanceId); - return ResponseConstants.OK; + return ResponseConstants.OK; } @Post diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 56b9553d..31c6c9a9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -59,7 +59,7 @@ public void tearDown() throws Exception { @Test public void testDelete() throws Exception { - HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + ""); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 74dd6798..ed8f86a9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -30,9 +30,8 @@ public class TestOCCIApplication { private static final String INSTANCE_LOCATION = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" +OCCITestHelper.ENDPOINT_PORT + ComputeApplication.TARGET - + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - private static final String INSTANCE_ID = INSTANCE_LOCATION.replace( - HeaderUtils.X_OCCI_LOCATION, "").trim(); + + "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + private static final String INSTANCE_ID = INSTANCE_LOCATION; private static final Long SCHEDULER_PERIOD = 500L; private OCCIApplication occiApplication; diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 4b6049e3..339e8d71 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -30,7 +30,8 @@ public class TestComputeOpenStack { private static final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; private static final String URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; - + private static final String PREFIX_INSTANCE = "http://localhost:8182/compute/"; + private OpenStackComputePlugin computeOpenStack; private PluginHelper pluginHelper; List expectedInstanceIds; @@ -71,7 +72,7 @@ public void testRequestAValidInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, + Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -119,7 +120,7 @@ public void testRequestWithoutSizeCateory() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, + Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -191,7 +192,7 @@ public void testSupportedOCCIAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); - Assert.assertEquals(FIRST_INSTANCE_ID, + Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, @@ -212,7 +213,7 @@ public void testMoreSupportedOCCIAtts() { xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); xOCCIAtt.put("occi.compute.state", "inactive"); - Assert.assertEquals(FIRST_INSTANCE_ID, + Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, @@ -233,7 +234,7 @@ public void testGetAllInstanceIds() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, + Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -257,7 +258,7 @@ public void testGetAllManyInstanceIds() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(instanceId, computeOpenStack + Assert.assertEquals(PREFIX_INSTANCE + instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -292,7 +293,7 @@ public void testGetInstanceDetails() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, + Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -337,7 +338,7 @@ public void testDeleteAllManyInstances() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(instanceId, computeOpenStack + Assert.assertEquals(PREFIX_INSTANCE + instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -365,7 +366,7 @@ public void testDeleteOneInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(instanceId, computeOpenStack + Assert.assertEquals(PREFIX_INSTANCE + instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index c54fad40..d0b10a7a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -1,8 +1,13 @@ package org.fogbowcloud.manager.occi.plugins; +import java.util.HashMap; +import java.util.Map; import java.util.Properties; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.PluginHelper; import org.junit.After; import org.junit.Assert; @@ -54,18 +59,30 @@ public void testGetNameUserFromTokenInvalid() { @Test public void testGetToken() { - String token = this.identityOpenStack.getToken(PluginHelper.USERNAME_FOGBOW, - PluginHelper.PASSWORD_FOGBOW); - Assert.assertEquals(PluginHelper.AUTH_TOKEN, token); + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, "admin"); + Token token = this.identityOpenStack.getToken(tokenAttributes); + String authToken = token.get(OCCIHeaders.X_TOKEN); + Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); } - @Test(expected = ResourceException.class) + @Test(expected = OCCIException.class) public void testGetTokenWrongUsername() { - this.identityOpenStack.getToken("wrong", PluginHelper.USERNAME_FOGBOW); + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, "wrong"); + tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); + this.identityOpenStack.getToken(tokenAttributes); } - @Test(expected = ResourceException.class) + @Test(expected = OCCIException.class) public void testGetTokenWrongPassword() { - this.identityOpenStack.getToken(PluginHelper.PASSWORD_FOGBOW, "wrong"); + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, "worng"); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); + this.identityOpenStack.getToken(tokenAttributes); } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index ae0cb3a9..7732320f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -7,6 +7,7 @@ import org.apache.http.HttpStatus; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Application; @@ -30,13 +31,13 @@ public class KeystoneApplication extends Application { private String usernameAdmin; private String passwordAdmin; - private String defaultToken; + private Token defaultToken; public KeystoneApplication() { this.tokenToUser = new HashMap(); } - public KeystoneApplication(String usernameAdmin, String passwordAdmin, String defaultToken) { + public KeystoneApplication(String usernameAdmin, String passwordAdmin, Token defaultToken) { this.tokenToUser = new HashMap(); this.usernameAdmin = usernameAdmin; this.passwordAdmin = passwordAdmin; @@ -72,7 +73,7 @@ public void authenticationCheck(String username, String password) { } } - public String getDefaultToken() { + public Token getDefaultToken() { return this.defaultToken; } @@ -99,22 +100,28 @@ public Representation post(Representation entity) { } String username = getUserFeatureCredentials(jsonCredentials, - OpenStackIdentityPlugin.USERNAME_KEYSTONE); + OpenStackIdentityPlugin.KEYSTONE_USERNAME); String password = getUserFeatureCredentials(jsonCredentials, - OpenStackIdentityPlugin.PASSWORD_KEYSTONE); + OpenStackIdentityPlugin.KEYSTONE_PASSWORD); + keyStoneApplication.authenticationCheck(username, password); return new StringRepresentation( mountJSONResponseAuthenticateToken(keyStoneApplication.getDefaultToken()), - MediaType.TEXT_ALL); + MediaType.TEXT_ALL); } - private String mountJSONResponseAuthenticateToken(String token) { + private String mountJSONResponseAuthenticateToken(Token token) { try { - JSONObject rootIdTOken = new JSONObject(); - rootIdTOken.put(OpenStackIdentityPlugin.ID_KEYSTONE, token); + String tokenId = token.get(OCCIHeaders.X_TOKEN); + String tenantId = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); + JSONObject rootIdTenantToken = new JSONObject(); + rootIdTenantToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tenantId); + JSONObject rootIdToken = new JSONObject(); + rootIdToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tokenId); + rootIdToken.put(OpenStackIdentityPlugin.TENANT_KEYSTONE, rootIdTenantToken); JSONObject rootToken = new JSONObject(); - rootToken.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdTOken); + rootToken.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdToken); JSONObject rootAccess = new JSONObject(); rootAccess.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, rootToken); return rootAccess.toString(); @@ -128,7 +135,7 @@ private String getUserFeatureCredentials(String jsonCredentials, String feature) try { JSONObject root = new JSONObject(jsonCredentials); return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) - .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS_KEYSTONE) + .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS) .getString(feature).toString(); } catch (JSONException e) { return null; diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index a1ed4a2f..f6f2cfb4 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -1,7 +1,11 @@ package org.fogbowcloud.manager.occi.util; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; import org.mockito.Mockito; import org.restlet.Component; @@ -12,6 +16,7 @@ public class PluginHelper { private Component component; public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; + public static final String TENANT_ID = "TEnAHDH49U"; public static final String USERNAME_FOGBOW = "admin"; public static final String PASSWORD_FOGBOW = "reverse"; @@ -25,8 +30,13 @@ public void initializeKeystoneComponent() throws Exception { this.component = new Component(); this.component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN, AUTH_TOKEN); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); + Token token = new Token(tokenAttributes); + KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW, - AUTH_TOKEN); + token); keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); this.component.getDefaultHost().attach(keystoneApplication); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 511d7188..25dcf5ad 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -78,8 +78,13 @@ public void testGetRemoteInstance() throws Exception { request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); - Instance remoteInstance = ManagerPacketHelper.getRemoteInstance(request, - managerTestHelper.createPacketSender()); + Instance remoteInstance = null; + try { + remoteInstance = ManagerPacketHelper.getRemoteInstance(request, + managerTestHelper.createPacketSender()); + } catch (Exception e) { + e.printStackTrace(); + } Assert.assertEquals(instance.getId(), remoteInstance.getId()); Assert.assertEquals(instance.getAttributes(), remoteInstance.getAttributes()); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 9c46eeba..3cf76c66 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -65,8 +65,12 @@ public boolean accept(Packet packet) { .equals(ManagerTestHelper.MANAGER_COMPONENT_URL); } }, callback); - - managerXmppComponent.iAmAlive(); + + try { + managerXmppComponent.iAmAlive(); + } catch (Exception e) { + e.printStackTrace(); + } Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); Element element = packet.getElement().element("query"); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 4023c830..8c3e9397 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -4,9 +4,11 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Properties; import org.dom4j.Attribute; @@ -18,6 +20,8 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; import org.jamppa.client.plugin.xep0077.XEP0077; @@ -39,7 +43,7 @@ public class ManagerTestHelper { private static final String CLIENT_ADRESS = "client@test.com"; private static final String CLIENT_PASS = "password"; private static final String SMACK_ENDING = "/Smack"; - private static final String TOKEN = "token"; + private static final Token TOKEN = new Token(new HashMap()); public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String MANAGER_COMPONENT_PASS = "password"; @@ -53,46 +57,47 @@ public class ManagerTestHelper { private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; + private Token tokenDefault; - public ResourcesInfo getResources() throws CertificateException, - IOException { + public ManagerTestHelper() { + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN, "token"); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); + this.tokenDefault = new Token(tokenAttributes); + } + + public ResourcesInfo getResources() throws CertificateException, IOException { List flavours = new LinkedList(); flavours.add(new Flavor("small", "cpu", "mem", 2)); flavours.add(new Flavor("small", "cpu", "mem", 3)); - ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", - "value3", "value4", flavours, getCertificate()); + ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", "value3", "value4", + flavours, getCertificate()); return resources; } - public IQ createWhoIsAliveResponse(ArrayList aliveIds, - IQ iq) throws CertificateException, IOException { + public IQ createWhoIsAliveResponse(ArrayList aliveIds, IQ iq) + throws CertificateException, IOException { IQ resultIQ = IQ.createResultIQ(iq); - Element queryElement = resultIQ.getElement().addElement("query", - WHOISALIVE_NAMESPACE); + Element queryElement = resultIQ.getElement().addElement("query", WHOISALIVE_NAMESPACE); for (FederationMember rendezvousItem : aliveIds) { Element itemEl = queryElement.addElement("item"); itemEl.addAttribute("id", rendezvousItem.getResourcesInfo().getId()); - itemEl.addElement("cert").setText( - CertificateHandlerHelper.convertToSendingFormat()); + itemEl.addElement("cert").setText(CertificateHandlerHelper.convertToSendingFormat()); Element statusEl = itemEl.addElement("status"); - statusEl.addElement("cpu-idle").setText( - rendezvousItem.getResourcesInfo().getCpuIdle()); + statusEl.addElement("cpu-idle").setText(rendezvousItem.getResourcesInfo().getCpuIdle()); statusEl.addElement("cpu-inuse").setText( rendezvousItem.getResourcesInfo().getCpuInUse()); - statusEl.addElement("mem-idle").setText( - rendezvousItem.getResourcesInfo().getMemIdle()); + statusEl.addElement("mem-idle").setText(rendezvousItem.getResourcesInfo().getMemIdle()); statusEl.addElement("mem-inuse").setText( rendezvousItem.getResourcesInfo().getMemInUse()); - List flavours = rendezvousItem.getResourcesInfo() - .getFlavours(); + List flavours = rendezvousItem.getResourcesInfo().getFlavours(); for (Flavor f : flavours) { Element flavorElement = statusEl.addElement("flavor"); flavorElement.addElement("name").setText(f.getName()); flavorElement.addElement("cpu").setText(f.getCpu()); flavorElement.addElement("mem").setText(f.getMem()); - flavorElement.addElement("capacity").setText( - f.getCapacity().toString()); + flavorElement.addElement("capacity").setText(f.getCapacity().toString()); } statusEl.addElement("cert"); statusEl.addElement("updated").setText( @@ -103,8 +108,8 @@ public IQ createWhoIsAliveResponse(ArrayList aliveIds, public XMPPClient createXMPPClient() throws XMPPException { - XMPPClient xmppClient = new XMPPClient(CLIENT_ADRESS, CLIENT_PASS, - SERVER_HOST, SERVER_CLIENT_PORT); + XMPPClient xmppClient = new XMPPClient(CLIENT_ADRESS, CLIENT_PASS, SERVER_HOST, + SERVER_CLIENT_PORT); XEP0077 register = new XEP0077(); xmppClient.registerPlugin(register); xmppClient.connect(); @@ -125,8 +130,8 @@ public PacketSender createPacketSender() throws XMPPException { @Override public Packet syncSendPacket(Packet packet) { PacketFilter responseFilter = new PacketIDFilter(packet.getID()); - PacketCollector response = xmppClient.getConnection() - .createPacketCollector(responseFilter); + PacketCollector response = xmppClient.getConnection().createPacketCollector( + responseFilter); xmppClient.getConnection().sendPacket(packet); Packet result = response.nextResult(5000); response.cancel(); @@ -149,8 +154,7 @@ public IdentityPlugin getIdentityPlugin() { return identityPlugin; } - public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) - throws Exception { + public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Exception { this.computePlugin = Mockito.mock(ComputePlugin.class); this.identityPlugin = Mockito.mock(IdentityPlugin.class); @@ -158,6 +162,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) Properties properties = new Properties(); properties.put("federation_user_name", "fogbow"); properties.put("federation_user_password", "fogbow"); + properties.put("federation_user_tenant_name", "fogbow"); properties.put("xmpp_jid", "manager.test.com"); ManagerFacade managerFacade = new ManagerFacade(properties); @@ -165,12 +170,12 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) managerFacade.setIdentityPlugin(identityPlugin); managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, - MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, - managerFacade); - Mockito.when(computePlugin.getResourcesInfo(TOKEN)).thenReturn( + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); + + Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); - Mockito.when(identityPlugin.getToken("fogbow", "fogbow")).thenReturn( - TOKEN); + + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(tokenDefault); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -183,8 +188,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) return managerXmppComponent; } - public ManagerXmppComponent initializeLocalXMPPManagerComponent() - throws Exception { + public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Exception { this.computePlugin = Mockito.mock(ComputePlugin.class); this.identityPlugin = Mockito.mock(IdentityPlugin.class); @@ -199,12 +203,12 @@ public ManagerXmppComponent initializeLocalXMPPManagerComponent() managerFacade.setIdentityPlugin(identityPlugin); managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, - MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, - managerFacade); - Mockito.when(computePlugin.getResourcesInfo(TOKEN)).thenReturn( + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); + + Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); - Mockito.when(identityPlugin.getToken("fogbow", "fogbow")).thenReturn( - TOKEN); + + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(tokenDefault); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -224,7 +228,8 @@ public void shutdown() throws ComponentException { } @SuppressWarnings("unchecked") - public List getItemsFromIQ(Packet response) throws CertificateException, IOException { + public List getItemsFromIQ(Packet response) throws CertificateException, + IOException { Element queryElement = response.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); ArrayList aliveItems = new ArrayList(); @@ -233,35 +238,33 @@ public List getItemsFromIQ(Packet response) throws Certificate Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); Element statusEl = itemEl.element("status"); - Certificate cert = CertificateHandlerHelper.convertToCertificateFormat(itemEl.element("cert").getText()); - String cpuIdle = statusEl.element("cpu-idle").getText(); + Certificate cert = CertificateHandlerHelper.convertToCertificateFormat(itemEl.element( + "cert").getText()); + String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); List flavoursList = new LinkedList(); - Iterator flavourIterator = itemEl - .elementIterator("flavor"); + Iterator flavourIterator = itemEl.elementIterator("flavor"); while (flavourIterator.hasNext()) { Element flavour = (Element) itemIterator.next(); String name = flavour.element("name").getText(); String cpu = flavour.element("cpu").getText(); String mem = flavour.element("mem").getText(); - int capacity = Integer.parseInt(flavour.element("capacity") - .getText()); + int capacity = Integer.parseInt(flavour.element("capacity").getText()); Flavor flavor = new Flavor(name, cpu, mem, capacity); flavoursList.add(flavor); } - ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse, flavoursList, cert); + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, cpuInUse, memIdle, + memInUse, flavoursList, cert); FederationMember item = new FederationMember(resources); aliveItems.add(item); } return aliveItems; } - public Certificate getCertificate() throws CertificateException, - IOException { + public Certificate getCertificate() throws CertificateException, IOException { return CertificateHandlerHelper.getCertificate(); } From 1810cd540aa6de1ed9eddb42f7cb3b37ee51a500 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Fri, 2 May 2014 17:10:28 -0300 Subject: [PATCH 089/185] Refactoring certificate handling part --- .../core/CertificateHandlerHelper.java | 89 ++++++++++++++----- .../manager/xmpp/ManagerPacketHelper.java | 39 ++++++-- .../core/TestCertificateOperations.java | 49 +++++++++- .../manager/xmpp/util/ManagerTestHelper.java | 31 +++++-- src/test/resources/manager.conf.invalidConf2 | 1 + src/test/resources/manager.conf.invalidConf3 | 1 + src/test/resources/manager.conf.invalidTest | 1 + src/test/resources/server1.crt | 0 8 files changed, 172 insertions(+), 39 deletions(-) create mode 100644 src/test/resources/manager.conf.invalidConf2 create mode 100644 src/test/resources/manager.conf.invalidConf3 create mode 100644 src/test/resources/manager.conf.invalidTest create mode 100644 src/test/resources/server1.crt diff --git a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java index 61df180f..438a63a4 100644 --- a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java +++ b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java @@ -2,6 +2,7 @@ import java.io.ByteArrayInputStream; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.security.cert.Certificate; @@ -9,43 +10,85 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Properties; +import java.util.logging.Logger; import org.apache.commons.codec.binary.Base64; +import org.restlet.engine.log.LoggerFacade; public class CertificateHandlerHelper { private static final String CERTIFICATE_KEY = "certificate"; - private final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; + private final static Logger LOGGER = Logger + .getLogger(CertificateHandlerHelper.class.getName()); - public static String convertToSendingFormat() throws CertificateException, - IOException { - Certificate cert = getCertificate(); - byte[] base64Certificate = Base64.encodeBase64(cert.getEncoded()); + public static String getBase64Certificate(Properties properties) + throws CertificateException, IOException { + Certificate cert = getCertificate(properties); + byte[] base64Certificate; + try { + base64Certificate = Base64.encodeBase64(cert.getEncoded()); + } catch (NullPointerException n) { + return null; + } return new String(base64Certificate); } - public static Certificate getCertificate() throws IOException, - CertificateException { - Properties properties = new Properties(); - FileInputStream input = new FileInputStream(CONFIG_PATH); - properties.load(input); + public static Certificate getCertificate(Properties properties) + throws CertificateException { String path = properties.getProperty(CERTIFICATE_KEY); - - final CertificateFactory certFactory = CertificateFactory - .getInstance("X.509"); - input = new FileInputStream(path); - final Certificate cert = (Certificate) certFactory - .generateCertificate(new FileInputStream(path)); - input.close(); + if (path == null || path.isEmpty()) { + LOGGER.warning("Empty Path."); + return null; + } + CertificateFactory certFactory; + certFactory = CertificateFactory.getInstance("X.509"); + FileInputStream input = null; + try { + input = new FileInputStream(path); + } catch (FileNotFoundException e1) { + LOGGER.warning("File does not Exist." + e1); + return null; + } + Certificate cert = null; + try { + try { + cert = (Certificate) certFactory + .generateCertificate(new FileInputStream(path)); + } catch (FileNotFoundException e) { + LOGGER.warning("Wring Path, File does not Exist." + e); + return null; + } + } catch (CertificateException e) { + LOGGER.warning("Certificate does not Exist" + e); + return null; + } + finally { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } return cert; } - - public static Certificate convertToCertificateFormat( - String base64StringCertificate) throws CertificateException { - byte[] base64BytesCertificate = base64StringCertificate.getBytes(); - CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); + + public static Certificate parseCertificate(String base64StringCertificate) + throws CertificateException { + byte[] base64BytesCertificate; + try { + base64BytesCertificate = base64StringCertificate.getBytes(); + } catch (NullPointerException n) { + return null; + } + CertificateFactory certFactory = CertificateFactory + .getInstance("X.509"); byte[] certificateBytes = Base64.decodeBase64(base64BytesCertificate); InputStream in = new ByteArrayInputStream(certificateBytes); - X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in); + X509Certificate cert = null; + try { + cert = (X509Certificate) certFactory.generateCertificate(in); + } catch (CertificateException e) { + LOGGER.warning("Certificate can not be generated."); + } return cert; } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 1a0c17f6..15f064ba 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.xmpp; +import java.io.FileInputStream; import java.io.IOException; import java.security.cert.Certificate; import java.security.cert.CertificateException; @@ -10,6 +11,8 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.logging.Logger; +import java.util.Properties; import org.apache.http.HttpStatus; import org.dom4j.Attribute; @@ -26,6 +29,7 @@ import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.jamppa.component.PacketSender; import org.xmpp.packet.IQ; import org.xmpp.packet.IQ.Type; @@ -33,17 +37,29 @@ import org.xmpp.packet.PacketError.Condition; public class ManagerPacketHelper { - + + private final static Logger LOGGER = Logger + .getLogger(ManagerPacketHelper.class.getName()); + public static void iAmAlive(ResourcesInfo resourcesInfo, String rendezvousAddress, PacketSender packetSender) - throws CertificateException, IOException { + throws IOException { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); Element statusEl = iq.getElement() .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE) .addElement("status"); - iq.getElement().element("query").addElement("cert") - .setText(CertificateHandlerHelper.convertToSendingFormat()); + + try { + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(ManagerTestHelper.CONFIG_PATH); + properties.load(input); + iq.getElement().element("query").addElement("cert") + .setText(CertificateHandlerHelper.getBase64Certificate(properties)); + } catch (CertificateException e) { + LOGGER.warning("Certificate does not Exist"); + } + statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); @@ -73,7 +89,7 @@ public static List whoIsalive(String rendezvousAddress, @SuppressWarnings("unchecked") private static ArrayList getMembersFromIQ( - IQ responseFromWhoIsAliveIQ) throws CertificateException { + IQ responseFromWhoIsAliveIQ) { Element queryElement = responseFromWhoIsAliveIQ.getElement().element( "query"); Iterator itemIterator = queryElement.elementIterator("item"); @@ -82,9 +98,16 @@ private static ArrayList getMembersFromIQ( while (itemIterator.hasNext()) { Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); - Certificate cert = CertificateHandlerHelper - .convertToCertificateFormat(itemEl.element("cert") - .getText()); + Certificate cert = null; + + try { + cert = CertificateHandlerHelper + .parseCertificate(itemEl.element("cert") + .getText()); + } catch (CertificateException e) { + LOGGER.warning("Certificate can not be Parsed."); + } + Element statusEl = itemEl.element("status"); String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java index 875d4ab1..20aec005 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java @@ -4,6 +4,7 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Test; @@ -11,10 +12,52 @@ public class TestCertificateOperations { @Test public void testGetCertificate() throws IOException, CertificateException { - Certificate cert = CertificateHandlerHelper.getCertificate(); + ManagerTestHelper helper = new ManagerTestHelper(); + Certificate cert = CertificateHandlerHelper.getCertificate(helper + .getProperties()); Certificate result = CertificateHandlerHelper - .convertToCertificateFormat(CertificateHandlerHelper - .convertToSendingFormat()); + .parseCertificate(CertificateHandlerHelper + .getBase64Certificate(helper.getProperties())); Assert.assertEquals(cert, result); } + + @Test + public void testEmptyCertificatePath() throws CertificateException, IOException { + String configPath = "src/test/resources/manager.conf.invalidTest"; + ManagerTestHelper helper = new ManagerTestHelper(); + Certificate cert = CertificateHandlerHelper.getCertificate(helper + .getProperties(configPath)); + Assert.assertEquals(null, cert); + Certificate result = CertificateHandlerHelper + .parseCertificate(CertificateHandlerHelper + .getBase64Certificate(helper.getProperties(configPath))); + Assert.assertEquals(null, result); + } + + @Test + public void testWrongCertificatepath() throws CertificateException, IOException { + String configPath = "src/test/resources/manager.conf.invalidConf2"; + ManagerTestHelper helper = new ManagerTestHelper(); + Certificate cert = CertificateHandlerHelper.getCertificate(helper + .getProperties(configPath)); + Assert.assertEquals(null, cert); + Certificate result = CertificateHandlerHelper + .parseCertificate(CertificateHandlerHelper + .getBase64Certificate(helper.getProperties(configPath))); + Assert.assertEquals(null, result); + } + + @Test + public void testaNotACertificateFile() throws CertificateException, IOException { + String configPath = "src/test/resources/manager.conf.invalidConf3"; + ManagerTestHelper helper = new ManagerTestHelper(); + Certificate cert = CertificateHandlerHelper.getCertificate(helper + .getProperties(configPath)); + Assert.assertEquals(null, cert); + Certificate result = CertificateHandlerHelper + .parseCertificate(CertificateHandlerHelper + .getBase64Certificate(helper.getProperties(configPath))); + Assert.assertEquals(null, result); + } + } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 4023c830..58f67c54 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -1,5 +1,7 @@ package org.fogbowcloud.manager.xmpp.util; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; import java.security.cert.Certificate; import java.security.cert.CertificateException; @@ -50,6 +52,8 @@ public class ManagerTestHelper { public static final int TEST_DEFAULT_TIMEOUT = 10000; public static final int TIMEOUT_GRACE = 500; + public final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; + private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; @@ -72,8 +76,9 @@ public IQ createWhoIsAliveResponse(ArrayList aliveIds, for (FederationMember rendezvousItem : aliveIds) { Element itemEl = queryElement.addElement("item"); itemEl.addAttribute("id", rendezvousItem.getResourcesInfo().getId()); + // exception too itemEl.addElement("cert").setText( - CertificateHandlerHelper.convertToSendingFormat()); + CertificateHandlerHelper.getBase64Certificate(getProperties())); Element statusEl = itemEl.addElement("status"); statusEl.addElement("cpu-idle").setText( rendezvousItem.getResourcesInfo().getCpuIdle()); @@ -224,7 +229,8 @@ public void shutdown() throws ComponentException { } @SuppressWarnings("unchecked") - public List getItemsFromIQ(Packet response) throws CertificateException, IOException { + public List getItemsFromIQ(Packet response) + throws CertificateException, IOException { Element queryElement = response.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); ArrayList aliveItems = new ArrayList(); @@ -233,8 +239,9 @@ public List getItemsFromIQ(Packet response) throws Certificate Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); Element statusEl = itemEl.element("status"); - Certificate cert = CertificateHandlerHelper.convertToCertificateFormat(itemEl.element("cert").getText()); - String cpuIdle = statusEl.element("cpu-idle").getText(); + Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl + .element("cert").getText()); + String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); String memIdle = statusEl.element("mem-idle").getText(); String memInUse = statusEl.element("mem-inuse").getText(); @@ -260,9 +267,23 @@ public List getItemsFromIQ(Packet response) throws Certificate return aliveItems; } + public Properties getProperties() throws IOException { + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(CONFIG_PATH); + properties.load(input); + return properties; + } + + public Properties getProperties(String path) throws IOException { + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(path); + properties.load(input); + return properties; + } + public Certificate getCertificate() throws CertificateException, IOException { - return CertificateHandlerHelper.getCertificate(); + return CertificateHandlerHelper.getCertificate(getProperties()); } /* diff --git a/src/test/resources/manager.conf.invalidConf2 b/src/test/resources/manager.conf.invalidConf2 new file mode 100644 index 00000000..f51c9b75 --- /dev/null +++ b/src/test/resources/manager.conf.invalidConf2 @@ -0,0 +1 @@ +certificate= cert.crt \ No newline at end of file diff --git a/src/test/resources/manager.conf.invalidConf3 b/src/test/resources/manager.conf.invalidConf3 new file mode 100644 index 00000000..113df5b7 --- /dev/null +++ b/src/test/resources/manager.conf.invalidConf3 @@ -0,0 +1 @@ +certificate= src/test/resources/server1.crt \ No newline at end of file diff --git a/src/test/resources/manager.conf.invalidTest b/src/test/resources/manager.conf.invalidTest new file mode 100644 index 00000000..cf7c07f0 --- /dev/null +++ b/src/test/resources/manager.conf.invalidTest @@ -0,0 +1 @@ +certificate= \ No newline at end of file diff --git a/src/test/resources/server1.crt b/src/test/resources/server1.crt new file mode 100644 index 00000000..e69de29b From 4cac8712324f53ad17b76c17c74ab378ea9d045b Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Fri, 2 May 2014 20:28:00 +0000 Subject: [PATCH 090/185] Fixing inject tunnel script --- bin/fogbow-inject-tunnel | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bin/fogbow-inject-tunnel b/bin/fogbow-inject-tunnel index 962d6ad0..f398b3fb 100644 --- a/bin/fogbow-inject-tunnel +++ b/bin/fogbow-inject-tunnel @@ -1,2 +1,3 @@ #!/bin/sh -/usr/bin/ssh -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# +/usr/bin/ssh -y -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# + From 902fb3ac3b5c334d9252c9979f5e1b463105b8e0 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Fri, 2 May 2014 17:45:31 -0300 Subject: [PATCH 091/185] Adding certificate Exceptions --- .../manager/xmpp/util/ManagerTestHelper.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 23b1546a..6dfdb959 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -287,14 +287,4 @@ public Certificate getCertificate() throws CertificateException, IOException { return CertificateHandlerHelper.getCertificate(getProperties()); } - - /* - * public static IQ createIAmAliveIQ() { IQ iq = new IQ(Type.get); - * iq.setTo(RENDEZVOUS_COMPONENT_URL); Element statusEl = iq.getElement() - * .addElement("query", IAMALIVE_NAMESPACE).addElement("status"); - * statusEl.addElement("cpu-idle").setText("valor1"); - * statusEl.addElement("cpu-inuse").setText("valor2"); - * statusEl.addElement("mem-idle").setText("valor3"); - * statusEl.addElement("mem-inuse").setText("valor4"); return iq; } - */ } From 3438101672396d2c8a903ae81b169a811e501e29 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 22:52:35 +0200 Subject: [PATCH 092/185] Priorizing remote members --- .../manager/core/FederationMemberPicker.java | 4 +--- .../org/fogbowcloud/manager/core/ManagerFacade.java | 6 +++++- .../manager/core/RoundRobinMemberPicker.java | 11 ++++++++++- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java index 697ac331..fd850b83 100644 --- a/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java @@ -1,11 +1,9 @@ package org.fogbowcloud.manager.core; -import java.util.List; - import org.fogbowcloud.manager.core.model.FederationMember; public interface FederationMemberPicker { - public FederationMember pick(List members); + public FederationMember pick(ManagerFacade facade); } diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index dca3c7cb..b2c5856c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -298,7 +298,7 @@ public List createRequests(String authToken, List categories, } private boolean submitRemoteRequest(Request request) { - FederationMember member = memberPicker.pick(getMembers()); + FederationMember member = memberPicker.pick(this); String memberAddress = member.getResourcesInfo().getId(); request.setMemberId(memberAddress); @@ -387,4 +387,8 @@ public void setRequests(RequestRepository requests) { public Token getToken(Map attributesToken) { return identityPlugin.getToken(attributesToken); } + + public Properties getProperties() { + return properties; + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java index 9e2c7755..f2bab3db 100644 --- a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java @@ -9,11 +9,20 @@ public class RoundRobinMemberPicker implements FederationMemberPicker { private int current = -1; @Override - public FederationMember pick(List members) { + public FederationMember pick(ManagerFacade facade) { + List members = facade.getMembers(); if (members.isEmpty()) { return null; } current = (current + 1) % members.size(); + FederationMember currentMember = members.get(current); + + String myJid = facade.getProperties().getProperty("xmpp_jid"); + if (currentMember.getResourcesInfo().getId().equals(myJid) && members.size() > 1) { + current = (current + 1) % members.size(); + currentMember = members.get(current); + } + return members.get(current); } From f710efff005530e8c48b33c46f7fd64bf6368f9e Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 22:58:28 +0200 Subject: [PATCH 093/185] Removing references to test packages in src/main --- manager.conf.example | 2 ++ .../fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 10 +++++----- .../fogbowcloud/manager/xmpp/ManagerXmppComponent.java | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index 227675a2..e513baa4 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -20,6 +20,8 @@ federation_user_name=fogbow federation_user_password=fogbow federation_user_tenant_name=demo +cert_path= + scheduler_period=30000 ssh_tunnel_host=10.0.0.1 diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 15f064ba..9f54e7b1 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -11,8 +11,8 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.logging.Logger; import java.util.Properties; +import java.util.logging.Logger; import org.apache.http.HttpStatus; import org.dom4j.Attribute; @@ -29,7 +29,6 @@ import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.jamppa.component.PacketSender; import org.xmpp.packet.IQ; import org.xmpp.packet.IQ.Type; @@ -42,7 +41,8 @@ public class ManagerPacketHelper { .getLogger(ManagerPacketHelper.class.getName()); public static void iAmAlive(ResourcesInfo resourcesInfo, - String rendezvousAddress, PacketSender packetSender) + String rendezvousAddress, Properties properties, + PacketSender packetSender) throws IOException { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); @@ -51,8 +51,8 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, .addElement("status"); try { - Properties properties = new Properties(); - FileInputStream input = new FileInputStream(ManagerTestHelper.CONFIG_PATH); + FileInputStream input = new FileInputStream( + properties.getProperty("cert_path")); properties.load(input); iq.getElement().element("query").addElement("cert") .setText(CertificateHandlerHelper.getBase64Certificate(properties)); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 50ffaf1d..4414fce4 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -39,7 +39,7 @@ public void init() { public void iAmAlive() throws CertificateException, IOException { ManagerPacketHelper.iAmAlive(managerFacade.getResourcesInfo(), - rendezvousAddress, this); + rendezvousAddress, managerFacade.getProperties(), this); } @Override From b1b05b01e57c5783224a1c62f1f3c940b846e9b0 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:03:17 +0200 Subject: [PATCH 094/185] Catching any exception during certificate load --- .../org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 9f54e7b1..7dc00526 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -56,8 +56,8 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, properties.load(input); iq.getElement().element("query").addElement("cert") .setText(CertificateHandlerHelper.getBase64Certificate(properties)); - } catch (CertificateException e) { - LOGGER.warning("Certificate does not Exist"); + } catch (Exception e) { + LOGGER.warning("Could not load certificate"); } statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); From e04c96782f4a47995d6d18db84316da97e68f77e Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:05:35 +0200 Subject: [PATCH 095/185] Catching any exception during certificate parsing --- .../org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 7dc00526..3cdfb5d4 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -101,11 +101,9 @@ private static ArrayList getMembersFromIQ( Certificate cert = null; try { - cert = CertificateHandlerHelper - .parseCertificate(itemEl.element("cert") - .getText()); - } catch (CertificateException e) { - LOGGER.warning("Certificate can not be Parsed."); + cert = CertificateHandlerHelper.parseCertificate(itemEl.element("cert").getText()); + } catch (Exception e) { + LOGGER.warning("Certificate could not be parsed."); } Element statusEl = itemEl.element("status"); From e7e0ce9c3f5c92bc75ca9644f21d13afb681967a Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:21:25 +0200 Subject: [PATCH 096/185] Fixes error type for quota exceeded --- .../org/fogbowcloud/manager/core/ManagerFacade.java | 3 +-- .../plugins/openstack/OpenStackComputePlugin.java | 11 +++++++---- .../org/fogbowcloud/manager/occi/core/ErrorType.java | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index b2c5856c..c7dbc03b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -325,8 +325,7 @@ private boolean submitLocalRequest(Request request) { instanceId = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.BAD_REQUEST) - && e.getMessage().contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + if (e.getStatus().equals(ErrorType.QUOTA_EXCEEDED)) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; } else { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 2c492e7e..9790ae6a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -118,12 +118,15 @@ public String requestInstance(String authToken, List categories, attName + "=" + "\"" + xOCCIAtt.get(attName) + "\""); } HttpResponse response = httpClient.execute(httpPost); + String errorMessage = EntityUtils.toString( + response.getEntity(), String.valueOf(Charsets.UTF_8)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, EntityUtils.toString( - response.getEntity(), String.valueOf(Charsets.UTF_8))); + throw new OCCIException(ErrorType.UNAUTHORIZED, errorMessage); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { - throw new OCCIException(ErrorType.NOT_FOUND, EntityUtils.toString( - response.getEntity(), String.valueOf(Charsets.UTF_8))); + if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); + } + throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); } return response.getFirstHeader("Location").getValue(); diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ErrorType.java b/src/main/java/org/fogbowcloud/manager/occi/core/ErrorType.java index 79c29d90..3307948f 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ErrorType.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ErrorType.java @@ -2,6 +2,6 @@ public enum ErrorType { - UNAUTHORIZED, NOT_FOUND, BAD_REQUEST; + UNAUTHORIZED, NOT_FOUND, BAD_REQUEST, QUOTA_EXCEEDED; } From 502559cd44f24d427f79d9c8a45454b03498ffc4 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:29:33 +0200 Subject: [PATCH 097/185] Fixes quota exceeded token --- .../org/fogbowcloud/manager/occi/core/ResponseConstants.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java index 8d14e15a..b43a778c 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java @@ -10,6 +10,6 @@ public class ResponseConstants { public static final String CLOUD_NOT_SUPPORT_CATEGORY = "The cloud does not support category: "; public static final String COULD_NOT_CREATE_TUNNEL = "SSH tunnel could not be created."; public static final String INVALID_OS_TEMPLATE = "Please provide a valid OS Template."; - public static final String QUOTA_EXCEEDED_FOR_INSTANCES = "Quota exceeded for instances."; + public static final String QUOTA_EXCEEDED_FOR_INSTANCES = "Quota exceeded"; } From e596c4794605080d1a28fffd5fb8d30f148ece01 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:33:14 +0200 Subject: [PATCH 098/185] Temporarily considering any bad request as quota exceeded --- .../core/plugins/openstack/OpenStackComputePlugin.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 9790ae6a..7b12dc7e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -123,10 +123,10 @@ public String requestInstance(String authToken, List categories, if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, errorMessage); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { - if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { +// if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); - } - throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); +// } +// throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); } return response.getFirstHeader("Location").getValue(); From c76e98af1ea49effeb718359dbed1fc985f262af Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:35:51 +0200 Subject: [PATCH 099/185] quota: Filtering by a proper status code --- .../java/org/fogbowcloud/manager/core/ManagerFacade.java | 2 +- .../core/plugins/openstack/OpenStackComputePlugin.java | 6 +++--- .../org/fogbowcloud/manager/occi/core/OCCIException.java | 2 ++ 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index c7dbc03b..b1721ba2 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -325,7 +325,7 @@ private boolean submitLocalRequest(Request request) { instanceId = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.QUOTA_EXCEEDED)) { + if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; } else { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 7b12dc7e..9790ae6a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -123,10 +123,10 @@ public String requestInstance(String authToken, List categories, if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, errorMessage); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { -// if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); -// } -// throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); + } + throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); } return response.getFirstHeader("Location").getValue(); diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java index 856e046d..4b8f6104 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java @@ -20,6 +20,8 @@ private static int getStatusCode(ErrorType type) { return HttpStatus.SC_NOT_FOUND; case BAD_REQUEST: return HttpStatus.SC_BAD_REQUEST; + case QUOTA_EXCEEDED: + return HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE; default: break; } From 16dacfa55eb4ae05c0e0cf449b349c88fc32e477 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:35:51 +0200 Subject: [PATCH 100/185] quota: Filtering by a proper status code --- src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java | 2 +- .../java/org/fogbowcloud/manager/occi/core/OCCIException.java | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index c7dbc03b..b1721ba2 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -325,7 +325,7 @@ private boolean submitLocalRequest(Request request) { instanceId = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { - if (e.getStatus().equals(ErrorType.QUOTA_EXCEEDED)) { + if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; } else { diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java index 856e046d..4b8f6104 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIException.java @@ -20,6 +20,8 @@ private static int getStatusCode(ErrorType type) { return HttpStatus.SC_NOT_FOUND; case BAD_REQUEST: return HttpStatus.SC_BAD_REQUEST; + case QUOTA_EXCEEDED: + return HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE; default: break; } From 6e53c0d26faacb8f776005fbcc4d38322679785b Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:40:58 +0200 Subject: [PATCH 101/185] bad request == quota exceeded --- .../core/plugins/openstack/OpenStackComputePlugin.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 9790ae6a..7b12dc7e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -123,10 +123,10 @@ public String requestInstance(String authToken, List categories, if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, errorMessage); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { - if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { +// if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); - } - throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); +// } +// throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); } return response.getFirstHeader("Location").getValue(); From 682f5990b42eef96fab8b903a28d33b20c8af6df Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 2 May 2014 23:50:04 +0200 Subject: [PATCH 102/185] More logs on federation --- src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index b1721ba2..e8ce0fa2 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -146,8 +146,11 @@ public Instance getInstance(String authToken, String instanceId) { private Instance getInstance(String authToken, String instanceId, Request request) { Instance instance = null; if (isLocal(request)) { + LOGGER.debug(instanceId + " is local, getting its information in the local cloud."); instance = this.computePlugin.getInstance(authToken, instanceId); } else { + LOGGER.debug(instanceId + " is remote, going out to " + + request.getMemberId() + " to get its information."); instance = getRemoteInstance(request); } String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); From ad653c0d67d3382848536af0ef6937e741195c34 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sat, 3 May 2014 00:12:59 +0200 Subject: [PATCH 103/185] normalizing instance ids --- .../org/fogbowcloud/manager/core/ManagerFacade.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index e8ce0fa2..4316dc6a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -198,13 +198,21 @@ private void removeInstance(String authToken, String instanceId, Request request private void removeRemoteInstance(Request request) { ManagerPacketHelper.deleteRemoteInstace(request, packetSender); } + + private static String normalizeInstanceId(String instanceId) { + if (!instanceId.contains("/")) { + return instanceId; + } + String[] splitInstanceId = instanceId.split("/"); + return splitInstanceId[splitInstanceId.length - 1]; + } public Request getRequestFromInstance(String authToken, String instanceId) { String user = getUser(authToken); LOGGER.debug("Getting instance " + instanceId + " of user " + user); List userRequests = requests.getAll(); for (Request request : userRequests) { - if (instanceId.equals(request.getInstanceId())) { + if (instanceId.equals(normalizeInstanceId(request.getInstanceId()))) { if (!request.getUser().equals(user)) { LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " + ResponseConstants.UNAUTHORIZED); From 6cd3d5bc83ae971b68b9e52d57dc8dea5cedb7d7 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sat, 3 May 2014 17:54:56 +0200 Subject: [PATCH 104/185] Normalizing ids before sending to remote members. --- .../java/org/fogbowcloud/manager/core/ManagerFacade.java | 2 +- .../core/plugins/openstack/OpenStackComputePlugin.java | 3 +++ .../org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java | 7 +++++-- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 4316dc6a..37d5dca1 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -199,7 +199,7 @@ private void removeRemoteInstance(Request request) { ManagerPacketHelper.deleteRemoteInstace(request, packetSender); } - private static String normalizeInstanceId(String instanceId) { + public static String normalizeInstanceId(String instanceId) { if (!instanceId.contains("/")) { return instanceId; } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 7b12dc7e..291a5258 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -152,7 +152,10 @@ public Instance getInstance(String authToken, String instanceId) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } else if (response.getStatusLine().getStatusCode() >= 400) { + throw new OCCIException(ErrorType.BAD_REQUEST, response.getStatusLine().toString()); } + String responseStr = EntityUtils.toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); return Instance.parseInstance(instanceId, responseStr); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 3cdfb5d4..c1eeb07c 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -18,6 +18,7 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.CertificateHandlerHelper; +import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; @@ -174,7 +175,8 @@ public static Instance getRemoteInstance(Request request, ManagerXmppComponent.GETINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); try { - instanceEl.addElement("id").setText(request.getInstanceId()); + instanceEl.addElement("id").setText( + ManagerFacade.normalizeInstanceId(request.getInstanceId())); } catch (Exception e) { // TODO: handle exception } @@ -200,7 +202,8 @@ public static void deleteRemoteInstace(Request request, Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); - instanceEl.addElement("id").setText(request.getInstanceId()); + instanceEl.addElement("id").setText( + ManagerFacade.normalizeInstanceId(request.getInstanceId())); IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { From e9b4c4063c063800d13b25c2012e5ed1c6f8338d Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sat, 3 May 2014 18:00:05 +0200 Subject: [PATCH 105/185] TokenServerResource: we just care about the token, really --- .../org/fogbowcloud/manager/occi/TokenServerResource.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java index c2fec0ea..d6a5eb58 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java @@ -36,10 +36,6 @@ public String generateResponse(Token token) { } Map tokenAttributes = token.getAttributes(); - String tokenId = tokenAttributes.get(OCCIHeaders.X_TOKEN); - String tenantId = tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_ID); - - return OCCIHeaders.X_TOKEN + ":" + tokenId + "\n" + OCCIHeaders.X_TOKEN_TENANT_ID + ":" - + tenantId; + return tokenAttributes.get(OCCIHeaders.X_TOKEN); } } From 6578454f9633538704388b5d3a972c15c427693a Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 5 May 2014 15:22:57 +0200 Subject: [PATCH 106/185] Reading from env vars, using proper headers. --- bin/fogbow-cli | 2 +- .../org/fogbowcloud/manager/cli/Main.java | 53 ++++++++++--------- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/bin/fogbow-cli b/bin/fogbow-cli index 3ac63ec2..93983e46 100755 --- a/bin/fogbow-cli +++ b/bin/fogbow-cli @@ -1,4 +1,4 @@ #!/bin/bash DIRNAME=`dirname $0` cd $DIRNAME/.. -java -cp target/manager-0.0.1-SNAPSHOT.jar:target/lib/* org.fogbowcloud.manager.cli.Main $@ \ No newline at end of file +java -Dlog4j.configuration=file:log4j.properties -cp target/manager-0.0.1-SNAPSHOT.jar:target/lib/* org.fogbowcloud.manager.cli.Main $@ diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 5d4324d6..e4243c96 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -5,6 +5,7 @@ import java.util.HashSet; import java.util.Set; +import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -14,6 +15,7 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.occi.core.OCCIHeaders; @@ -54,7 +56,7 @@ public static void main(String[] args) throws Exception { String url = member.url; doRequest("get", url + "/members", null); } else if (parsedCommand.equals("request")) { - String url = member.url; + String url = request.url; if (request.get) { if (request.create || request.delete) { jc.usage(); @@ -77,21 +79,21 @@ public static void main(String[] args) throws Exception { return; } - Set headers = new HashSet(); - headers.add("Category: fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\""); - headers.add("X-OCCI-Attribute: org.fogbowcloud.request.instance-count = " - + request.instanceCount); - headers.add("X-OCCI-Attribute: org.fogbowcloud.request.type = one-time"); - headers.add("Category: " - + request.flavor - + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); - headers.add("Category: " - + request.image - + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); + Set
headers = new HashSet
(); + headers.add(new BasicHeader("Category", + "fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\"")); + headers.add(new BasicHeader("X-OCCI-Attribute", + "org.fogbowcloud.request.instance-count=" + request.instanceCount)); + headers.add(new BasicHeader("X-OCCI-Attribute", + "org.fogbowcloud.request.type=one-time")); + headers.add(new BasicHeader("Category", + request.flavor + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\"")); + headers.add(new BasicHeader("Category", + request.image + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\"")); doRequest("post", url + "/request", request.authToken, headers); } } else if (parsedCommand.equals("instance")) { - String url = member.url; + String url = instance.url; if (instance.delete && instance.get) { jc.usage(); return; @@ -110,11 +112,11 @@ public static void main(String[] args) throws Exception { doRequest("delete", url + "/compute/" + instance.instanceId, instance.authToken); } } else if (parsedCommand.equals("token")) { - String url = member.url; - Set headers = new HashSet(); - headers.add(OCCIHeaders.X_TOKEN_USER + ": " + token.username); - headers.add(OCCIHeaders.X_TOKEN_PASS + ": " + token.password); - headers.add(OCCIHeaders.X_TOKEN_TENANT_NAME + ": " + token.tenantName); + String url = token.url; + Set
headers = new HashSet
(); + headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_USER, token.username)); + headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_PASS, token.password)); + headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_TENANT_NAME, token.tenantName)); doRequest("get", url + "/token", null, headers); } @@ -122,11 +124,11 @@ public static void main(String[] args) throws Exception { private static void doRequest(String method, String endpoint, String authToken) throws URISyntaxException, HttpException, IOException { - doRequest(method, endpoint, authToken, new HashSet()); + doRequest(method, endpoint, authToken, new HashSet
()); } private static void doRequest(String method, String endpoint, String authToken, - Set additionalHeaders) throws URISyntaxException, HttpException, IOException { + Set
additionalHeaders) throws URISyntaxException, HttpException, IOException { HttpUriRequest request = null; if (method.equals("get")) { request = new HttpGet(endpoint); @@ -139,9 +141,8 @@ private static void doRequest(String method, String endpoint, String authToken, if (authToken != null) { request.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); } - for (String header : additionalHeaders) { - String[] splitHeader = header.split(": "); - request.addHeader(splitHeader[0].trim(), splitHeader[1].trim()); + for (Header header : additionalHeaders) { + request.addHeader(header); } HttpClient client = new DefaultHttpClient(); @@ -156,12 +157,12 @@ private static void doRequest(String method, String endpoint, String authToken, private static class Command { @Parameter(names = "--url", description = "fogbow manager url") - String url = Main.DEFAULT_URL; + String url = System.getenv("FOGBOW_URL") == null ? Main.DEFAULT_URL : System.getenv("FOGBOW_URL"); } private static class AuthedCommand extends Command { - @Parameter(names = "--auth-token", required = true, description = "auth token") - String authToken = null; + @Parameter(names = "--auth-token", description = "auth token") + String authToken = System.getenv("FOGBOW_AUTH_TOKEN"); } @Parameters(separators = "=", commandDescription = "Members operations") From b6906ef09694ce7cfde9fa0c7a0f93137bea1e79 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 5 May 2014 15:05:35 -0300 Subject: [PATCH 107/185] Implementing the behavior of the password. cli. --- src/main/java/org/fogbowcloud/manager/cli/Main.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index e4243c96..4a8d798f 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -45,8 +45,8 @@ public static void main(String[] args) throws Exception { jc.setProgramName("fogbow-cli"); jc.parse(args); - String parsedCommand = jc.getParsedCommand(); - + String parsedCommand = jc.getParsedCommand(); + if (parsedCommand == null) { jc.usage(); return; @@ -113,6 +113,12 @@ public static void main(String[] args) throws Exception { } } else if (parsedCommand.equals("token")) { String url = token.url; + + if(token.password == null) { + System.out.print("Password:"); + token.password = new String(JCommander.getConsole().readPassword(false)); + } + Set
headers = new HashSet
(); headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_USER, token.username)); headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_PASS, token.password)); @@ -212,7 +218,7 @@ private static class TokenCommand extends Command { @Parameter(names = "--get", description = "Get token") Boolean get = false; - @Parameter(names = "--password", required = true, description = "Password", password = true) + @Parameter(names = "--password", required = false, description = "Password") String password = null; @Parameter(names = "--username", required = true, description = "Username") From 1861b23b4afa42bdf4146c735595baeae85db70f Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 5 May 2014 17:05:00 -0300 Subject: [PATCH 108/185] Refatoring using HttpCLient. OpenStackComputePlugin. --- .../openstack/OpenStackComputePlugin.java | 96 +++++++++++-------- 1 file changed, 55 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 291a5258..c515b1a8 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -4,11 +4,14 @@ import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.Set; import org.apache.commons.codec.Charsets; +import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -16,7 +19,9 @@ import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.model.Flavor; @@ -104,20 +109,18 @@ public String requestInstance(String authToken, List categories, xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(DefaultSSHTunnel.USER_DATA_ATT)); - HttpClient httpClient = new DefaultHttpClient(); - HttpPost httpPost; - try { - httpPost = new HttpPost(computeOCCIEndpoint); - httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); - httpPost.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - for (Category category : openStackCategories) { - httpPost.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - } - for (String attName : xOCCIAtt.keySet()) { - httpPost.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, - attName + "=" + "\"" + xOCCIAtt.get(attName) + "\""); - } - HttpResponse response = httpClient.execute(httpPost); + Set
headers = new HashSet
(); + for (Category category : openStackCategories) { + headers.add(new BasicHeader(OCCIHeaders.CATEGORY, category.toHeader())); + } + for (String attName : xOCCIAtt.keySet()) { + headers.add(new BasicHeader(OCCIHeaders.X_OCCI_ATTRIBUTE + , attName + "=" + "\"" + xOCCIAtt.get(attName) + "\"")); + } + try { + HttpResponse response = doRequest("post", computeOCCIEndpoint + , authToken, headers); + String errorMessage = EntityUtils.toString( response.getEntity(), String.valueOf(Charsets.UTF_8)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { @@ -141,13 +144,9 @@ public String requestInstance(String authToken, List categories, } public Instance getInstance(String authToken, String instanceId) { - HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet; try { - httpGet = new HttpGet(computeOCCIEndpoint + instanceId); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - HttpResponse response = httpCLient.execute(httpGet); - + HttpResponse response = doRequest("get", computeOCCIEndpoint + instanceId + , authToken); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { @@ -172,12 +171,8 @@ public Instance getInstance(String authToken, String instanceId) { } public List getInstances(String authToken) { - HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet; try { - httpGet = new HttpGet(computeOCCIEndpoint); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - HttpResponse response = httpCLient.execute(httpGet); + HttpResponse response = doRequest("get", computeOCCIEndpoint, authToken); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); @@ -209,12 +204,8 @@ private List parseInstances(String responseStr) { } public void removeInstances(String authToken) { - HttpClient httpCLient = new DefaultHttpClient(); - HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeOCCIEndpoint); - httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - HttpResponse response = httpCLient.execute(httpDelete); + HttpResponse response = doRequest("delete", computeOCCIEndpoint, authToken); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } @@ -232,12 +223,9 @@ public void removeInstances(String authToken) { @Override public void removeInstance(String authToken, String instanceId) { - HttpClient httpCLient = new DefaultHttpClient(); - HttpDelete httpDelete; try { - httpDelete = new HttpDelete(computeOCCIEndpoint + instanceId); - httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - HttpResponse response = httpCLient.execute(httpDelete); + HttpResponse response = doRequest("delete", computeOCCIEndpoint + instanceId + , authToken); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); @@ -258,13 +246,10 @@ public void removeInstance(String authToken, String instanceId) { @Override public ResourcesInfo getResourcesInfo(Token token) { - HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet; try { - httpGet = new HttpGet(computeV2APIEndpoint - + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + "/limits"); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, token.get(OCCIHeaders.X_TOKEN)); - HttpResponse response = httpCLient.execute(httpGet); + HttpResponse response = doRequest("get", computeV2APIEndpoint + + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + "/limits" + , token.get(OCCIHeaders.X_TOKEN)); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); @@ -296,6 +281,35 @@ public ResourcesInfo getResourcesInfo(Token token) { throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } } + + private static HttpResponse doRequest(String method, String endpoint, String authToken) + throws URISyntaxException, HttpException, IOException { + return doRequest(method, endpoint, authToken, new HashSet
()); + } + + private static HttpResponse doRequest(String method, String endpoint, String authToken, + Set
additionalHeaders) throws URISyntaxException, HttpException, IOException { + HttpUriRequest request = null; + if (method.equals("get")) { + request = new HttpGet(endpoint); + } else if (method.equals("delete")) { + request = new HttpDelete(endpoint); + } else if (method.equals("post")) { + request = new HttpPost(endpoint); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + } + if (authToken != null) { + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + } + for (Header header : additionalHeaders) { + request.addHeader(header); + } + + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(request); + + return response; + } private String getAttFromJson(String attName, String responseStr) { try { From fdc41789b887fd3995b7a7658e6b094e4ae1e960 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Mon, 5 May 2014 17:40:54 -0300 Subject: [PATCH 109/185] Reviewing logs in ManagerFacade --- .../manager/core/ManagerFacade.java | 40 +++++++++++-------- .../manager/core/model/Flavor.java | 3 +- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 37d5dca1..c82e4827 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -71,6 +71,7 @@ public void setIdentityPlugin(IdentityPlugin identityPlugin) { } public void updateMembers(List members) { + LOGGER.debug("Updating members: " + members); if (members == null) { throw new IllegalArgumentException(); } @@ -103,10 +104,12 @@ public List getRequestsFromUser(String authToken) { public void removeAllRequests(String authToken) { String user = getUser(authToken); + LOGGER.debug("Removing all requests of user: " + user); requests.removeByUser(user); } public void removeRequest(String authToken, String requestId) { + LOGGER.debug("Removing requestId: " + requestId); checkRequestId(authToken, requestId); requests.remove(requestId); } @@ -114,8 +117,7 @@ public void removeRequest(String authToken, String requestId) { private void checkRequestId(String authToken, String requestId) { String user = getUser(authToken); if (requests.get(user, requestId) == null) { - LOGGER.warn("User " + user + " does not have requesId " + requestId); - LOGGER.warn("Throwing OCCIException at checkRequesId: " + ResponseConstants.NOT_FOUND); + LOGGER.debug("User " + user + " does not have requesId " + requestId); throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } } @@ -149,8 +151,8 @@ private Instance getInstance(String authToken, String instanceId, Request reques LOGGER.debug(instanceId + " is local, getting its information in the local cloud."); instance = this.computePlugin.getInstance(authToken, instanceId); } else { - LOGGER.debug(instanceId + " is remote, going out to " + - request.getMemberId() + " to get its information."); + LOGGER.debug(instanceId + " is remote, going out to " + request.getMemberId() + + " to get its information."); instance = getRemoteInstance(request); } String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); @@ -166,7 +168,9 @@ private Instance getRemoteInstance(Request request) { } public void removeInstances(String authToken) { - for (Request request : requests.getByUser(getUser(authToken))) { + String user = getUser(authToken); + LOGGER.debug("Removing instances of user: " + user); + for (Request request : requests.getByUser(user)) { String instanceId = request.getInstanceId(); if (instanceId == null) { continue; @@ -189,16 +193,17 @@ private void removeInstance(String authToken, String instanceId, Request request } request.setInstanceId(null); request.setMemberId(null); - if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null + if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null && request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { request.setState(RequestState.OPEN); } + // TODO if request type is one-time, request state is set to CLOSED } private void removeRemoteInstance(Request request) { ManagerPacketHelper.deleteRemoteInstace(request, packetSender); } - + public static String normalizeInstanceId(String instanceId) { if (!instanceId.contains("/")) { return instanceId; @@ -214,15 +219,11 @@ public Request getRequestFromInstance(String authToken, String instanceId) { for (Request request : userRequests) { if (instanceId.equals(normalizeInstanceId(request.getInstanceId()))) { if (!request.getUser().equals(user)) { - LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " - + ResponseConstants.UNAUTHORIZED); throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } return request; } } - LOGGER.warn("Throwing OCCIException at getRequestFromInstance: " - + ResponseConstants.NOT_FOUND); throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } @@ -231,12 +232,15 @@ private boolean isLocal(Request request) { } public Request getRequest(String authToken, String requestId) { + LOGGER.debug("Getting requestId " + requestId); checkRequestId(authToken, requestId); return requests.get(requestId); } public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { + LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + + xOCCIAtt + " for remote member."); String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); @@ -257,16 +261,18 @@ private Token getFederationUserToken() { String tenantName = properties.getProperty("federation_user_tenant_name"); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, username); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); + return identityPlugin.getToken(tokenAttributes); } public Instance getInstanceForRemoteMember(String instanceId) { + LOGGER.info("Getting instance " + instanceId + " for remote member."); String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { + LOGGER.warn("Exception while getting instance " + instanceId + " for remote member.", e); if (e.getStatus().getCode() == HttpStatus.SC_NOT_FOUND) { return null; } @@ -275,6 +281,7 @@ public Instance getInstanceForRemoteMember(String instanceId) { } public void removeInstanceForRemoteMember(String instanceId) { + LOGGER.info("Removing instance " + instanceId + " for remote member."); String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); computePlugin.removeInstance(token, instanceId); } @@ -297,7 +304,7 @@ public List createRequests(String authToken, List categories, LOGGER.warn("Exception while creating ssh tunnel.", e); request.setState(RequestState.FAILED); } - LOGGER.debug("Updated request with tunnel properties : " + request); + LOGGER.info("Created request: " + request); currentRequests.add(request); requests.addRequest(user, request); } @@ -313,7 +320,7 @@ private boolean submitRemoteRequest(Request request) { String memberAddress = member.getResourcesInfo().getId(); request.setMemberId(memberAddress); - LOGGER.info("Submiting request " + request.getId() + " to member " + memberAddress); + LOGGER.info("Submiting request " + request + " to member " + memberAddress); String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, memberAddress, packetSender); @@ -336,6 +343,7 @@ private boolean submitLocalRequest(Request request) { instanceId = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { + //TODO check if this is the error code! if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; @@ -397,7 +405,7 @@ public void setRequests(RequestRepository requests) { public Token getToken(Map attributesToken) { return identityPlugin.getToken(attributesToken); } - + public Properties getProperties() { return properties; } diff --git a/src/main/java/org/fogbowcloud/manager/core/model/Flavor.java b/src/main/java/org/fogbowcloud/manager/core/model/Flavor.java index b7371c82..d085c461 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/Flavor.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/Flavor.java @@ -1,8 +1,7 @@ package org.fogbowcloud.manager.core.model; -//TODO rename this class to Flavor public class Flavor { - + private Integer capacity; private String name; private String cpu; From e1e35ccf9392a33029445548b9bf63c195a094c5 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 6 May 2014 14:33:12 -0300 Subject: [PATCH 110/185] Refatoring OpenStackComputePlugin. fixes #28 --- .../openstack/OpenStackComputePlugin.java | 237 +++++++----------- 1 file changed, 91 insertions(+), 146 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index c515b1a8..f3e91014 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -1,7 +1,5 @@ package org.fogbowcloud.manager.core.plugins.openstack; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -12,7 +10,6 @@ import org.apache.commons.codec.Charsets; import org.apache.http.Header; -import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; @@ -41,6 +38,8 @@ public class OpenStackComputePlugin implements ComputePlugin { + // According to OCCI specification + private static final int LAST_SUCCESSFUL_STATUS = 204; private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; @@ -117,79 +116,43 @@ public String requestInstance(String authToken, List categories, headers.add(new BasicHeader(OCCIHeaders.X_OCCI_ATTRIBUTE , attName + "=" + "\"" + xOCCIAtt.get(attName) + "\"")); } - try { - HttpResponse response = doRequest("post", computeOCCIEndpoint - , authToken, headers); - - String errorMessage = EntityUtils.toString( - response.getEntity(), String.valueOf(Charsets.UTF_8)); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, errorMessage); - } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { -// if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { - throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); -// } -// throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); - } - - return response.getFirstHeader("Location").getValue(); - } catch (URISyntaxException e) { - LOGGER.error(e); - } catch (HttpException e) { - LOGGER.error(e); - } catch (IOException e) { - LOGGER.error(e); + + HttpResponse response = doRequest("post", computeOCCIEndpoint + , authToken, headers);; + + Header locationHeader = response.getFirstHeader("Location"); + if (locationHeader != null) { + return locationHeader.getValue(); } return null; } - public Instance getInstance(String authToken, String instanceId) { - try { - HttpResponse response = doRequest("get", computeOCCIEndpoint + instanceId + public Instance getInstance(String authToken, String instanceId){ + HttpResponse response = doRequest("get", computeOCCIEndpoint + instanceId , authToken); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); - } else if (response.getStatusLine().getStatusCode() >= 400) { - throw new OCCIException(ErrorType.BAD_REQUEST, response.getStatusLine().toString()); - } - - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); - return Instance.parseInstance(instanceId, responseStr); - } catch (URISyntaxException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (HttpException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (IOException e) { + String responseStr = null; + try { + responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + } catch (Exception e) { LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); + return null; } + + return Instance.parseInstance(instanceId, responseStr); } public List getInstances(String authToken) { + HttpResponse response = doRequest("get", computeOCCIEndpoint, authToken); + String responseStr = null; try { - HttpResponse response = doRequest("get", computeOCCIEndpoint, authToken); - - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); - return parseInstances(responseStr); - } catch (URISyntaxException e) { + responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + } catch (Exception e) { LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (HttpException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (IOException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); + return null; } + return parseInstances(responseStr); } private List parseInstances(String responseStr) { @@ -204,112 +167,94 @@ private List parseInstances(String responseStr) { } public void removeInstances(String authToken) { - try { - HttpResponse response = doRequest("delete", computeOCCIEndpoint, authToken); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } - } catch (URISyntaxException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (HttpException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (IOException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } + doRequest("delete", computeOCCIEndpoint, authToken); } @Override public void removeInstance(String authToken, String instanceId) { - try { - HttpResponse response = doRequest("delete", computeOCCIEndpoint + instanceId - , authToken); - - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); - } - } catch (URISyntaxException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (HttpException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (IOException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } + doRequest("delete", computeOCCIEndpoint + instanceId + , authToken); } @Override public ResourcesInfo getResourcesInfo(Token token) { - try { - HttpResponse response = doRequest("get", computeV2APIEndpoint + HttpResponse response = doRequest("get", computeV2APIEndpoint + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + "/limits" , token.get(OCCIHeaders.X_TOKEN)); + String responseStr = null; - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); - } - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); - - String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); - String cpuInUse = getAttFromJson(TOTAL_CORES_USED_ATT, responseStr); - String maxMem = getAttFromJson(MAX_TOTAL_RAM_SIZE_ATT, responseStr); - String memInUse = getAttFromJson(TOTAL_RAM_USED_ATT, responseStr); + try { + responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + } catch (Exception e) { + LOGGER.error(e); + return null; + } - int cpuIdle = Integer.parseInt(maxCpu) - Integer.parseInt(cpuInUse); - int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); + String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); + String cpuInUse = getAttFromJson(TOTAL_CORES_USED_ATT, responseStr); + String maxMem = getAttFromJson(MAX_TOTAL_RAM_SIZE_ATT, responseStr); + String memInUse = getAttFromJson(TOTAL_RAM_USED_ATT, responseStr); - return new ResourcesInfo(String.valueOf(cpuIdle), cpuInUse, String.valueOf(memIdle), - memInUse, getFlavors(cpuIdle, memIdle), null); + int cpuIdle = Integer.parseInt(maxCpu) - Integer.parseInt(cpuInUse); + int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); - } catch (URISyntaxException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (HttpException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } catch (IOException e) { - LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); - } + return new ResourcesInfo(String.valueOf(cpuIdle), cpuInUse, String.valueOf(memIdle), + memInUse, getFlavors(cpuIdle, memIdle), null); } - private static HttpResponse doRequest(String method, String endpoint, String authToken) - throws URISyntaxException, HttpException, IOException { + private HttpResponse doRequest(String method, String endpoint, String authToken) { return doRequest(method, endpoint, authToken, new HashSet
()); } - private static HttpResponse doRequest(String method, String endpoint, String authToken, - Set
additionalHeaders) throws URISyntaxException, HttpException, IOException { - HttpUriRequest request = null; - if (method.equals("get")) { - request = new HttpGet(endpoint); - } else if (method.equals("delete")) { - request = new HttpDelete(endpoint); - } else if (method.equals("post")) { - request = new HttpPost(endpoint); - request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); - } - if (authToken != null) { - request.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - } - for (Header header : additionalHeaders) { - request.addHeader(header); + private HttpResponse doRequest(String method, String endpoint, String authToken, + Set
additionalHeaders){ + HttpResponse response; + try { + HttpUriRequest request = null; + if (method.equals("get")) { + request = new HttpGet(endpoint); + } else if (method.equals("delete")) { + request = new HttpDelete(endpoint); + } else if (method.equals("post")) { + request = new HttpPost(endpoint); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + } + if (authToken != null) { + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + } + for (Header header : additionalHeaders) { + request.addHeader(header); + } + + HttpClient client = new DefaultHttpClient(); + response = client.execute(request); + + } catch (Exception e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } - HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(request); + checkStatusResponse(response); return response; } + + private void checkStatusResponse(HttpResponse response){ + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { +// if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { +// throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); + throw new OCCIException(ErrorType.QUOTA_EXCEEDED, "QUOTA_EXCEEDED"); +// } +// throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); + }else if (response.getStatusLine().getStatusCode() > LAST_SUCCESSFUL_STATUS) { + throw new OCCIException(ErrorType.BAD_REQUEST, response.getStatusLine().toString()); + } + } private String getAttFromJson(String attName, String responseStr) { try { @@ -334,4 +279,4 @@ private List getFlavors(int cpuIdle, int memIdle) { flavors.add(largeFlavor); return flavors; } -} +} \ No newline at end of file From faacaf7906d5c2fe57d11a4f7e1da24165497a40 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 6 May 2014 17:08:08 -0300 Subject: [PATCH 111/185] Removing mentions of instance location. We assume that the implementation of computePlugin.requestInstance method will return instance id. Fixes #36 --- .../manager/core/ManagerFacade.java | 12 +- .../openstack/OpenStackComputePlugin.java | 97 +++++++------- .../occi/request/RequestRepository.java | 21 ++- .../manager/xmpp/ManagerPacketHelper.java | 126 +++++++----------- .../manager/core/TestManagerFacade.java | 54 +++++++- .../manager/occi/TestOCCIApplication.java | 9 +- .../occi/plugins/TestComputeOpenStack.java | 19 ++- .../manager/xmpp/util/ManagerTestHelper.java | 3 +- 8 files changed, 177 insertions(+), 164 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index c82e4827..200b63d7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -197,27 +197,19 @@ private void removeInstance(String authToken, String instanceId, Request request && request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { request.setState(RequestState.OPEN); } - // TODO if request type is one-time, request state is set to CLOSED + //TODO check if closed updated } private void removeRemoteInstance(Request request) { ManagerPacketHelper.deleteRemoteInstace(request, packetSender); } - public static String normalizeInstanceId(String instanceId) { - if (!instanceId.contains("/")) { - return instanceId; - } - String[] splitInstanceId = instanceId.split("/"); - return splitInstanceId[splitInstanceId.length - 1]; - } - public Request getRequestFromInstance(String authToken, String instanceId) { String user = getUser(authToken); LOGGER.debug("Getting instance " + instanceId + " of user " + user); List userRequests = requests.getAll(); for (Request request : userRequests) { - if (instanceId.equals(normalizeInstanceId(request.getInstanceId()))) { + if (instanceId.equals(request.getInstanceId())) { if (!request.getUser().equals(user)) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index f3e91014..ef073746 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -38,8 +38,7 @@ public class OpenStackComputePlugin implements ComputePlugin { - // According to OCCI specification - private static final int LAST_SUCCESSFUL_STATUS = 204; + private static final int LAST_SUCCESSFUL_STATUS = 204; // According to OCCI specification private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; @@ -108,37 +107,44 @@ public String requestInstance(String authToken, List categories, xOCCIAtt.put("org.openstack.compute.user_data", xOCCIAtt.remove(DefaultSSHTunnel.USER_DATA_ATT)); - Set
headers = new HashSet
(); + Set
headers = new HashSet
(); for (Category category : openStackCategories) { headers.add(new BasicHeader(OCCIHeaders.CATEGORY, category.toHeader())); } for (String attName : xOCCIAtt.keySet()) { - headers.add(new BasicHeader(OCCIHeaders.X_OCCI_ATTRIBUTE - , attName + "=" + "\"" + xOCCIAtt.get(attName) + "\"")); + headers.add(new BasicHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, attName + "=" + "\"" + + xOCCIAtt.get(attName) + "\"")); } - - HttpResponse response = doRequest("post", computeOCCIEndpoint - , authToken, headers);; - + + HttpResponse response = doRequest("post", computeOCCIEndpoint, authToken, headers); + ; + Header locationHeader = response.getFirstHeader("Location"); if (locationHeader != null) { - return locationHeader.getValue(); + return normalizeInstanceId(locationHeader.getValue()); } return null; } - public Instance getInstance(String authToken, String instanceId){ - HttpResponse response = doRequest("get", computeOCCIEndpoint + instanceId - , authToken); + private String normalizeInstanceId(String instanceId) { + if (!instanceId.contains("/")) { + return instanceId; + } + String[] splitInstanceId = instanceId.split("/"); + return splitInstanceId[splitInstanceId.length - 1]; + } + + public Instance getInstance(String authToken, String instanceId) { + HttpResponse response = doRequest("get", computeOCCIEndpoint + instanceId, authToken); String responseStr = null; try { - responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); + responseStr = EntityUtils + .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (Exception e) { LOGGER.error(e); return null; } - + return Instance.parseInstance(instanceId, responseStr); } @@ -146,8 +152,8 @@ public List getInstances(String authToken) { HttpResponse response = doRequest("get", computeOCCIEndpoint, authToken); String responseStr = null; try { - responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); + responseStr = EntityUtils + .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (Exception e) { LOGGER.error(e); return null; @@ -167,25 +173,24 @@ private List parseInstances(String responseStr) { } public void removeInstances(String authToken) { - doRequest("delete", computeOCCIEndpoint, authToken); + doRequest("delete", computeOCCIEndpoint, authToken); } @Override public void removeInstance(String authToken, String instanceId) { - doRequest("delete", computeOCCIEndpoint + instanceId - , authToken); + doRequest("delete", computeOCCIEndpoint + instanceId, authToken); } @Override public ResourcesInfo getResourcesInfo(Token token) { - HttpResponse response = doRequest("get", computeV2APIEndpoint - + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + "/limits" - , token.get(OCCIHeaders.X_TOKEN)); + HttpResponse response = doRequest("get", + computeV2APIEndpoint + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + + "/limits", token.get(OCCIHeaders.X_TOKEN)); String responseStr = null; try { - responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); + responseStr = EntityUtils + .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (Exception e) { LOGGER.error(e); return null; @@ -200,15 +205,15 @@ public ResourcesInfo getResourcesInfo(Token token) { int memIdle = Integer.parseInt(maxMem) - Integer.parseInt(memInUse); return new ResourcesInfo(String.valueOf(cpuIdle), cpuInUse, String.valueOf(memIdle), - memInUse, getFlavors(cpuIdle, memIdle), null); + memInUse, getFlavors(cpuIdle, memIdle), null); } - + private HttpResponse doRequest(String method, String endpoint, String authToken) { return doRequest(method, endpoint, authToken, new HashSet
()); } - + private HttpResponse doRequest(String method, String endpoint, String authToken, - Set
additionalHeaders){ + Set
additionalHeaders) { HttpResponse response; try { HttpUriRequest request = null; @@ -226,34 +231,36 @@ private HttpResponse doRequest(String method, String endpoint, String authToken, for (Header header : additionalHeaders) { request.addHeader(header); } - + HttpClient client = new DefaultHttpClient(); - response = client.execute(request); - + response = client.execute(request); + } catch (Exception e) { LOGGER.error(e); - throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); + throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } - + checkStatusResponse(response); - + return response; - } - - private void checkStatusResponse(HttpResponse response){ + } + + private void checkStatusResponse(HttpResponse response) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { -// if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { -// throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); + // if + // (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) + // { + // throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); throw new OCCIException(ErrorType.QUOTA_EXCEEDED, "QUOTA_EXCEEDED"); -// } -// throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); - }else if (response.getStatusLine().getStatusCode() > LAST_SUCCESSFUL_STATUS) { + // } + // throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); + } else if (response.getStatusLine().getStatusCode() > LAST_SUCCESSFUL_STATUS) { throw new OCCIException(ErrorType.BAD_REQUEST, response.getStatusLine().toString()); - } + } } private String getAttFromJson(String attName, String responseStr) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index 6a3a13da..1d18b459 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -7,14 +7,13 @@ import java.util.Map; import org.apache.log4j.Logger; -import org.fogbowcloud.manager.occi.instance.ComputeServerResource; public class RequestRepository { private static final Logger LOGGER = Logger.getLogger(RequestRepository.class); private Map> requests = new HashMap>(); - + public void addRequest(String user, Request request) { LOGGER.debug("Adding request " + request.getId() + " to user " + user); List userRequests = requests.get(user); @@ -24,7 +23,7 @@ public void addRequest(String user, Request request) { } userRequests.add(request); } - + public List get(RequestState state) { List requestInState = new LinkedList(); for (List userRequests : requests.values()) { @@ -36,7 +35,7 @@ public List get(RequestState state) { } return requestInState; } - + public Request get(String requestId) { for (List userRequests : requests.values()) { for (Request request : userRequests) { @@ -65,20 +64,20 @@ public Request get(String user, String requestId) { LOGGER.debug("Request " + requestId + " owner by user " + user + " was not found."); return null; } - + public List getByUser(String user) { - LOGGER.debug("Getting instances by user " + user ); + LOGGER.debug("Getting instances by user " + user); List userRequests = requests.get(user); - return userRequests == null ? new LinkedList() - : new LinkedList(userRequests); + return userRequests == null ? new LinkedList() : new LinkedList( + userRequests); } - + public void removeByUser(String user) { requests.remove(user); } - + public void remove(String requestId) { - LOGGER.debug("Removing requestId " + requestId ); + LOGGER.debug("Removing requestId " + requestId); for (List userRequests : requests.values()) { Iterator iterator = userRequests.iterator(); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index c1eeb07c..707a693a 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -18,7 +18,6 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.CertificateHandlerHelper; -import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; @@ -37,30 +36,25 @@ import org.xmpp.packet.PacketError.Condition; public class ManagerPacketHelper { - - private final static Logger LOGGER = Logger - .getLogger(ManagerPacketHelper.class.getName()); - - public static void iAmAlive(ResourcesInfo resourcesInfo, - String rendezvousAddress, Properties properties, - PacketSender packetSender) - throws IOException { + + private final static Logger LOGGER = Logger.getLogger(ManagerPacketHelper.class.getName()); + + public static void iAmAlive(ResourcesInfo resourcesInfo, String rendezvousAddress, + Properties properties, PacketSender packetSender) throws IOException { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); Element statusEl = iq.getElement() - .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE) - .addElement("status"); + .addElement("query", ManagerXmppComponent.IAMALIVE_NAMESPACE).addElement("status"); try { - FileInputStream input = new FileInputStream( - properties.getProperty("cert_path")); + FileInputStream input = new FileInputStream(properties.getProperty("cert_path")); properties.load(input); iq.getElement().element("query").addElement("cert") .setText(CertificateHandlerHelper.getBase64Certificate(properties)); } catch (Exception e) { LOGGER.warning("Could not load certificate"); } - + statusEl.addElement("cpu-idle").setText(resourcesInfo.getCpuIdle()); statusEl.addElement("cpu-inuse").setText(resourcesInfo.getCpuInUse()); statusEl.addElement("mem-idle").setText(resourcesInfo.getMemIdle()); @@ -71,8 +65,7 @@ public static void iAmAlive(ResourcesInfo resourcesInfo, flavorElement.addElement("name").setText(f.getName()); flavorElement.addElement("cpu").setText(f.getCpu()); flavorElement.addElement("mem").setText(f.getMem()); - flavorElement.addElement("capacity").setText( - f.getCapacity().toString()); + flavorElement.addElement("capacity").setText(f.getCapacity().toString()); } packetSender.syncSendPacket(iq); } @@ -81,18 +74,15 @@ public static List whoIsalive(String rendezvousAddress, PacketSender packetSender) throws CertificateException { IQ iq = new IQ(Type.get); iq.setTo(rendezvousAddress); - iq.getElement().addElement("query", - ManagerXmppComponent.WHOISALIVE_NAMESPACE); + iq.getElement().addElement("query", ManagerXmppComponent.WHOISALIVE_NAMESPACE); IQ response = (IQ) packetSender.syncSendPacket(iq); ArrayList members = getMembersFromIQ(response); return members; } @SuppressWarnings("unchecked") - private static ArrayList getMembersFromIQ( - IQ responseFromWhoIsAliveIQ) { - Element queryElement = responseFromWhoIsAliveIQ.getElement().element( - "query"); + private static ArrayList getMembersFromIQ(IQ responseFromWhoIsAliveIQ) { + Element queryElement = responseFromWhoIsAliveIQ.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); ArrayList aliveItems = new ArrayList(); @@ -100,13 +90,13 @@ private static ArrayList getMembersFromIQ( Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); Certificate cert = null; - + try { cert = CertificateHandlerHelper.parseCertificate(itemEl.element("cert").getText()); } catch (Exception e) { LOGGER.warning("Certificate could not be parsed."); } - + Element statusEl = itemEl.element("status"); String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); @@ -114,21 +104,19 @@ private static ArrayList getMembersFromIQ( String memInUse = statusEl.element("mem-inuse").getText(); List flavoursList = new LinkedList(); - Iterator flavourIterator = statusEl - .elementIterator("flavor"); + Iterator flavourIterator = statusEl.elementIterator("flavor"); while (flavourIterator.hasNext()) { Element flavour = (Element) flavourIterator.next(); String name = flavour.element("name").getText(); String cpu = flavour.element("cpu").getText(); String mem = flavour.element("mem").getText(); - int capacity = Integer.parseInt(flavour.element("capacity") - .getText()); + int capacity = Integer.parseInt(flavour.element("capacity").getText()); Flavor flavor = new Flavor(name, cpu, mem, capacity); flavoursList.add(flavor); } - ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, - cpuInUse, memIdle, memInUse, flavoursList, cert); + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, cpuInUse, memIdle, + memInUse, flavoursList, cert); FederationMember item = new FederationMember(resources); aliveItems.add(item); } @@ -148,26 +136,22 @@ public static String remoteRequest(Request request, String memberAddress, categoryEl.addElement("term").setText(category.getTerm()); categoryEl.addElement("scheme").setText(category.getScheme()); } - for (Entry xOCCIEntry : request.getxOCCIAtt() - .entrySet()) { + for (Entry xOCCIEntry : request.getxOCCIAtt().entrySet()) { Element attributeEl = queryEl.addElement("attribute"); attributeEl.addAttribute("var", xOCCIEntry.getKey()); attributeEl.addElement("value").setText(xOCCIEntry.getValue()); } IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - if (response.getError().getCondition() - .equals(Condition.item_not_found)) { + if (response.getError().getCondition().equals(Condition.item_not_found)) { return null; } raiseException(response.getError()); } - return response.getElement().element("query").element("instance") - .elementText("id"); + return response.getElement().element("query").element("instance").elementText("id"); } - public static Instance getRemoteInstance(Request request, - PacketSender packetSender) { + public static Instance getRemoteInstance(Request request, PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(request.getMemberId()); iq.setType(Type.get); @@ -175,35 +159,30 @@ public static Instance getRemoteInstance(Request request, ManagerXmppComponent.GETINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); try { - instanceEl.addElement("id").setText( - ManagerFacade.normalizeInstanceId(request.getInstanceId())); + instanceEl.addElement("id").setText(request.getInstanceId()); } catch (Exception e) { // TODO: handle exception } IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { - if (response.getError().getCondition() - .equals(Condition.item_not_found)) { + if (response.getError().getCondition().equals(Condition.item_not_found)) { return null; } raiseException(response.getError()); } - return parseInstance(response.getElement().element("query") - .element("instance")); + return parseInstance(response.getElement().element("query").element("instance")); } - public static void deleteRemoteInstace(Request request, - PacketSender packetSender) { + public static void deleteRemoteInstace(Request request, PacketSender packetSender) { IQ iq = new IQ(); iq.setTo(request.getMemberId()); iq.setType(Type.set); Element queryEl = iq.getElement().addElement("query", ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); Element instanceEl = queryEl.addElement("instance"); - instanceEl.addElement("id").setText( - ManagerFacade.normalizeInstanceId(request.getInstanceId())); + instanceEl.addElement("id").setText(request.getInstanceId()); IQ response = (IQ) packetSender.syncSendPacket(iq); if (response.getError() != null) { @@ -214,15 +193,12 @@ public static void deleteRemoteInstace(Request request, private static void raiseException(PacketError error) { Condition condition = error.getCondition(); if (condition.equals(Condition.item_not_found)) { - throw new OCCIException(ErrorType.NOT_FOUND, - ResponseConstants.NOT_FOUND); + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } if (condition.equals(Condition.not_authorized)) { - throw new OCCIException(ErrorType.UNAUTHORIZED, - ResponseConstants.UNAUTHORIZED); + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } - throw new OCCIException(ErrorType.BAD_REQUEST, - ResponseConstants.IRREGULAR_SYNTAX); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } @SuppressWarnings("unchecked") @@ -231,8 +207,7 @@ private static Instance parseInstance(Element instanceEl) { Element linkEl = instanceEl.element("link"); String linkName = linkEl.element("link").getText(); - Iterator linkAttributeIterator = linkEl - .elementIterator("attribute"); + Iterator linkAttributeIterator = linkEl.elementIterator("attribute"); Map attributesLink = new HashMap(); while (linkAttributeIterator.hasNext()) { @@ -243,35 +218,28 @@ private static Instance parseInstance(Element instanceEl) { } Link link = new Link(linkName, attributesLink); - Iterator resourceIterator = instanceEl - .elementIterator("resource"); + Iterator resourceIterator = instanceEl.elementIterator("resource"); List resources = new ArrayList(); while (resourceIterator.hasNext()) { Element itemResourseEl = (Element) resourceIterator.next(); - String termCategory = itemResourseEl.element("category") - .element("term").getText(); - String schemeCategory = itemResourseEl.element("category") - .element("scheme").getText(); - String classCategory = itemResourseEl.element("category") - .element("class").getText(); - Category category = new Category(termCategory, schemeCategory, - classCategory); - - Iterator resourceAttributeIterator = itemResourseEl - .element("category").elementIterator("attribute"); + String termCategory = itemResourseEl.element("category").element("term").getText(); + String schemeCategory = itemResourseEl.element("category").element("scheme").getText(); + String classCategory = itemResourseEl.element("category").element("class").getText(); + Category category = new Category(termCategory, schemeCategory, classCategory); + + Iterator resourceAttributeIterator = itemResourseEl.element("category") + .elementIterator("attribute"); List resourceAttributes = new ArrayList(); while (resourceAttributeIterator.hasNext()) { - Element itemResourseAttributeEl = (Element) resourceAttributeIterator - .next(); + Element itemResourseAttributeEl = (Element) resourceAttributeIterator.next(); resourceAttributes.add(itemResourseAttributeEl.getText()); } - Iterator resourceActionsIterator = itemResourseEl.element( - "category").elementIterator("action"); + Iterator resourceActionsIterator = itemResourseEl.element("category") + .elementIterator("action"); List resourceActions = new ArrayList(); while (resourceActionsIterator.hasNext()) { - Element itemResourseActionEl = (Element) resourceActionsIterator - .next(); + Element itemResourseActionEl = (Element) resourceActionsIterator.next(); resourceActions.add(itemResourseActionEl.getText()); } @@ -279,12 +247,11 @@ private static Instance parseInstance(Element instanceEl) { String title = itemResourseEl.element("title").getText(); String rel = itemResourseEl.element("rel").getText(); - resources.add(new Resource(category, resourceAttributes, - resourceActions, location, title, rel)); + resources.add(new Resource(category, resourceAttributes, resourceActions, location, + title, rel)); } - Iterator attributesIterator = instanceEl - .elementIterator("attribute"); + Iterator attributesIterator = instanceEl.elementIterator("attribute"); Map attributes = new HashMap(); while (attributesIterator.hasNext()) { @@ -298,6 +265,7 @@ private static Instance parseInstance(Element instanceEl) { } public static Condition getCondition(OCCIException e) { + //TODO check if it is not needs other codes, e.g. quota exceeded switch (e.getStatus().getCode()) { case HttpStatus.SC_NOT_FOUND: return Condition.item_not_found; diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java index 5a0fe1f6..deed431f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java @@ -3,22 +3,35 @@ import java.io.IOException; import java.security.cert.CertificateException; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Properties; -import org.fogbowcloud.manager.core.ManagerFacade; import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.ssh.SSHTunnel; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestAttribute; +import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; public class TestManagerFacade { + private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; ManagerFacade managerFacade; ManagerTestHelper managerTestHelper; + private static final Long SCHEDULER_PERIOD = 500L; + @Before public void setUp() throws Exception { managerFacade = new ManagerFacade(new Properties()); @@ -65,4 +78,43 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { } Assert.assertEquals(10, managerFacade.getMembers().size()); } + + @Test + public void testGetRequestsByUser() throws InterruptedException { + + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerFacade = new ManagerFacade(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( + ManagerTestHelper.USER_NAME); + + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerFacade.setIdentityPlugin(identityPlugin); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setSSHTunnel(sshTunnel); + + managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + + Thread.sleep(SCHEDULER_PERIOD * 2); + + List requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(ManagerTestHelper.USER_NAME, requests.get(0).getUser()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getMemberId()); + } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index ed8f86a9..5c257580 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -12,14 +12,12 @@ import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; -import org.fogbowcloud.manager.occi.core.HeaderUtils; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; -import org.fogbowcloud.manager.occi.util.ComputeApplication; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.Assert; import org.junit.Before; @@ -28,10 +26,7 @@ public class TestOCCIApplication { - private static final String INSTANCE_LOCATION = HeaderUtils.X_OCCI_LOCATION - + "http://localhost:" +OCCITestHelper.ENDPOINT_PORT + ComputeApplication.TARGET - + "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - private static final String INSTANCE_ID = INSTANCE_LOCATION; + private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final Long SCHEDULER_PERIOD = 500L; private OCCIApplication occiApplication; @@ -88,7 +83,7 @@ public void testGetRequestDetails() throws InterruptedException { public void testGetRequestDetailsAfterPeriod() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_LOCATION); + .thenReturn(INSTANCE_ID); managerFacade.setComputePlugin(computePlugin); occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 339e8d71..6522a6c3 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -30,7 +30,6 @@ public class TestComputeOpenStack { private static final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; private static final String URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; - private static final String PREFIX_INSTANCE = "http://localhost:8182/compute/"; private OpenStackComputePlugin computeOpenStack; private PluginHelper pluginHelper; @@ -72,7 +71,7 @@ public void testRequestAValidInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -120,7 +119,7 @@ public void testRequestWithoutSizeCateory() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -192,7 +191,7 @@ public void testSupportedOCCIAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); - Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, @@ -213,7 +212,7 @@ public void testMoreSupportedOCCIAtts() { xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); xOCCIAtt.put("occi.compute.state", "inactive"); - Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, @@ -234,7 +233,7 @@ public void testGetAllInstanceIds() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -258,7 +257,7 @@ public void testGetAllManyInstanceIds() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(PREFIX_INSTANCE + instanceId, computeOpenStack + Assert.assertEquals(instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -293,7 +292,7 @@ public void testGetInstanceDetails() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(PREFIX_INSTANCE + FIRST_INSTANCE_ID, + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); @@ -338,7 +337,7 @@ public void testDeleteAllManyInstances() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(PREFIX_INSTANCE + instanceId, computeOpenStack + Assert.assertEquals(instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } @@ -366,7 +365,7 @@ public void testDeleteOneInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(PREFIX_INSTANCE + instanceId, computeOpenStack + Assert.assertEquals(instanceId, computeOpenStack .requestInstance(PluginHelper.AUTH_TOKEN, categories, new HashMap())); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 6dfdb959..4f772445 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -1,7 +1,6 @@ package org.fogbowcloud.manager.xmpp.util; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.security.cert.Certificate; import java.security.cert.CertificateException; @@ -46,6 +45,8 @@ public class ManagerTestHelper { private static final String CLIENT_PASS = "password"; private static final String SMACK_ENDING = "/Smack"; private static final Token TOKEN = new Token(new HashMap()); + public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; + public static final String USER_NAME = "user"; public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String MANAGER_COMPONENT_PASS = "password"; From 6a7861d1df3384a8e7528d0e93449f86b2bc11fe Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 7 May 2014 10:52:59 -0300 Subject: [PATCH 112/185] Fixing bug request state never set to closed. Fixes #40 --- .../manager/core/ManagerFacade.java | 3 +- .../manager/core/TestManagerFacade.java | 87 +++++++++++++++---- 2 files changed, 72 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 200b63d7..55ec6aee 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -196,8 +196,9 @@ private void removeInstance(String authToken, String instanceId, Request request if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null && request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { request.setState(RequestState.OPEN); + } else { + request.setState(RequestState.CLOSED); } - //TODO check if closed updated } private void removeRemoteInstance(Request request) { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java index deed431f..c09bcb33 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java @@ -29,9 +29,9 @@ public class TestManagerFacade { private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; ManagerFacade managerFacade; ManagerTestHelper managerTestHelper; - + private static final Long SCHEDULER_PERIOD = 500L; - + @Before public void setUp() throws Exception { managerFacade = new ManagerFacade(new Properties()); @@ -55,7 +55,7 @@ public void testGet1ItemFromIQ() throws CertificateException, IOException { List items = new LinkedList(); items.add(managerItem); managerFacade.updateMembers(items); - + List members = managerFacade.getMembers(); Assert.assertEquals(1, members.size()); Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); @@ -69,16 +69,15 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { items.add(new FederationMember(managerTestHelper.getResources())); } managerFacade.updateMembers(items); - + List members = managerFacade.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { - Assert.assertEquals("abc", members.get(0).getResourcesInfo() - .getId()); + Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); } Assert.assertEquals(10, managerFacade.getMembers().size()); } - + @Test public void testGetRequestsByUser() throws InterruptedException { @@ -92,29 +91,83 @@ public void testGetRequestsByUser() throws InterruptedException { String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); - + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( ManagerTestHelper.USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - + managerFacade.setIdentityPlugin(identityPlugin); managerFacade.setComputePlugin(computePlugin); managerFacade.setSSHTunnel(sshTunnel); - - managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - + + managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); + Thread.sleep(SCHEDULER_PERIOD * 2); - - List requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); - + + List requests = managerFacade + .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + Assert.assertEquals(1, requests.size()); Assert.assertEquals(ManagerTestHelper.USER_NAME, requests.get(0).getUser()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } + + @Test + public void testGetRequestSetClosed() throws InterruptedException { + + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerFacade = new ManagerFacade(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( + ManagerTestHelper.USER_NAME); + + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerFacade.setIdentityPlugin(identityPlugin); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setSSHTunnel(sshTunnel); + + managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); + + Thread.sleep(SCHEDULER_PERIOD * 2); + + List requests = managerFacade + .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getMemberId()); + + // removing instance + managerFacade.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + + requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } } From 38e6467fa8e0dcc2ac91f8394929765f90112101 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 7 May 2014 12:43:36 -0300 Subject: [PATCH 113/185] Fixing Quota exceeded filter. Refatoring OpenStackComputePlugin. fixes #35 --- .../manager/core/ManagerFacade.java | 3 + .../openstack/OpenStackComputePlugin.java | 93 ++++++++++--------- 2 files changed, 50 insertions(+), 46 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java index 55ec6aee..80fc1f0c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java @@ -310,6 +310,9 @@ public List createRequests(String authToken, List categories, private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(this); + if (member == null) { + return false; + } String memberAddress = member.getResourcesInfo().getId(); request.setMemberId(memberAddress); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index ef073746..981a5a7a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -38,7 +38,8 @@ public class OpenStackComputePlugin implements ComputePlugin { - private static final int LAST_SUCCESSFUL_STATUS = 204; // According to OCCI specification + // According to OCCI specification + private static final int LAST_SUCCESSFUL_STATUS = 204; private static final String INSTANCE_SCHEME = "http://schemas.openstack.org/compute/instance#"; private static final String SCHEME_COMPUTE = "http://schemas.ogf.org/occi/infrastructure#"; public static final String OS_SCHEME = "http://schemas.openstack.org/template/os#"; @@ -116,8 +117,8 @@ public String requestInstance(String authToken, List categories, + xOCCIAtt.get(attName) + "\"")); } - HttpResponse response = doRequest("post", computeOCCIEndpoint, authToken, headers); - ; + HttpResponse response = doRequest("post", computeOCCIEndpoint, authToken, headers) + .getHttpResponse(); Header locationHeader = response.getFirstHeader("Location"); if (locationHeader != null) { @@ -135,29 +136,16 @@ private String normalizeInstanceId(String instanceId) { } public Instance getInstance(String authToken, String instanceId) { - HttpResponse response = doRequest("get", computeOCCIEndpoint + instanceId, authToken); - String responseStr = null; - try { - responseStr = EntityUtils - .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - } catch (Exception e) { - LOGGER.error(e); - return null; - } + + String responseStr = doRequest("get", computeOCCIEndpoint + instanceId, authToken) + .getResponseString(); return Instance.parseInstance(instanceId, responseStr); } public List getInstances(String authToken) { - HttpResponse response = doRequest("get", computeOCCIEndpoint, authToken); - String responseStr = null; - try { - responseStr = EntityUtils - .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - } catch (Exception e) { - LOGGER.error(e); - return null; - } + String responseStr = doRequest("get", computeOCCIEndpoint, authToken).getResponseString(); + return parseInstances(responseStr); } @@ -183,18 +171,10 @@ public void removeInstance(String authToken, String instanceId) { @Override public ResourcesInfo getResourcesInfo(Token token) { - HttpResponse response = doRequest("get", + String responseStr = doRequest( + "get", computeV2APIEndpoint + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) - + "/limits", token.get(OCCIHeaders.X_TOKEN)); - String responseStr = null; - - try { - responseStr = EntityUtils - .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - } catch (Exception e) { - LOGGER.error(e); - return null; - } + + "/limits", token.get(OCCIHeaders.X_TOKEN)).getResponseString(); String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); String cpuInUse = getAttFromJson(TOTAL_CORES_USED_ATT, responseStr); @@ -208,13 +188,14 @@ public ResourcesInfo getResourcesInfo(Token token) { memInUse, getFlavors(cpuIdle, memIdle), null); } - private HttpResponse doRequest(String method, String endpoint, String authToken) { + private Response doRequest(String method, String endpoint, String authToken) { return doRequest(method, endpoint, authToken, new HashSet
()); } - private HttpResponse doRequest(String method, String endpoint, String authToken, + private Response doRequest(String method, String endpoint, String authToken, Set
additionalHeaders) { - HttpResponse response; + HttpResponse httpResponse; + String responseStr = null; try { HttpUriRequest request = null; if (method.equals("get")) { @@ -233,31 +214,32 @@ private HttpResponse doRequest(String method, String endpoint, String authToken, } HttpClient client = new DefaultHttpClient(); - response = client.execute(request); + httpResponse = client.execute(request); + + responseStr = EntityUtils.toString(httpResponse.getEntity(), + String.valueOf(Charsets.UTF_8)); } catch (Exception e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, e.getMessage()); } - checkStatusResponse(response); + checkStatusResponse(httpResponse, responseStr); - return response; + return new Response(httpResponse, responseStr); } - private void checkStatusResponse(HttpResponse response) { + private void checkStatusResponse(HttpResponse response, String errorMessage) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST) { - // if - // (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) - // { - // throw new OCCIException(ErrorType.QUOTA_EXCEEDED, errorMessage); - throw new OCCIException(ErrorType.QUOTA_EXCEEDED, "QUOTA_EXCEEDED"); - // } - // throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); + if (errorMessage.contains(ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)) { + throw new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES); + } + throw new OCCIException(ErrorType.BAD_REQUEST, errorMessage); } else if (response.getStatusLine().getStatusCode() > LAST_SUCCESSFUL_STATUS) { throw new OCCIException(ErrorType.BAD_REQUEST, response.getStatusLine().toString()); } @@ -286,4 +268,23 @@ private List getFlavors(int cpuIdle, int memIdle) { flavors.add(largeFlavor); return flavors; } + + private class Response { + + private HttpResponse httpResponse; + private String responseString; + + public Response(HttpResponse httpResponse, String responseString) { + this.httpResponse = httpResponse; + this.responseString = responseString; + } + + public HttpResponse getHttpResponse() { + return httpResponse; + } + + public String getResponseString() { + return responseString; + } + } } \ No newline at end of file From 105a7c67568ca47d4a8162720a77fb1e9b24d81d Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 7 May 2014 14:36:53 -0300 Subject: [PATCH 114/185] Adding test and Fixing bug of not scheduling requests after remove instance. Renaming ManagerFacade class to ManageController Fixes #41 Fixes #25 --- .../java/org/fogbowcloud/manager/Main.java | 4 +- .../manager/core/FederationMemberPicker.java | 2 +- ...agerFacade.java => ManagerController.java} | 15 +- .../manager/core/RoundRobinMemberPicker.java | 2 +- .../manager/occi/OCCIApplication.java | 6 +- .../manager/xmpp/GetInstanceHandler.java | 6 +- .../manager/xmpp/ManagerXmppComponent.java | 8 +- .../manager/xmpp/RemoveInstanceHandler.java | 6 +- .../manager/xmpp/RequestInstanceHandler.java | 6 +- .../manager/core/TestManagerFacade.java | 151 +++++++++++++++++- .../manager/occi/TestOCCIApplication.java | 6 +- .../manager/occi/util/OCCITestHelper.java | 8 +- .../manager/xmpp/util/ManagerTestHelper.java | 6 +- 13 files changed, 184 insertions(+), 42 deletions(-) rename src/main/java/org/fogbowcloud/manager/core/{ManagerFacade.java => ManagerController.java} (97%) diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index b8e34ad1..b25b723f 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -3,7 +3,7 @@ import java.io.FileInputStream; import java.util.Properties; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; @@ -23,7 +23,7 @@ public static void main(String[] args) throws Exception { IdentityPlugin identityPlugin = (IdentityPlugin) createInstance( "identity_class", properties); - ManagerFacade facade = new ManagerFacade(properties); + ManagerController facade = new ManagerController(properties); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); diff --git a/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java index fd850b83..7e7ab493 100644 --- a/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/FederationMemberPicker.java @@ -4,6 +4,6 @@ public interface FederationMemberPicker { - public FederationMember pick(ManagerFacade facade); + public FederationMember pick(ManagerController facade); } diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java similarity index 97% rename from src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java rename to src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 80fc1f0c..70d4aaf0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerFacade.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -29,12 +29,13 @@ import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; +import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.xmpp.ManagerPacketHelper; import org.jamppa.component.PacketSender; -public class ManagerFacade { +public class ManagerController { - private static final Logger LOGGER = Logger.getLogger(ManagerFacade.class); + private static final Logger LOGGER = Logger.getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; private boolean scheduled = false; @@ -51,7 +52,7 @@ public class ManagerFacade { private SSHTunnel sshTunnel = new DefaultSSHTunnel(); - public ManagerFacade(Properties properties) { + public ManagerController(Properties properties) { this.properties = properties; if (properties == null) { throw new IllegalArgumentException(); @@ -194,8 +195,12 @@ private void removeInstance(String authToken, String instanceId, Request request request.setInstanceId(null); request.setMemberId(null); if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null - && request.getAttValue(RequestAttribute.TYPE.getValue()).equals("persistent")) { + && request.getAttValue(RequestAttribute.TYPE.getValue()).equals( + RequestType.PERSISTENT.getValue())) { request.setState(RequestState.OPEN); + if (!scheduled) { + scheduleRequests(); + } } else { request.setState(RequestState.CLOSED); } @@ -339,7 +344,7 @@ private boolean submitLocalRequest(Request request) { instanceId = computePlugin.requestInstance(request.getAuthToken(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { - //TODO check if this is the error code! + // TODO check if this is the error code! if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; diff --git a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java index f2bab3db..5c4e05d4 100644 --- a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java @@ -9,7 +9,7 @@ public class RoundRobinMemberPicker implements FederationMemberPicker { private int current = -1; @Override - public FederationMember pick(ManagerFacade facade) { + public FederationMember pick(ManagerController facade) { List members = facade.getMembers(); if (members.isEmpty()) { return null; diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index 17faf6bb..de893229 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -3,7 +3,7 @@ import java.util.List; import java.util.Map; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.Token; @@ -17,9 +17,9 @@ public class OCCIApplication extends Application { - private ManagerFacade managerFacade; + private ManagerController managerFacade; - public OCCIApplication(ManagerFacade facade) { + public OCCIApplication(ManagerController facade) { this.managerFacade = facade; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java index 21dbd9a8..3d02c874 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/GetInstanceHandler.java @@ -4,7 +4,7 @@ import java.util.Map.Entry; import org.dom4j.Element; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.Resource; @@ -16,9 +16,9 @@ public class GetInstanceHandler extends AbstractQueryHandler { - private ManagerFacade facade; + private ManagerController facade; - public GetInstanceHandler(ManagerFacade facade) { + public GetInstanceHandler(ManagerController facade) { super(ManagerXmppComponent.GETINSTANCE_NAMESPACE); this.facade = facade; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java index 4414fce4..6e7333b0 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerXmppComponent.java @@ -6,7 +6,7 @@ import java.util.TimerTask; import org.apache.log4j.Logger; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.jamppa.component.XMPPComponent; import org.xmpp.packet.Packet; @@ -20,12 +20,12 @@ public class ManagerXmppComponent extends XMPPComponent { private static long PERIOD = 30000; private static Logger LOGGER = Logger.getLogger(ManagerXmppComponent.class); - private ManagerFacade managerFacade; + private ManagerController managerFacade; private final Timer timer = new Timer(); private String rendezvousAddress; public ManagerXmppComponent(String jid, String password, String server, - int port, ManagerFacade managerFacade) { + int port, ManagerController managerFacade) { super(jid, password, server, port); this.managerFacade = managerFacade; addGetHandler(new GetInstanceHandler(managerFacade)); @@ -75,7 +75,7 @@ public void setRendezvousAddress(String address) { rendezvousAddress = address; } - public ManagerFacade getManagerFacade() { + public ManagerController getManagerFacade() { return managerFacade; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java index 70c46c33..dbf1997d 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RemoveInstanceHandler.java @@ -1,15 +1,15 @@ package org.fogbowcloud.manager.xmpp; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.occi.core.OCCIException; import org.jamppa.component.handler.AbstractQueryHandler; import org.xmpp.packet.IQ; public class RemoveInstanceHandler extends AbstractQueryHandler { - private ManagerFacade facade; + private ManagerController facade; - public RemoveInstanceHandler(ManagerFacade facade) { + public RemoveInstanceHandler(ManagerController facade) { super(ManagerXmppComponent.REMOVEINSTANCE_NAMESPACE); this.facade = facade; } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java index a0092635..fdd68cb3 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java @@ -6,7 +6,7 @@ import java.util.Map; import org.dom4j.Element; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.OCCIException; import org.jamppa.component.handler.AbstractQueryHandler; @@ -15,9 +15,9 @@ public class RequestInstanceHandler extends AbstractQueryHandler { - private ManagerFacade facade; + private ManagerController facade; - public RequestInstanceHandler(ManagerFacade facade) { + public RequestInstanceHandler(ManagerController facade) { super(ManagerXmppComponent.REQUEST_NAMESPACE); this.facade = facade; } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java index c09bcb33..b4f01027 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java @@ -14,10 +14,14 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; +import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; @@ -27,20 +31,22 @@ public class TestManagerFacade { private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - ManagerFacade managerFacade; + private static final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; + + ManagerController managerFacade; ManagerTestHelper managerTestHelper; private static final Long SCHEDULER_PERIOD = 500L; @Before public void setUp() throws Exception { - managerFacade = new ManagerFacade(new Properties()); + managerFacade = new ManagerController(new Properties()); managerTestHelper = new ManagerTestHelper(); } @Test(expected = IllegalArgumentException.class) public void testConstructorException() throws Exception { - new ManagerFacade(null); + new ManagerController(null); } @Test @@ -83,7 +89,7 @@ public void testGetRequestsByUser() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerFacade(properties); + managerFacade = new ManagerController(properties); // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -121,11 +127,11 @@ public void testGetRequestsByUser() throws InterruptedException { } @Test - public void testGetRequestSetClosed() throws InterruptedException { + public void testOneTimeRequestSetClosed() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerFacade(properties); + managerFacade = new ManagerController(properties); // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -150,7 +156,7 @@ public void testGetRequestSetClosed() throws InterruptedException { managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - Thread.sleep(SCHEDULER_PERIOD * 2); + Thread.sleep(SCHEDULER_PERIOD); List requests = managerFacade .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); @@ -170,4 +176,135 @@ public void testGetRequestSetClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } + + @Test + public void testPersistentRequestSetOpen() throws InterruptedException { + + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerFacade = new ManagerController(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + String.valueOf(RequestType.PERSISTENT.getValue())); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID) + .thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( + ManagerTestHelper.USER_NAME); + + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerFacade.setIdentityPlugin(identityPlugin); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setSSHTunnel(sshTunnel); + + managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); + + Thread.sleep(SCHEDULER_PERIOD); + + List requests = managerFacade + .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getMemberId()); + + // removing instance + managerFacade.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + + requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + @Test + public void testPersistentRequestSetFulfilled() throws InterruptedException { + + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerFacade = new ManagerController(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + String.valueOf(RequestType.PERSISTENT.getValue())); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( + ManagerTestHelper.USER_NAME); + + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerFacade.setIdentityPlugin(identityPlugin); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setSSHTunnel(sshTunnel); + + managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); + + Thread.sleep(SCHEDULER_PERIOD); + + List requests = managerFacade + .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getMemberId()); + + // removing instance + managerFacade.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + + requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + //getting second instance + Thread.sleep(SCHEDULER_PERIOD * 2); + + requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getMemberId()); + } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 5c257580..07e4e32f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -6,7 +6,7 @@ import java.util.Map; import java.util.Properties; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; @@ -31,14 +31,14 @@ public class TestOCCIApplication { private OCCIApplication occiApplication; private Map xOCCIAtt; - ManagerFacade managerFacade; + ManagerController managerFacade; @SuppressWarnings("unchecked") @Before public void setUp() { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerFacade(properties); + managerFacade = new ManagerController(properties); occiApplication = new OCCIApplication(managerFacade); // default instance count value is 1 diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 8fceca1a..642ed28f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -12,7 +12,7 @@ import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.util.EntityUtils; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; @@ -43,7 +43,7 @@ public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin iden component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); - ManagerFacade facade = new ManagerFacade(new Properties()); + ManagerController facade = new ManagerController(new Properties()); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); facade.setSSHTunnel(Mockito.mock(SSHTunnel.class)); @@ -57,7 +57,7 @@ public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlug component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); - ManagerFacade facade = new ManagerFacade(new Properties()); + ManagerController facade = new ManagerController(new Properties()); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); facade.setSSHTunnel(Mockito.mock(SSHTunnel.class)); @@ -77,7 +77,7 @@ public void initializeComponentMember(ComputePlugin computePlugin, IdentityPlugi component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); - ManagerFacade facade = new ManagerFacade(new Properties()); + ManagerController facade = new ManagerController(new Properties()); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); facade.setMembers(federationMembers); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 4f772445..c9125847 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -15,7 +15,7 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.CertificateHandlerHelper; -import org.fogbowcloud.manager.core.ManagerFacade; +import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; @@ -171,7 +171,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws properties.put("federation_user_tenant_name", "fogbow"); properties.put("xmpp_jid", "manager.test.com"); - ManagerFacade managerFacade = new ManagerFacade(properties); + ManagerController managerFacade = new ManagerController(properties); managerFacade.setComputePlugin(computePlugin); managerFacade.setIdentityPlugin(identityPlugin); @@ -204,7 +204,7 @@ public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Excepti properties.put("federation_user_password", "fogbow"); properties.put("xmpp_jid", "manager.test.com"); - ManagerFacade managerFacade = new ManagerFacade(properties); + ManagerController managerFacade = new ManagerController(properties); managerFacade.setComputePlugin(computePlugin); managerFacade.setIdentityPlugin(identityPlugin); From 8205c85784c32153c54d43963471884aebcf4076 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 7 May 2014 15:40:17 -0300 Subject: [PATCH 115/185] Adding federation Member Validator Interface --- .../DefaultFederationMemberValidator.java | 29 ++++++++++ .../core/FederationMemberValidator.java | 15 +++++ .../TestDefaultFederationMemberValidator.java | 58 +++++++++++++++++++ .../resources/manager.conf.testdefaultFMV | 1 + src/test/resources/server2.crt | 19 ++++++ 5 files changed, 122 insertions(+) create mode 100644 src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java create mode 100644 src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java create mode 100644 src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java create mode 100644 src/test/resources/manager.conf.testdefaultFMV create mode 100644 src/test/resources/server2.crt diff --git a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java new file mode 100644 index 00000000..0731779a --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java @@ -0,0 +1,29 @@ +package org.fogbowcloud.manager.core; + +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.fogbowcloud.manager.core.model.FederationMember; + +public class DefaultFederationMemberValidator implements FederationMemberValidator { + + @Override + public boolean validateDonatorMember(FederationMember member) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean validateReceivingMember(FederationMember member) { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setValidCAs(List list) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java new file mode 100644 index 00000000..2637e822 --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java @@ -0,0 +1,15 @@ +package org.fogbowcloud.manager.core; + +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.fogbowcloud.manager.core.model.FederationMember; + +public interface FederationMemberValidator { + + public boolean validateDonatorMember(FederationMember member); + public boolean validateReceivingMember(FederationMember member); + public void setValidCAs(List list); + +} diff --git a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java new file mode 100644 index 00000000..b7d9cd60 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java @@ -0,0 +1,58 @@ +package org.fogbowcloud.manager.core; + +import java.io.IOException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.util.LinkedList; +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TestDefaultFederationMemberValidator { + ManagerTestHelper helper; + FederationMemberValidator validator; + + @Before + public void setUp() { + helper = new ManagerTestHelper(); + validator = new DefaultFederationMemberValidator(); + X500Principal ca = new X500Principal( + "O=Internet Widgits Pty Ltd, L=Campina Gande, ST=Paraiba, C=BR"); + X500Principal ca2 = new X500Principal( + "O=Internet Widgits Pty Ltd, ST=Some-State, C=BR"); + List list = new LinkedList(); + list.add(ca); + list.add(ca2); + validator.setValidCAs(list); + } + + @Test + public void testValidMember() throws CertificateException, IOException { + + ManagerTestHelper helper = new ManagerTestHelper(); + Certificate cert = CertificateHandlerHelper.getCertificate(helper + .getProperties()); + FederationMemberValidator validator = new DefaultFederationMemberValidator(); + //see if is this cert in the helper + FederationMember member = new FederationMember(helper.getResources()); + Assert.assertTrue(validator.validateDonatorMember(member)); + } + + @Test + public void testExpiredMember() throws CertificateException, IOException { + + Certificate cert = CertificateHandlerHelper.getCertificate(helper + .getProperties(/*add expired certificate*/)); + FederationMemberValidator validator = new DefaultFederationMemberValidator(); + + FederationMember member = new FederationMember(helper.getResources()); + Assert.assertTrue(validator.validateDonatorMember(member)); + } + +} diff --git a/src/test/resources/manager.conf.testdefaultFMV b/src/test/resources/manager.conf.testdefaultFMV new file mode 100644 index 00000000..1adb14a9 --- /dev/null +++ b/src/test/resources/manager.conf.testdefaultFMV @@ -0,0 +1 @@ +certificate=src/test/resources/newreq.pem \ No newline at end of file diff --git a/src/test/resources/server2.crt b/src/test/resources/server2.crt new file mode 100644 index 00000000..838051ff --- /dev/null +++ b/src/test/resources/server2.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDBjCCAe4CCQCVxx1VVABlZjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJC +UjETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 +cyBQdHkgTHRkMB4XDTE0MDUwNzEyNDE1OFoXDTE1MDUwNzEyNDE1OFowRTELMAkG +A1UEBhMCQlIxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 +IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ANcJCqfDLEzODSRuZ+09RI1k2agqRac/86ycf8PUmE3uMBjg14G8HU0MJKBcaftt +uIO9DOg5a00ZV7cIOzlG5qx7HKzTe+UKSiQQP/vXL7joeGI3ksfitNJJh6r9VEo8 +yHKdG4a3ozr758kC5IMrUMbLLRowYnaiIgKFmNrVlWDy5jU4zUerj69PYGrYCA7m +bbYXfQcMNIGfAke0DiRRbspOhscA2wNvwr+nmHUB4tVPIZLz7pDMkBTh6Lhe+w9a +Cr1nwjTwDK4BrU5oCFdUtHD2qvwneEOauzod0PmfY6QCfsXg9YEyFGdaUobwblNF +bi1dB6GXITGhjKzCGxWz2E8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAYW6WHqw8 +NwwUu6gJ7oaT3RJtb3ByLWA8l43tUSBVPd3YrhRnRFtYUsMxG5R829eLvHKN2Rwk +JIB3ozzZuwbOPNhwBVnd444lBcI06JIJ3jdA8F5BxwTDdA1B31rpa5ZJwu98IUrL +BX2xNtQhkAFynNbi+3UKQi1U2W+zRLza1kl7+CZgqVx0QK97tiwo1eH//OE4x0rf +CoaTtukQYKsgY2eR2ZfqVErBOZrH3kaxK3Elm+SsqOZZTV2kUhKXegWC+dr0QmOe +DWdE9FzhcL8Z+IbHluzTnCDg3IICm4zVf3jWYf8QlrtAD7/9D1vQOm0ikW7LMARR +gn36ucRyCF0OFQ== +-----END CERTIFICATE----- From d9511942fccb85de58097f45a84d0628ed036722 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 8 May 2014 17:16:27 -0300 Subject: [PATCH 116/185] Get new token only if the token is expired. fixes #33 --- .../manager/core/ManagerController.java | 23 +-- .../openstack/OpenStackComputePlugin.java | 2 +- .../openstack/OpenStackIdentityPlugin.java | 5 +- .../manager/occi/TokenServerResource.java | 2 +- .../manager/occi/core/OCCIHeaders.java | 3 +- .../fogbowcloud/manager/occi/core/Token.java | 34 +++- .../manager/core/TestManagerFacade.java | 150 +++++++++++++----- .../occi/plugins/TestIdentityOpenStack.java | 12 +- .../occi/util/KeystoneApplication.java | 5 +- .../manager/occi/util/PluginHelper.java | 6 +- .../manager/xmpp/util/ManagerTestHelper.java | 2 +- 11 files changed, 174 insertions(+), 70 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 70d4aaf0..2250d23d 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -41,6 +41,7 @@ public class ManagerController { private boolean scheduled = false; private Timer timer; + private Token tokenMemberLocal = new Token(new HashMap()); private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); private FederationMemberPicker memberPicker = new RoundRobinMemberPicker(); @@ -239,7 +240,7 @@ public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); - String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); + String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); } catch (OCCIException e) { @@ -249,10 +250,8 @@ public String submitRequestForRemoteMember(List categories, throw e; } } - - // TODO Think about always get new federation user token or store a valid - // one. - private Token getFederationUserToken() { + + protected Token getFederationUserToken() { Map tokenAttributes = new HashMap(); String username = properties.getProperty("federation_user_name"); String password = properties.getProperty("federation_user_password"); @@ -260,13 +259,17 @@ private Token getFederationUserToken() { tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, username); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - - return identityPlugin.getToken(tokenAttributes); - } + + if (tokenMemberLocal.isExpiredToken()) { + Token token = identityPlugin.getToken(tokenAttributes); + this.tokenMemberLocal = token; + } + return this.tokenMemberLocal; + } public Instance getInstanceForRemoteMember(String instanceId) { LOGGER.info("Getting instance " + instanceId + " for remote member."); - String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); + String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { @@ -280,7 +283,7 @@ public Instance getInstanceForRemoteMember(String instanceId) { public void removeInstanceForRemoteMember(String instanceId) { LOGGER.info("Removing instance " + instanceId + " for remote member."); - String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN); + String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); computePlugin.removeInstance(token, instanceId); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 981a5a7a..97df11f1 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -174,7 +174,7 @@ public ResourcesInfo getResourcesInfo(Token token) { String responseStr = doRequest( "get", computeV2APIEndpoint + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) - + "/limits", token.get(OCCIHeaders.X_TOKEN)).getResponseString(); + + "/limits", token.get(OCCIHeaders.X_TOKEN_ACCESS_ID)).getResponseString(); String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); String cpuInUse = getAttFromJson(TOTAL_CORES_USED_ATT, responseStr); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index b4fbee9b..2138a0be 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -37,6 +37,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String ID_KEYSTONE = "id"; public static final String TENANT_KEYSTONE = "tenant"; public static final String ACCESS_KEYSTONE = "access"; + public static final String EXPIRES_KEYSTONE = "expires"; public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; @@ -136,9 +137,11 @@ private Token getTokenFromJson(String responseStr) throws JSONException { String token = tokenKeyStone.getString(ID_KEYSTONE); String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE) .getString(ID_KEYSTONE); + String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); - attributes.put(OCCIHeaders.X_TOKEN, token); + attributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, token); attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); + attributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDateToken); return new Token(attributes); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java index d6a5eb58..90a5eaf6 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java @@ -36,6 +36,6 @@ public String generateResponse(Token token) { } Map tokenAttributes = token.getAttributes(); - return tokenAttributes.get(OCCIHeaders.X_TOKEN); + return tokenAttributes.get(OCCIHeaders.X_TOKEN_ACCESS_ID); } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java index f44ef291..a51d0b56 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java @@ -10,7 +10,8 @@ public class OCCIHeaders { public static final String X_TOKEN_PASS = "X-Token-Pass"; public static final String X_TOKEN_TENANT_NAME = "X-Token-Tenant-Name"; public static final String X_TOKEN_TENANT_ID = "X-Token-Tenant-Id"; - public static final String X_TOKEN = "X-Token"; + public static final String X_TOKEN_ACCESS_ID = "X-Token-Access-Id"; + public static final String X_TOKEN_EXPIRATION_DATE = "X-Token-Expiration-Date"; // occi constants public static final String CATEGORY = "Category"; diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index 15c70c79..fd2895b8 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -1,25 +1,45 @@ package org.fogbowcloud.manager.occi.core; +import java.text.SimpleDateFormat; +import java.util.Locale; import java.util.Map; +import java.util.TimeZone; + +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class Token { - - private Map attributes; - + + private Map attributes; + public Token(Map attributes) { this.attributes = attributes; } - + public String get(String attributeName) { try { - return attributes.get(attributeName); + return attributes.get(attributeName); } catch (Exception e) { return null; } - + } - + public Map getAttributes() { return attributes; } + + public boolean isExpiredToken() { + String expirationDateSrt = get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + long expirationDateMillis; + try { + expirationDateMillis = dateFormatISO8601.parse(expirationDateSrt).getTime(); + } catch (Exception e) { + return true; + } + return expirationDateMillis < new DateUtils().currentTimeMillis(); + } } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java index b4f01027..40632395 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java @@ -2,26 +2,34 @@ import java.io.IOException; import java.security.cert.CertificateException; +import java.sql.Date; +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Properties; +import java.util.TimeZone; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; @@ -33,16 +41,76 @@ public class TestManagerFacade { private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; - ManagerController managerFacade; + ManagerController managerController; ManagerTestHelper managerTestHelper; private static final Long SCHEDULER_PERIOD = 500L; @Before public void setUp() throws Exception { - managerFacade = new ManagerController(new Properties()); + managerController = new ManagerController(new Properties()); managerTestHelper = new ManagerTestHelper(); } + + //TODO mock date + @Test + public void testGetFederationMember() throws InterruptedException { + final String username = "name"; + final String password = "password"; + final String tenantName = "tenantName"; + final String ACCESS_ID_1 = "1111R3FHUISDGVPCHC10"; + final String ACCESS_ID_2 = "2222CVXV23T4TG42VVCV"; + + Properties properties = new Properties(); + properties.put("federation_user_name", username); + properties.put("federation_user_password", password); + properties.put("federation_user_tenant_name", tenantName); + ManagerController managerController = new ManagerController(properties); + OpenStackIdentityPlugin openStackidentityPlugin = Mockito + .mock(OpenStackIdentityPlugin.class); + Map attributesToken = new HashMap(); + attributesToken.put(OCCIHeaders.X_TOKEN_USER, username); + attributesToken.put(OCCIHeaders.X_TOKEN_PASS, password); + attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); + + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + long timeForward = System.currentTimeMillis() + 250; + String expirationDate = dateFormatISO8601.format(new Date(timeForward)); + + Map attributesTokenReturn = new HashMap(); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_ID_1); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDate); + Token token = new Token(attributesTokenReturn); + + Map attributesTokenReturn2 = new HashMap(); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_ID_2); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, "data"); + Token token2 = new Token(attributesTokenReturn2); + + Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); + managerController.setIdentityPlugin(openStackidentityPlugin); + + //Get new token + Token federationUserToken = managerController.getFederationUserToken(); + String accessToken = federationUserToken.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + Assert.assertEquals(ACCESS_ID_1, accessToken); + + //Use member token + accessToken = managerController.getFederationUserToken() + .get(OCCIHeaders.X_TOKEN_ACCESS_ID); + Assert.assertEquals(ACCESS_ID_1, accessToken); + + Thread.sleep(300); + + //Get new token + accessToken = managerController.getFederationUserToken() + .get(OCCIHeaders.X_TOKEN_ACCESS_ID); + Assert.assertEquals(ACCESS_ID_2, accessToken); + } @Test(expected = IllegalArgumentException.class) public void testConstructorException() throws Exception { @@ -51,8 +119,8 @@ public void testConstructorException() throws Exception { @Test public void testGet0ItemsFromIQ() { - managerFacade.updateMembers(new LinkedList()); - Assert.assertEquals(0, managerFacade.getMembers().size()); + managerController.updateMembers(new LinkedList()); + Assert.assertEquals(0, managerController.getMembers().size()); } @Test @@ -60,12 +128,12 @@ public void testGet1ItemFromIQ() throws CertificateException, IOException { FederationMember managerItem = new FederationMember(managerTestHelper.getResources()); List items = new LinkedList(); items.add(managerItem); - managerFacade.updateMembers(items); + managerController.updateMembers(items); - List members = managerFacade.getMembers(); + List members = managerController.getMembers(); Assert.assertEquals(1, members.size()); Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); - Assert.assertEquals(1, managerFacade.getMembers().size()); + Assert.assertEquals(1, managerController.getMembers().size()); } @Test @@ -74,14 +142,14 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { for (int i = 0; i < 10; i++) { items.add(new FederationMember(managerTestHelper.getResources())); } - managerFacade.updateMembers(items); + managerController.updateMembers(items); - List members = managerFacade.getMembers(); + List members = managerController.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); } - Assert.assertEquals(10, managerFacade.getMembers().size()); + Assert.assertEquals(10, managerController.getMembers().size()); } @Test @@ -89,7 +157,7 @@ public void testGetRequestsByUser() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerController(properties); + managerController = new ManagerController(properties); // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -107,16 +175,16 @@ public void testGetRequestsByUser() throws InterruptedException { SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - managerFacade.setIdentityPlugin(identityPlugin); - managerFacade.setComputePlugin(computePlugin); - managerFacade.setSSHTunnel(sshTunnel); + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); - managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD * 2); - List requests = managerFacade + List requests = managerController .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -131,7 +199,7 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerController(properties); + managerController = new ManagerController(properties); // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -149,16 +217,16 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - managerFacade.setIdentityPlugin(identityPlugin); - managerFacade.setComputePlugin(computePlugin); - managerFacade.setSSHTunnel(sshTunnel); + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); - managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerFacade + List requests = managerController .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -167,9 +235,9 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerFacade.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + managerController.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); - requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); @@ -182,7 +250,7 @@ public void testPersistentRequestSetOpen() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerController(properties); + managerController = new ManagerController(properties); // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -206,16 +274,16 @@ public void testPersistentRequestSetOpen() throws InterruptedException { SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - managerFacade.setIdentityPlugin(identityPlugin); - managerFacade.setComputePlugin(computePlugin); - managerFacade.setSSHTunnel(sshTunnel); + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); - managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerFacade + List requests = managerController .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -226,9 +294,9 @@ public void testPersistentRequestSetOpen() throws InterruptedException { Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerFacade.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + managerController.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); - requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -243,7 +311,7 @@ public void testPersistentRequestSetFulfilled() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerFacade = new ManagerController(properties); + managerController = new ManagerController(properties); // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -264,16 +332,16 @@ public void testPersistentRequestSetFulfilled() throws InterruptedException { SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - managerFacade.setIdentityPlugin(identityPlugin); - managerFacade.setComputePlugin(computePlugin); - managerFacade.setSSHTunnel(sshTunnel); + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); - managerFacade.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerFacade + List requests = managerController .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -284,9 +352,9 @@ public void testPersistentRequestSetFulfilled() throws InterruptedException { Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerFacade.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + managerController.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); - requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -298,7 +366,7 @@ public void testPersistentRequestSetFulfilled() throws InterruptedException { //getting second instance Thread.sleep(SCHEDULER_PERIOD * 2); - requests = managerFacade.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index d0b10a7a..18a2fcb5 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -64,8 +64,12 @@ public void testGetToken() { tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, "admin"); Token token = this.identityOpenStack.getToken(tokenAttributes); - String authToken = token.get(OCCIHeaders.X_TOKEN); - Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + String authToken = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); + String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); + Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); } @Test(expected = OCCIException.class) @@ -73,7 +77,7 @@ public void testGetTokenWrongUsername() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, "wrong"); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); this.identityOpenStack.getToken(tokenAttributes); } @@ -82,7 +86,7 @@ public void testGetTokenWrongPassword() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, "worng"); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); this.identityOpenStack.getToken(tokenAttributes); } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 7732320f..21b0c12d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -113,12 +113,15 @@ public Representation post(Representation entity) { private String mountJSONResponseAuthenticateToken(Token token) { try { - String tokenId = token.get(OCCIHeaders.X_TOKEN); + String tokenId = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); String tenantId = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); + String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + JSONObject rootIdTenantToken = new JSONObject(); rootIdTenantToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tenantId); JSONObject rootIdToken = new JSONObject(); rootIdToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tokenId); + rootIdToken.put(OpenStackIdentityPlugin.EXPIRES_KEYSTONE, expirationDate); rootIdToken.put(OpenStackIdentityPlugin.TENANT_KEYSTONE, rootIdTenantToken); JSONObject rootToken = new JSONObject(); rootToken.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index f6f2cfb4..92ceb4b3 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -16,7 +16,8 @@ public class PluginHelper { private Component component; public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; - public static final String TENANT_ID = "TEnAHDH49U"; + public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; + public static final String EXPIRATION_DATA = "2014-01-31T15:30:58Z"; public static final String USERNAME_FOGBOW = "admin"; public static final String PASSWORD_FOGBOW = "reverse"; @@ -31,8 +32,9 @@ public void initializeKeystoneComponent() throws Exception { this.component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN, AUTH_TOKEN); + tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, AUTH_TOKEN); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); + tokenAttributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, EXPIRATION_DATA); Token token = new Token(tokenAttributes); KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW, diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index c9125847..c60ba017 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -66,7 +66,7 @@ public class ManagerTestHelper { public ManagerTestHelper() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN, "token"); + tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, "token"); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); this.tokenDefault = new Token(tokenAttributes); } From 8fd110ee86cf5d73684e178711b5ae63fd8af876 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 8 May 2014 17:18:12 -0300 Subject: [PATCH 117/185] Renaming TestManagerFacade to TestManagerController --- .../core/{TestManagerFacade.java => TestManagerController.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename src/test/java/org/fogbowcloud/manager/core/{TestManagerFacade.java => TestManagerController.java} (99%) diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java similarity index 99% rename from src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java rename to src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 40632395..a7d8379c 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerFacade.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -36,7 +36,7 @@ import org.junit.Test; import org.mockito.Mockito; -public class TestManagerFacade { +public class TestManagerController { private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; From 4ae6e5bcef682e83ba966e1b30e577ba6fa50fe9 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 9 May 2014 10:21:50 -0300 Subject: [PATCH 118/185] Implementing tests to /token endpoint. Refatoring TestMemberServerResource . fixes #42 --- .../occi/TestMemberServerResource.java | 17 +--- .../manager/occi/TestTokenServerResource.java | 95 +++++++++++++++++++ .../manager/occi/util/OCCITestHelper.java | 1 + 3 files changed, 101 insertions(+), 12 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java index 34294e93..78c80f98 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestMemberServerResource.java @@ -31,9 +31,13 @@ public class TestMemberServerResource { private final String ID_RESOURCEINFO2 = "id2"; private OCCITestHelper helper; - + private ComputePlugin computePlugin; + private IdentityPlugin identityPlugin; + @Before public void setup() throws Exception { + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); this.helper = new OCCITestHelper(); } @@ -44,10 +48,6 @@ public void tearDown() throws Exception { @Test public void testGetMember() throws Exception { - - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - List federationMembers = new ArrayList(); List flavours = new ArrayList(); flavours.add(new Flavor(FLAVOUR_1, "3", "135", 2)); @@ -80,11 +80,7 @@ public void testGetMember() throws Exception { @Test public void testGetMemberEmpty() throws Exception { - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - List federationMembers = new ArrayList(); - this.helper.initializeComponentMember(computePlugin, identityPlugin, federationMembers); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); @@ -97,9 +93,6 @@ public void testGetMemberEmpty() throws Exception { @Test public void testGetMemberWrongContentType() throws Exception { - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - this.helper.initializeComponentMember(computePlugin, identityPlugin, null); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_MEMBER); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java new file mode 100644 index 00000000..7da33bdf --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -0,0 +1,95 @@ +package org.fogbowcloud.manager.occi; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.codec.Charsets; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestTokenServerResource { + + private final String ACCESS_TOKEN_ID = "e723tgdjscbh1gyFV4GFC3OQ"; + + private OCCITestHelper helper; + private ComputePlugin computePlugin; + private IdentityPlugin identityPlugin; + + @Before + public void setup() throws Exception { + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); + this.helper = new OCCITestHelper(); + } + + @After + public void tearDown() throws Exception { + this.helper.stopComponent(); + } + + @Test + public void testGetTokenWrongContentType() throws Exception { + this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); + get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); + } + + @Test + public void testGetToken() throws Exception { + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_TOKEN_ID); + Token token = new Token(tokenAttributes); + + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(token); + + this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + + Assert.assertEquals(ACCESS_TOKEN_ID, responseStr); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } + + @Test + public void testGetTokenUnauthorized() throws Exception { + Mockito.when(identityPlugin.getToken(Mockito.anyMap())) + .thenThrow(new OCCIException(ErrorType.UNAUTHORIZED, "")); + + this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine() + .getStatusCode()); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 642ed28f..a017f564 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -33,6 +33,7 @@ public class OCCITestHelper { public static final String URI_FOGBOW_REQUEST = "http://localhost:8182/request"; public static final String URI_FOGBOW_COMPUTE = "http://localhost:8182/compute/"; public static final String URI_FOGBOW_MEMBER = "http://localhost:8182/members"; + public static final String URI_FOGBOW_TOKEN = "http://localhost:8182/token"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; From f13a7199859d7be950a017f09f44a15aaebcf468 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 9 May 2014 11:21:18 -0300 Subject: [PATCH 119/185] Implementing query interface for ext-OCCI endpoint. fixes #38 --- .../org/fogbowcloud/manager/cli/Main.java | 12 ++++ .../manager/occi/OCCIApplication.java | 1 + .../manager/occi/QueryServerResource.java | 29 ++++++++ .../manager/occi/TestPostCompute.java | 16 +++++ .../manager/occi/TestQueryServerResource.java | 70 +++++++++++++++++++ .../manager/occi/TestTokenServerResource.java | 10 +-- .../manager/occi/util/OCCITestHelper.java | 27 +++---- 7 files changed, 149 insertions(+), 16 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java create mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java create mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestQueryServerResource.java diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 4a8d798f..efcbf4b1 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -41,6 +41,8 @@ public static void main(String[] args) throws Exception { jc.addCommand("instance", instance); TokenCommand token = new TokenCommand(); jc.addCommand("token", token); + QueryCommand query = new QueryCommand(); + jc.addCommand("query", query); jc.setProgramName("fogbow-cli"); jc.parse(args); @@ -125,6 +127,10 @@ public static void main(String[] args) throws Exception { headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_TENANT_NAME, token.tenantName)); doRequest("get", url + "/token", null, headers); + } else if (parsedCommand.equals("query")) { + String url = token.url; + + doRequest("get", url + "/-/", null); } } @@ -227,4 +233,10 @@ private static class TokenCommand extends Command { @Parameter(names = "--tenantName", required = true, description = "TenantName") String tenantName = null; } + + @Parameters(separators = "=", commandDescription = "Resources Fogbow") + private static class QueryCommand extends Command { + @Parameter(names = "--get", description = "Get all resources") + Boolean get = false; + } } \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java index de893229..52fb13be 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java +++ b/src/main/java/org/fogbowcloud/manager/occi/OCCIApplication.java @@ -34,6 +34,7 @@ public Restlet createInboundRoot() { router.attach("/compute/{instanceId}", ComputeServerResource.class); router.attach("/members", MemberServerResource.class); router.attach("/token", TokenServerResource.class); + router.attach("/-/", QueryServerResource.class); return router; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java new file mode 100644 index 00000000..fd16d95b --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java @@ -0,0 +1,29 @@ +package org.fogbowcloud.manager.occi; + +import java.util.List; + +import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.core.ResourceRepository; +import org.restlet.engine.adapter.HttpRequest; +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +public class QueryServerResource extends ServerResource { + + @Get + public String fetch() { + HttpRequest req = (HttpRequest) getRequest(); + HeaderUtils.checkOCCIContentType(req.getHeaders()); + + return generateResponse(ResourceRepository.getAll()); + } + + public String generateResponse(List allResources) { + String response = ""; + for (Resource resource : allResources) { + response += resource.toHeader() + "\n"; + } + return response.trim(); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java new file mode 100644 index 00000000..fa86f552 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java @@ -0,0 +1,16 @@ +package org.fogbowcloud.manager.occi; + +import static org.junit.Assert.fail; + +import org.junit.Ignore; +import org.junit.Test; + +public class TestPostCompute { + + @Ignore + @Test + public void test() { + fail("Not yet implemented"); + } + +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestQueryServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestQueryServerResource.java new file mode 100644 index 00000000..3f8cd462 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/TestQueryServerResource.java @@ -0,0 +1,70 @@ +package org.fogbowcloud.manager.occi; + +import org.apache.commons.codec.Charsets; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.core.ResourceRepository; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +public class TestQueryServerResource { + + private OCCITestHelper helper; + private ComputePlugin computePlugin; + private IdentityPlugin identityPlugin; + + @Before + public void setup() throws Exception { + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); + this.helper = new OCCITestHelper(); + } + + @After + public void tearDown() throws Exception { + this.helper.stopComponent(); + } + + @Test + public void testGetQueryWrongContentType() throws Exception { + this.helper.initializeComponent(computePlugin, identityPlugin); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_QUERY); + get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); + } + + @Test + public void testGetQuery() throws Exception { + this.helper.initializeComponent(computePlugin, identityPlugin); + + HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_QUERY); + get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(get); + + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + + for (Resource resource : ResourceRepository.getAll()) { + Assert.assertTrue(responseStr.contains(resource.toHeader())); + } + + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java index 7da33bdf..927ac1f8 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -45,7 +45,7 @@ public void tearDown() throws Exception { @Test public void testGetTokenWrongContentType() throws Exception { - this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + this.helper.initializeComponent(computePlugin, identityPlugin); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); get.addHeader(OCCIHeaders.CONTENT_TYPE, "wrong"); @@ -55,6 +55,7 @@ public void testGetTokenWrongContentType() throws Exception { Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); } + @SuppressWarnings("unchecked") @Test public void testGetToken() throws Exception { Map tokenAttributes = new HashMap(); @@ -63,7 +64,7 @@ public void testGetToken() throws Exception { Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(token); - this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + this.helper.initializeComponent(computePlugin, identityPlugin); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); @@ -71,18 +72,19 @@ public void testGetToken() throws Exception { HttpResponse response = client.execute(get); String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); + String.valueOf(Charsets.UTF_8)); Assert.assertEquals(ACCESS_TOKEN_ID, responseStr); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } + @SuppressWarnings("unchecked") @Test public void testGetTokenUnauthorized() throws Exception { Mockito.when(identityPlugin.getToken(Mockito.anyMap())) .thenThrow(new OCCIException(ErrorType.UNAUTHORIZED, "")); - this.helper.initializeComponentMember(computePlugin, identityPlugin, null); + this.helper.initializeComponent(computePlugin, identityPlugin); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index a017f564..3832fd14 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -34,13 +34,15 @@ public class OCCITestHelper { public static final String URI_FOGBOW_COMPUTE = "http://localhost:8182/compute/"; public static final String URI_FOGBOW_MEMBER = "http://localhost:8182/members"; public static final String URI_FOGBOW_TOKEN = "http://localhost:8182/token"; + public static final String URI_FOGBOW_QUERY = "http://localhost:8182/-/"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; private Component component; private RequestRepository requests; - - public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) throws Exception { + + public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin identityPlugin) + throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); @@ -48,13 +50,13 @@ public void initializeComponent(ComputePlugin computePlugin, IdentityPlugin iden facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); facade.setSSHTunnel(Mockito.mock(SSHTunnel.class)); - + component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); } - - public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlugin identityPlugin, - List requestsToAdd) throws Exception { + + public void initializeComponentCompute(ComputePlugin computePlugin, + IdentityPlugin identityPlugin, List requestsToAdd) throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); @@ -68,13 +70,14 @@ public void initializeComponentCompute(ComputePlugin computePlugin, IdentityPlug for (Request request : requestsToAdd) { requests.addRequest(OCCITestHelper.USER_MOCK, request); } - + component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); } - - public void initializeComponentMember(ComputePlugin computePlugin, IdentityPlugin identityPlugin, - List federationMembers) throws Exception { + + public void initializeComponentMember(ComputePlugin computePlugin, + IdentityPlugin identityPlugin, List federationMembers) + throws Exception { component = new Component(); component.getServers().add(Protocol.HTTP, ENDPOINT_PORT); @@ -82,10 +85,10 @@ public void initializeComponentMember(ComputePlugin computePlugin, IdentityPlugi facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); facade.setMembers(federationMembers); - + component.getDefaultHost().attach(new OCCIApplication(facade)); component.start(); - } + } public void stopComponent() throws Exception { component.stop(); From b2b90d69acd0198007a3e23edf098a915e28748a Mon Sep 17 00:00:00 2001 From: Giovanni Date: Fri, 9 May 2014 16:03:20 -0300 Subject: [PATCH 120/185] Implementing tests to request state changing --- .../manager/core/plugins/IdentityPlugin.java | 4 +- .../fogbowcloud/manager/occi/core/Token.java | 1 + .../manager/core/TestManagerController.java | 435 ++++++++++++++---- .../manager/xmpp/util/ManagerTestHelper.java | 5 +- 4 files changed, 339 insertions(+), 106 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index 22e6ec92..2dbe64f0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -6,7 +6,9 @@ public interface IdentityPlugin { - public String getUser(String token); + public String getUser(String tokenId); + + public String getTokenExpiresDate(String tokenId); public Token getToken(Map tokenAttributes); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index fd2895b8..37ca5841 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -19,6 +19,7 @@ public Token(Map attributes) { public String get(String attributeName) { try { return attributes.get(attributeName); + //TODO Which exception could happen here? } catch (Exception e) { return null; } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index a7d8379c..d446f09e 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -29,7 +29,6 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; @@ -45,71 +44,74 @@ public class TestManagerController { ManagerTestHelper managerTestHelper; private static final Long SCHEDULER_PERIOD = 500L; + public static final String USER_NAME = "user"; + public static final String USER_PASS = "password"; + public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; + public static final String ACCESS_TOKEN_ID_2 = "2222CVXV23T4TG42VVCV"; + private static final Long GRACE_TIME = 30L; + private static final String TENANT_NAME = "tenantName"; @Before public void setUp() throws Exception { managerController = new ManagerController(new Properties()); managerTestHelper = new ManagerTestHelper(); } - - //TODO mock date + + // TODO mock date @Test public void testGetFederationMember() throws InterruptedException { - final String username = "name"; - final String password = "password"; - final String tenantName = "tenantName"; - final String ACCESS_ID_1 = "1111R3FHUISDGVPCHC10"; - final String ACCESS_ID_2 = "2222CVXV23T4TG42VVCV"; - Properties properties = new Properties(); - properties.put("federation_user_name", username); - properties.put("federation_user_password", password); - properties.put("federation_user_tenant_name", tenantName); - ManagerController managerController = new ManagerController(properties); + properties.put("federation_user_name", USER_NAME); + properties.put("federation_user_password", USER_PASS); + properties.put("federation_user_tenant_name", TENANT_NAME); + managerController = new ManagerController(properties); OpenStackIdentityPlugin openStackidentityPlugin = Mockito .mock(OpenStackIdentityPlugin.class); Map attributesToken = new HashMap(); - attributesToken.put(OCCIHeaders.X_TOKEN_USER, username); - attributesToken.put(OCCIHeaders.X_TOKEN_PASS, password); - attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - long timeForward = System.currentTimeMillis() + 250; - String expirationDate = dateFormatISO8601.format(new Date(timeForward)); - + attributesToken.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + attributesToken.put(OCCIHeaders.X_TOKEN_PASS, USER_PASS); + attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + + long expirationTime = System.currentTimeMillis() + 250; + + String expirationDateStr = getDateISO8601Format(expirationTime); + Map attributesTokenReturn = new HashMap(); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_ID_1); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_ACCESS_ID, + ACCESS_TOKEN_ID); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDate); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, + expirationDateStr); Token token = new Token(attributesTokenReturn); - + Map attributesTokenReturn2 = new HashMap(); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_ID_2); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, + ACCESS_TOKEN_ID_2); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, "data"); Token token2 = new Token(attributesTokenReturn2); - - Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); + + Mockito.when(openStackidentityPlugin.getToken(attributesToken)) + .thenReturn(token, token2); managerController.setIdentityPlugin(openStackidentityPlugin); - - //Get new token + + // Get new token Token federationUserToken = managerController.getFederationUserToken(); - String accessToken = federationUserToken.get(OCCIHeaders.X_TOKEN_ACCESS_ID); - Assert.assertEquals(ACCESS_ID_1, accessToken); - - //Use member token - accessToken = managerController.getFederationUserToken() - .get(OCCIHeaders.X_TOKEN_ACCESS_ID); - Assert.assertEquals(ACCESS_ID_1, accessToken); - - Thread.sleep(300); - - //Get new token - accessToken = managerController.getFederationUserToken() + String accessToken = federationUserToken .get(OCCIHeaders.X_TOKEN_ACCESS_ID); - Assert.assertEquals(ACCESS_ID_2, accessToken); + Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); + + // Use member token + accessToken = managerController.getFederationUserToken().get( + OCCIHeaders.X_TOKEN_ACCESS_ID); + Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); + + Thread.sleep(300); + + // Get new token + accessToken = managerController.getFederationUserToken().get( + OCCIHeaders.X_TOKEN_ACCESS_ID); + Assert.assertEquals(ACCESS_TOKEN_ID_2, accessToken); } @Test(expected = IllegalArgumentException.class) @@ -125,7 +127,8 @@ public void testGet0ItemsFromIQ() { @Test public void testGet1ItemFromIQ() throws CertificateException, IOException { - FederationMember managerItem = new FederationMember(managerTestHelper.getResources()); + FederationMember managerItem = new FederationMember( + managerTestHelper.getResources()); List items = new LinkedList(); items.add(managerItem); managerController.updateMembers(items); @@ -137,7 +140,8 @@ public void testGet1ItemFromIQ() throws CertificateException, IOException { } @Test - public void testGetManyItemsFromIQ() throws CertificateException, IOException { + public void testGetManyItemsFromIQ() throws CertificateException, + IOException { ArrayList items = new ArrayList(); for (int i = 0; i < 10; i++) { items.add(new FederationMember(managerTestHelper.getResources())); @@ -147,7 +151,8 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { List members = managerController.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { - Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); + Assert.assertEquals("abc", members.get(0).getResourcesInfo() + .getId()); } Assert.assertEquals(10, managerController.getMembers().size()); } @@ -166,12 +171,13 @@ public void testGetRequestsByUser() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( - ManagerTestHelper.USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -179,23 +185,23 @@ public void testGetRequestsByUser() throws InterruptedException { managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD * 2); List requests = managerController - .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(ManagerTestHelper.USER_NAME, requests.get(0).getUser()); + Assert.assertEquals(USER_NAME, requests.get(0).getUser()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } @Test - public void testOneTimeRequestSetClosed() throws InterruptedException { + public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); @@ -208,12 +214,13 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( - ManagerTestHelper.USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -221,13 +228,13 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); List requests = managerController - .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); @@ -235,9 +242,9 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); - requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); @@ -246,7 +253,7 @@ public void testOneTimeRequestSetClosed() throws InterruptedException { } @Test - public void testPersistentRequestSetOpen() throws InterruptedException { + public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); @@ -261,16 +268,16 @@ public void testPersistentRequestSetOpen() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))) + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) .thenReturn(INSTANCE_ID) .thenThrow( new OCCIException(ErrorType.QUOTA_EXCEEDED, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( - ManagerTestHelper.USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -278,36 +285,36 @@ public void testPersistentRequestSetOpen() throws InterruptedException { managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); List requests = managerController - .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); - requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); - Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + @Test - public void testPersistentRequestSetFulfilled() throws InterruptedException { + public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); @@ -322,13 +329,13 @@ public void testPersistentRequestSetFulfilled() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ManagerTestHelper.ACCESS_TOKEN_ID)).thenReturn( - ManagerTestHelper.USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -336,43 +343,267 @@ public void testPersistentRequestSetFulfilled() throws InterruptedException { managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ManagerTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); List requests = managerController - .getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(ManagerTestHelper.ACCESS_TOKEN_ID, INSTANCE_ID); + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); - requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); - Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - - //getting second instance + + // getting second instance Thread.sleep(SCHEDULER_PERIOD * 2); - requests = managerController.getRequestsFromUser(ManagerTestHelper.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } + + @Test + public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + String.valueOf(RequestType.PERSISTENT.getValue())); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( + USER_NAME); + + long expirationTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + String expirationDateStr = getDateISO8601Format(expirationTime); + + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + expirationDateStr); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + // creating request + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID_2); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + @Test + public void testPersistentRequestSetFulfilledAndOpenAndClosed() throws InterruptedException { + + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + String.valueOf(RequestType.PERSISTENT.getValue())); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( + USER_NAME); + + long expirationTime = System.currentTimeMillis() + 2 * SCHEDULER_PERIOD; + String expirationDateStr = getDateISO8601Format(expirationTime); + + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + expirationDateStr); + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + Thread.sleep(SCHEDULER_PERIOD); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getMemberId()); + + // removing instance + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + // getting second instance + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID_2); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + @Test + public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestConstants.DEFAULT_TYPE); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( + USER_NAME); + + long expirationTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + String expirationDateStr = getDateISO8601Format(expirationTime); + + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + expirationDateStr); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + // creating request + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + + private String getDateISO8601Format(long dateMili) { + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + String expirationDate = dateFormatISO8601.format(new Date(dateMili)); + return expirationDate; + } + } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index c60ba017..ef3171b8 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -45,9 +45,7 @@ public class ManagerTestHelper { private static final String CLIENT_PASS = "password"; private static final String SMACK_ENDING = "/Smack"; private static final Token TOKEN = new Token(new HashMap()); - public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; - public static final String USER_NAME = "user"; - + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String MANAGER_COMPONENT_PASS = "password"; @@ -59,6 +57,7 @@ public class ManagerTestHelper { public final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; + private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; From 812356a100b1f8c479238c3981de98ee55435648 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 9 May 2014 16:27:57 -0300 Subject: [PATCH 121/185] Implementing the Identity API v2.0 in OpenStackIdentityPlugin. fixes #45 --- .../openstack/OpenStackIdentityPlugin.java | 133 ++++++++++-------- .../occi/util/KeystoneApplication.java | 26 ++-- 2 files changed, 87 insertions(+), 72 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 2138a0be..c0fe8ca7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -1,13 +1,10 @@ package org.fogbowcloud.manager.core.plugins.openstack; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.codec.Charsets; -import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; @@ -17,6 +14,7 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; +import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -40,48 +38,51 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String EXPIRES_KEYSTONE = "expires"; public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; + private static final Logger LOGGER = Logger.getLogger(OpenStackIdentityPlugin.class); + private static final int LAST_SUCCESSFUL_STATUS = 204; - private static String V3_ENDPOINT_PATH = "/v3/auth/tokens/"; private static String V2_ENDPOINT_PATH = "/v2.0/tokens"; private String v2Endpoint; - private String v3Endpoint; public OpenStackIdentityPlugin(Properties properties) { String keystoneUrl = properties.getProperty("identity_openstack_url"); - this.v3Endpoint = keystoneUrl + V3_ENDPOINT_PATH; this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } + @Override + public String getTokenExpiresDate(String tokenId) { + return getUserDateExpirationTokenFromJson(getResponseJson(tokenId)); + } + public String getUser(String authToken) { + return getUserNameUserFromJson(getResponseJson(authToken)); + } + + public String getResponseJson(String authToken) { + HttpResponse response; + String responseStr = null; try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.v3Endpoint); + HttpGet httpGet = new HttpGet(this.v2Endpoint + "/" + authToken); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); - httpGet.addHeader(OCCIHeaders.X_SUBJECT_TOKEN, authToken); - HttpResponse response = httpCLient.execute(httpGet); - - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); - } - - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); - return getUserNameUserFromJson(responseStr); - } catch (IOException e) { - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } catch (URISyntaxException e){ - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } catch (HttpException e){ + response = httpCLient.execute(httpGet); + + responseStr = EntityUtils + .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); + } catch (Exception e) { + LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } + checkStatusResponse(response); + + return responseStr; } @Override public Token getToken(Map tokenAttributes) { + HttpResponse response; + String responseStr = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(this.v2Endpoint); @@ -96,57 +97,69 @@ public Token getToken(Map tokenAttributes) { tokenAttributes.get(OCCIHeaders.X_TOKEN_PASS)); JSONObject auth = new JSONObject(); auth.put(KEYSTONE_TENANT_NAME, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); - auth.put(PASSWORD_CREDENTIALS, passwordCredentials); + auth.put(PASSWORD_CREDENTIALS, passwordCredentials); JSONObject root = new JSONObject(); root.put(AUTH_KEYSTONE, auth); httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); - HttpResponse response = httpClient.execute(httpPost); - - String responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); - - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); - } - - return getTokenFromJson(responseStr); - } catch (IOException e) { - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } catch (URISyntaxException e){ - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } catch (HttpException e){ - throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } catch (JSONException e) { + response = httpClient.execute(httpPost); + + responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); + } catch (Exception e) { + LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); - } + } + checkStatusResponse(response); + + return getTokenFromJson(responseStr); + } + + private void checkStatusResponse(HttpResponse response) { + if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { + throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { + throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + } else if (response.getStatusLine().getStatusCode() > LAST_SUCCESSFUL_STATUS) { + throw new OCCIException(ErrorType.BAD_REQUEST, response.getStatusLine().toString()); + } } private String getUserNameUserFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - return root.getJSONObject(TOKEN_KEYSTONE).getJSONObject(USER_KEYSTONE) + return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) .getString(NAME_KEYSTONE); } catch (JSONException e) { return null; } } - private Token getTokenFromJson(String responseStr) throws JSONException { - Map attributes = new HashMap(); - JSONObject root = new JSONObject(responseStr); - JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE); - String token = tokenKeyStone.getString(ID_KEYSTONE); - String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE) - .getString(ID_KEYSTONE); - String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); - - attributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, token); - attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); - attributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDateToken); - - return new Token(attributes); + private String getUserDateExpirationTokenFromJson(String responseStr) { + try { + JSONObject root = new JSONObject(responseStr); + return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) + .getString(EXPIRES_KEYSTONE); + } catch (JSONException e) { + return null; + } } - public void setEnd(String end) { - this.v3Endpoint = end; + private Token getTokenFromJson(String responseStr) { + try { + Map attributes = new HashMap(); + JSONObject root = new JSONObject(responseStr); + JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( + TOKEN_KEYSTONE); + String token = tokenKeyStone.getString(ID_KEYSTONE); + String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); + String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); + + attributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, token); + attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); + attributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDateToken); + + return new Token(attributes); + } catch (Exception e) { + return null; + } } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 21b0c12d..b7355855 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -6,6 +6,8 @@ import org.apache.http.HttpStatus; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.json.JSONException; @@ -23,9 +25,9 @@ import org.restlet.routing.Router; public class KeystoneApplication extends Application { - - public static String TARGET_TOKENS = "/v3/auth/tokens/"; - public static String TARGET_AUTH_TOKEN = "/v2.0/tokens"; + + public static String TARGET_TOKEN_POST = "/v2.0/tokens"; + public static String TARGET_TOKEN_GET = "/v2.0/tokens/{tokenId}"; private Map tokenToUser; @@ -47,8 +49,8 @@ public KeystoneApplication(String usernameAdmin, String passwordAdmin, Token def @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); - router.attach(TARGET_TOKENS, KeystoneServer.class); - router.attach(TARGET_AUTH_TOKEN, KeystoneServer.class); + router.attach(TARGET_TOKEN_POST, KeystoneServer.class); + router.attach(TARGET_TOKEN_GET, KeystoneServer.class); return router; } @@ -84,7 +86,7 @@ public String fetch() { KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String token = req.getHeaders().getValues(OCCIHeaders.X_AUTH_TOKEN); - keyStoneApplication.checkUserByToken(token); + keyStoneApplication.checkUserByToken(token); String user = keyStoneApplication.getUserFromToken(token); return mountJSONResponseUserPerToken(token, user); } @@ -145,14 +147,14 @@ private String getUserFeatureCredentials(String jsonCredentials, String feature) } } - private String mountJSONResponseUserPerToken(String token, String user) { + private String mountJSONResponseUserPerToken(String token, String username) { try { - JSONObject nameObject = new JSONObject(); - nameObject.put(OpenStackIdentityPlugin.NAME_KEYSTONE, user); - JSONObject tokenObject = new JSONObject(); - tokenObject.put(OpenStackIdentityPlugin.USER_KEYSTONE, nameObject); + JSONObject usernameObject = new JSONObject(); + usernameObject.put(OpenStackIdentityPlugin.NAME_KEYSTONE, username); + JSONObject userObject = new JSONObject(); + userObject.put(OpenStackIdentityPlugin.USER_KEYSTONE, usernameObject); JSONObject accessObject = new JSONObject(); - accessObject.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, tokenObject); + accessObject.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, userObject); return accessObject.toString(); } catch (JSONException e) { } From ff4627da0db3b3ce9b18ba311d46bc0efae2e638 Mon Sep 17 00:00:00 2001 From: Giovanni Date: Fri, 9 May 2014 17:22:06 -0300 Subject: [PATCH 122/185] Implementing tests and request validity --- .../manager/core/ManagerController.java | 24 ++++++++++-- .../manager/occi/request/Request.java | 20 ++++++++++ .../occi/request/RequestServerResource.java | 3 ++ .../manager/core/TestManagerController.java | 37 ++++++++++--------- .../manager/occi/TestDeleteCompute.java | 3 ++ .../manager/occi/TestGetCompute.java | 3 ++ .../manager/occi/TestGetRequest.java | 3 ++ .../manager/occi/TestOCCIApplication.java | 3 ++ .../manager/occi/util/OCCITestHelper.java | 1 + 9 files changed, 76 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 2250d23d..9d337210 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -10,6 +10,8 @@ import java.util.TimerTask; import java.util.UUID; +import javax.management.modelmbean.RequiredModelMBean; + import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.model.FederationMember; @@ -31,6 +33,7 @@ import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.xmpp.ManagerPacketHelper; +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.jamppa.component.PacketSender; public class ManagerController { @@ -290,6 +293,12 @@ public void removeInstanceForRemoteMember(String instanceId) { public List createRequests(String authToken, List categories, Map xOCCIAtt) { String user = getUser(authToken); + String tokenExpiresDate = identityPlugin.getTokenExpiresDate(authToken); + + //TODO check if UNTIL is before token expires date + if (xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()) == null){ + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), tokenExpiresDate); + } Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT .getValue())); @@ -316,6 +325,11 @@ public List createRequests(String authToken, List categories, return currentRequests; } + private boolean validUntilDate(String string) { + // TODO Auto-generated method stub + return false; + } + private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(this); if (member == null) { @@ -386,10 +400,14 @@ private void checkAndSubmitOpenRequests() { for (Request request : requests.get(RequestState.OPEN)) { Map xOCCIAtt = request.getxOCCIAtt(); - for (String keyAttributes : RequestAttribute.getValues()) { - xOCCIAtt.remove(keyAttributes); + if (!request.isExpired()){ + for (String keyAttributes : RequestAttribute.getValues()) { + xOCCIAtt.remove(keyAttributes); + } + allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); + } else { + request.setState(RequestState.CLOSED); } - allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); } if (allFulfilled) { LOGGER.info("All request fulfilled."); diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 7379e5a5..390940b4 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -1,11 +1,17 @@ package org.fogbowcloud.manager.occi.request; +import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.TimeZone; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class Request { @@ -102,4 +108,18 @@ public String toString() { + instanceId + ", memberId: " + memberId + ", state: " + state + ", categories: " + categories + ", xOCCIAtt: " + xOCCIAtt; } + + public boolean isExpired() { + String expirationDateSrt = xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()); + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + long expirationDateMillis; + try { + expirationDateMillis = dateFormatISO8601.parse(expirationDateSrt).getTime(); + } catch (Exception e) { + return true; + } + return expirationDateMillis < new DateUtils().currentTimeMillis(); + } } \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java index 5243be0b..f32d78d7 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java @@ -81,6 +81,7 @@ public static Map normalizeXOCCIAtt(Map xOCCIAtt defOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); defOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), RequestConstants.DEFAULT_INSTANCE_COUNT.toString()); + //TODO add date default values defOCCIAtt.putAll(xOCCIAtt); @@ -89,6 +90,8 @@ public static Map normalizeXOCCIAtt(Map xOCCIAtt HeaderUtils.checkDateValue(defOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue())); HeaderUtils.checkIntegerValue(defOCCIAtt.get(RequestAttribute.INSTANCE_COUNT.getValue())); + //TODO check from is before until dates + List requestResources = ResourceRepository.getAll(); for (String attributeName : xOCCIAtt.keySet()) { boolean supportedAtt = false; diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index d446f09e..e5e43641 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -50,6 +50,7 @@ public class TestManagerController { public static final String ACCESS_TOKEN_ID_2 = "2222CVXV23T4TG42VVCV"; private static final Long GRACE_TIME = 30L; private static final String TENANT_NAME = "tenantName"; + private static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; @Before public void setUp() throws Exception { @@ -178,6 +179,8 @@ public void testGetRequestsByUser() throws InterruptedException { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -221,6 +224,8 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -278,6 +283,8 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -336,7 +343,9 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( USER_NAME); - + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); managerController.setIdentityPlugin(identityPlugin); @@ -452,7 +461,7 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException } @Test - public void testPersistentRequestSetFulfilledAndOpenAndClosed() throws InterruptedException { + public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); @@ -478,7 +487,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndClosed() throws Interrupt Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( USER_NAME); - long expirationTime = System.currentTimeMillis() + 2 * SCHEDULER_PERIOD; + long expirationTime = System.currentTimeMillis() + SCHEDULER_PERIOD + GRACE_TIME; String expirationDateStr = getDateISO8601Format(expirationTime); Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( @@ -503,22 +512,14 @@ public void testPersistentRequestSetFulfilledAndOpenAndClosed() throws Interrupt .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); - + + Thread.sleep(SCHEDULER_PERIOD); + // removing instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); - - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - - Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); - Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); - Assert.assertNull(requests.get(0).getInstanceId()); - Assert.assertNull(requests.get(0).getMemberId()); - - // getting second instance - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + managerController.removeInstance(ACCESS_TOKEN_ID_2, INSTANCE_ID); + Thread.sleep(SCHEDULER_PERIOD); + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID_2); Assert.assertEquals(1, requests.size()); @@ -598,7 +599,7 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { } - private String getDateISO8601Format(long dateMili) { + public static String getDateISO8601Format(long dateMili) { SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 31c6c9a9..db7c72ec 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -9,6 +9,7 @@ import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; @@ -38,6 +39,8 @@ public void setup() throws Exception { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); List requests = new LinkedList(); Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 3d01f340..aa5c0cf8 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -11,6 +11,7 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; +import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; @@ -54,6 +55,8 @@ public void setup() throws Exception { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); List requests = new LinkedList(); Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 62d78738..2adaf200 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -15,6 +15,7 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -53,6 +54,8 @@ public void setup() throws Exception { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 07e4e32f..2eab1624 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -7,6 +7,7 @@ import java.util.Properties; import org.fogbowcloud.manager.core.ManagerController; +import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; @@ -56,6 +57,8 @@ public void setUp() { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 3832fd14..51a0f79b 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -37,6 +37,7 @@ public class OCCITestHelper { public static final String URI_FOGBOW_QUERY = "http://localhost:8182/-/"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; + public static final long LONG_TIME = 24 * 60 * 60 * 1000; //one day private Component component; private RequestRepository requests; From 6883ad71b97509eea3bffce3b1b2171e60999fc5 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Mon, 12 May 2014 12:23:36 -0300 Subject: [PATCH 123/185] Fixing tests --- .../org/fogbowcloud/manager/occi/QueryServerResource.java | 2 +- src/main/java/org/fogbowcloud/manager/occi/core/Token.java | 7 ++++++- .../fogbowcloud/manager/core/TestManagerController.java | 6 ++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java index fd16d95b..7f3037cc 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/QueryServerResource.java @@ -22,7 +22,7 @@ public String fetch() { public String generateResponse(List allResources) { String response = ""; for (Resource resource : allResources) { - response += resource.toHeader() + "\n"; + response += "Category: " + resource.toHeader() + "\n"; } return response.trim(); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index 37ca5841..6fb30ee0 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -11,6 +11,7 @@ public class Token { private Map attributes; + private DateUtils dateUtils = new DateUtils(); public Token(Map attributes) { this.attributes = attributes; @@ -41,6 +42,10 @@ public boolean isExpiredToken() { } catch (Exception e) { return true; } - return expirationDateMillis < new DateUtils().currentTimeMillis(); + return expirationDateMillis < dateUtils.currentTimeMillis(); + } + + public void setDateUtils(DateUtils dateUtils){ + this.dateUtils = dateUtils; } } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index e5e43641..f40470c5 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -29,6 +29,7 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; @@ -58,7 +59,6 @@ public void setUp() throws Exception { managerTestHelper = new ManagerTestHelper(); } - // TODO mock date @Test public void testGetFederationMember() throws InterruptedException { Properties properties = new Properties(); @@ -107,7 +107,9 @@ public void testGetFederationMember() throws InterruptedException { OCCIHeaders.X_TOKEN_ACCESS_ID); Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); - Thread.sleep(300); + DateUtils dateUtils = Mockito.mock(DateUtils.class); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(expirationTime + GRACE_TIME); + token.setDateUtils(dateUtils); // Get new token accessToken = managerController.getFederationUserToken().get( From 9df11ac63f66709bd1a451bd26307910a1e671c5 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Mon, 12 May 2014 17:42:31 -0300 Subject: [PATCH 124/185] Implement request validity according to token validity --- .../manager/core/ManagerController.java | 14 +- .../manager/occi/core/HeaderUtils.java | 4 +- .../manager/occi/core/ResponseConstants.java | 1 + .../manager/occi/request/Request.java | 30 +- .../occi/request/RequestServerResource.java | 8 +- .../manager/core/TestManagerController.java | 337 +++++++++++++++++- 6 files changed, 373 insertions(+), 21 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 9d337210..2ebba677 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -321,15 +321,9 @@ public List createRequests(String authToken, List categories, if (!scheduled) { scheduleRequests(); } - return currentRequests; } - private boolean validUntilDate(String string) { - // TODO Auto-generated method stub - return false; - } - private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(this); if (member == null) { @@ -399,14 +393,16 @@ private void checkAndSubmitOpenRequests() { LOGGER.debug("Checking and submiting requests."); for (Request request : requests.get(RequestState.OPEN)) { - Map xOCCIAtt = request.getxOCCIAtt(); - if (!request.isExpired()){ + Map xOCCIAtt = request.getxOCCIAtt(); + if (request.isIntoValidPeriod()){ for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); - } else { + } else if (request.isExpired()){ request.setState(RequestState.CLOSED); + } else { + allFulfilled = false; } } if (allFulfilled) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java b/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java index 28a7d2a3..2b93512f 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java @@ -4,6 +4,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -13,6 +14,7 @@ public class HeaderUtils { + public static final String REQUEST_DATE_FORMAT = "yyyy-MM-dd"; public static final String X_OCCI_LOCATION = "X-OCCI-Location: "; public static void checkOCCIContentType(Series
headers) { @@ -112,7 +114,7 @@ public static void checkCategories(List categories, String mandatoryTe public static void checkDateValue(String dataString) { try { if (dataString != null && !dataString.equals("")) { - DateFormat formatter = new SimpleDateFormat("yy-MM-dd"); + DateFormat formatter = new SimpleDateFormat(REQUEST_DATE_FORMAT); formatter.parse(dataString); } } catch (ParseException e) { diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java index b43a778c..f1bfeaef 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/ResponseConstants.java @@ -11,5 +11,6 @@ public class ResponseConstants { public static final String COULD_NOT_CREATE_TUNNEL = "SSH tunnel could not be created."; public static final String INVALID_OS_TEMPLATE = "Please provide a valid OS Template."; public static final String QUOTA_EXCEEDED_FOR_INSTANCES = "Quota exceeded"; + public static final String INVALID_DATE_ATTRIBUTES = "Invalid valid from and valid until attributes."; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 390940b4..501f0a9c 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.occi.request; import java.text.SimpleDateFormat; +import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -10,7 +11,6 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class Request { @@ -109,17 +109,37 @@ public String toString() { + categories + ", xOCCIAtt: " + xOCCIAtt; } - public boolean isExpired() { + public boolean isIntoValidPeriod() { + String startDateStr = xOCCIAtt.get(RequestAttribute.VALID_FROM.getValue()); + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + long startDateMillis; + try { + if (startDateStr != null){ + startDateMillis = dateFormatISO8601.parse(startDateStr).getTime(); + } else { + startDateMillis = new DateUtils().currentTimeMillis(); + } + } catch (Exception e) { + return false; + } + long now = new DateUtils().currentTimeMillis(); + return startDateMillis <= now && !isExpired(); + } + + public boolean isExpired() { String expirationDateSrt = xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()); SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - long expirationDateMillis; + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + long expirationDateMillis; try { expirationDateMillis = dateFormatISO8601.parse(expirationDateSrt).getTime(); } catch (Exception e) { return true; } - return expirationDateMillis < new DateUtils().currentTimeMillis(); + long now = new DateUtils().currentTimeMillis(); + return expirationDateMillis < now; } } \ No newline at end of file diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java index f32d78d7..7922a1c1 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java @@ -81,7 +81,6 @@ public static Map normalizeXOCCIAtt(Map xOCCIAtt defOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); defOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), RequestConstants.DEFAULT_INSTANCE_COUNT.toString()); - //TODO add date default values defOCCIAtt.putAll(xOCCIAtt); @@ -90,8 +89,6 @@ public static Map normalizeXOCCIAtt(Map xOCCIAtt HeaderUtils.checkDateValue(defOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue())); HeaderUtils.checkIntegerValue(defOCCIAtt.get(RequestAttribute.INSTANCE_COUNT.getValue())); - //TODO check from is before until dates - List requestResources = ResourceRepository.getAll(); for (String attributeName : xOCCIAtt.keySet()) { boolean supportedAtt = false; @@ -118,12 +115,13 @@ protected static void checkRequestType(String enumString) { } throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - + protected static String generateResponse(List requests, HttpRequest req) { String requestEndpoint = req.getHostRef() + req.getHttpCall().getRequestUri(); String response = ""; for (Request request : requests) { - response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + request.getId() + "\n"; + response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + request.getId() + + "\n"; } if (response.equals("")) { response = "Empty"; diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index f40470c5..2370e470 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -598,8 +598,344 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + } + @Test + public void testOneTimeRequestValidFromInFuture() throws InterruptedException { + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + long now = System.currentTimeMillis(); + long startRequestTime = now + (SCHEDULER_PERIOD * 2); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + String.valueOf(RequestType.ONE_TIME.getValue())); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(now + LONG_TIME)); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + // creating request + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + //request is not in validity period yet + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //request is in validity period + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + @Test + public void testPersistentRequestValidFromInFuture() throws InterruptedException { + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + long now = System.currentTimeMillis(); + long startRequestTime = now + (SCHEDULER_PERIOD * 2); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestType.PERSISTENT.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(now + LONG_TIME)); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + // creating request + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + //request is not in validity period yet + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //request is in validity period + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + @Test + public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + long now = System.currentTimeMillis(); + long startRequestTime = now + (SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (SCHEDULER_PERIOD * 3); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestType.ONE_TIME.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + getDateISO8601Format(expirationRequestTime)); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(now + LONG_TIME)); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + // creating request + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + //request is not in validity period yet + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //request is in validity period + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + //remove instance + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //request is not in validity period anymore + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } + + @Test + public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { + Properties properties = new Properties(); + properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + long now = System.currentTimeMillis(); + long startRequestTime = now + (SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (SCHEDULER_PERIOD * 3); + + // default instance count value is 1 + Map xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestType.PERSISTENT.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + getDateISO8601Format(expirationRequestTime)); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( + getDateISO8601Format(now + LONG_TIME)); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + // creating request + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); + + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + //request is not in validity period yet + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //request is in validity period + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); + Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //remove instance + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + + //request is not in validity period anymore + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + Assert.assertEquals(1, requests.size()); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); + Assert.assertNull(requests.get(0).getInstanceId()); + Assert.assertNull(requests.get(0).getMemberId()); + } public static String getDateISO8601Format(long dateMili) { SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( @@ -608,5 +944,4 @@ public static String getDateISO8601Format(long dateMili) { String expirationDate = dateFormatISO8601.format(new Date(dateMili)); return expirationDate; } - } From 2eb45bc5f814e382e84e4e12df6024542a18cb8a Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 13 May 2014 10:19:16 -0300 Subject: [PATCH 125/185] Implementing UpdateToken. --- .../manager/core/plugins/IdentityPlugin.java | 4 +- .../openstack/OpenStackIdentityPlugin.java | 48 ++++++++++--- .../occi/plugins/TestIdentityOpenStack.java | 28 +++++++- .../occi/util/KeystoneApplication.java | 69 ++++++++++++++----- .../manager/occi/util/PluginHelper.java | 9 ++- 5 files changed, 130 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index 2dbe64f0..f75b62e7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -10,5 +10,7 @@ public interface IdentityPlugin { public String getTokenExpiresDate(String tokenId); - public Token getToken(Map tokenAttributes); + public Token getToken(Map tokenCredentials); + + public Token updateToken(Map tokenAttributes); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index c0fe8ca7..5a09fb91 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -26,10 +26,10 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { - private static final String KEYSTONE_TENANT_NAME = "tenantName"; - public static final String KEYSTONE_USERNAME = "username"; - public static final String KEYSTONE_PASSWORD = "password"; - public static final String PASSWORD_CREDENTIALS = "passwordCredentials"; + public static final String TENANT_NAME_KEYSTONE = "tenantName"; + public static final String USERNAME_KEYSTONE = "username"; + public static final String PASSWORD_KEYSTONE = "password"; + public static final String PASSWORD_CREDENTIALS_KEYSTONE = "passwordCredentials"; public static final String AUTH_KEYSTONE = "auth"; public static final String TOKEN_KEYSTONE = "token"; public static final String ID_KEYSTONE = "id"; @@ -91,13 +91,45 @@ public Token getToken(Map tokenAttributes) { httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); JSONObject passwordCredentials = new JSONObject(); - passwordCredentials.put(KEYSTONE_USERNAME, + passwordCredentials.put(USERNAME_KEYSTONE, tokenAttributes.get(OCCIHeaders.X_TOKEN_USER)); - passwordCredentials.put(KEYSTONE_PASSWORD, + passwordCredentials.put(PASSWORD_KEYSTONE, tokenAttributes.get(OCCIHeaders.X_TOKEN_PASS)); JSONObject auth = new JSONObject(); - auth.put(KEYSTONE_TENANT_NAME, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); - auth.put(PASSWORD_CREDENTIALS, passwordCredentials); + auth.put(TENANT_NAME_KEYSTONE, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); + auth.put(PASSWORD_CREDENTIALS_KEYSTONE, passwordCredentials); + JSONObject root = new JSONObject(); + root.put(AUTH_KEYSTONE, auth); + httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); + response = httpClient.execute(httpPost); + + responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); + } catch (Exception e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } + checkStatusResponse(response); + + return getTokenFromJson(responseStr); + } + + @Override + public Token updateToken(Map tokenAttributes) { + HttpResponse response; + String responseStr = null; + try { + HttpClient httpClient = new DefaultHttpClient(); + HttpPost httpPost = new HttpPost(this.v2Endpoint); + + httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); + httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); + + JSONObject idToken = new JSONObject(); + idToken.put(ID_KEYSTONE, + tokenAttributes.get(OCCIHeaders.X_TOKEN_ACCESS_ID)); + JSONObject auth = new JSONObject(); + auth.put(TENANT_NAME_KEYSTONE, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); + auth.put(TOKEN_KEYSTONE, idToken); JSONObject root = new JSONObject(); root.put(AUTH_KEYSTONE, auth); httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 18a2fcb5..904a89c7 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -62,7 +62,7 @@ public void testGetToken() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, "admin"); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANTNAME_FOGBOW); Token token = this.identityOpenStack.getToken(tokenAttributes); String authToken = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); @@ -72,6 +72,32 @@ public void testGetToken() { Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); } + @Test + public void testUpgradeToken() { + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANTNAME_FOGBOW); + Token token = this.identityOpenStack.getToken(tokenAttributes); + String authToken = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); + String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); + Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); + + Map tokenAttributes2 = new HashMap(); + tokenAttributes2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, PluginHelper.VALID_TOKEN); + tokenAttributes2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANTNAME_FOGBOW); + Token token2 = this.identityOpenStack.updateToken(tokenAttributes2); + authToken = token2.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + tenantID = token2.get(OCCIHeaders.X_TOKEN_TENANT_ID); + expirationDate = token2.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); + Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); + } + @Test(expected = OCCIException.class) public void testGetTokenWrongUsername() { Map tokenAttributes = new HashMap(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index b7355855..85fd3a0f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -6,8 +6,6 @@ import org.apache.http.HttpStatus; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; -import org.fogbowcloud.manager.occi.core.ErrorType; -import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.json.JSONException; @@ -25,7 +23,7 @@ import org.restlet.routing.Router; public class KeystoneApplication extends Application { - + public static String TARGET_TOKEN_POST = "/v2.0/tokens"; public static String TARGET_TOKEN_GET = "/v2.0/tokens/{tokenId}"; @@ -33,14 +31,19 @@ public class KeystoneApplication extends Application { private String usernameAdmin; private String passwordAdmin; + private String tenantName; + private String validToken; private Token defaultToken; public KeystoneApplication() { this.tokenToUser = new HashMap(); } - public KeystoneApplication(String usernameAdmin, String passwordAdmin, Token defaultToken) { + public KeystoneApplication(String usernameAdmin, String passwordAdmin, String tenantName, + String validToken, Token defaultToken) { this.tokenToUser = new HashMap(); + this.tenantName = tenantName; + this.validToken = validToken; this.usernameAdmin = usernameAdmin; this.passwordAdmin = passwordAdmin; this.defaultToken = defaultToken; @@ -69,8 +72,15 @@ public void checkUserByToken(String token) { } } - public void authenticationCheck(String username, String password) { - if (!this.usernameAdmin.equals(username) || !this.passwordAdmin.equals(password)) { + public void authenticationCheckToken(String idToken, String tenantName) { + if (!this.validToken.equals(idToken) || !this.tenantName.equals(tenantName)) { + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); + } + } + + public void checkAuthenticationCredentials(String username, String password, String tenantName) { + if (!this.usernameAdmin.equals(username) || !this.passwordAdmin.equals(password) + || !this.tenantName.equals(tenantName)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } @@ -86,7 +96,7 @@ public String fetch() { KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String token = req.getHeaders().getValues(OCCIHeaders.X_AUTH_TOKEN); - keyStoneApplication.checkUserByToken(token); + keyStoneApplication.checkUserByToken(token); String user = keyStoneApplication.getUserFromToken(token); return mountJSONResponseUserPerToken(token, user); } @@ -101,16 +111,22 @@ public Representation post(Representation entity) { } catch (IOException e) { } - String username = getUserFeatureCredentials(jsonCredentials, - OpenStackIdentityPlugin.KEYSTONE_USERNAME); - String password = getUserFeatureCredentials(jsonCredentials, - OpenStackIdentityPlugin.KEYSTONE_PASSWORD); - - keyStoneApplication.authenticationCheck(username, password); + String tenantNname = getTenantName(jsonCredentials); + String idToken = getIdToken(jsonCredentials); + if (idToken != null) { + keyStoneApplication.authenticationCheckToken(idToken, tenantNname); + } else { + String username = getUserFeatureCredentials(jsonCredentials, + OpenStackIdentityPlugin.USERNAME_KEYSTONE); + String password = getUserFeatureCredentials(jsonCredentials, + OpenStackIdentityPlugin.PASSWORD_KEYSTONE); + + keyStoneApplication.checkAuthenticationCredentials(username, password, tenantNname); + } return new StringRepresentation( mountJSONResponseAuthenticateToken(keyStoneApplication.getDefaultToken()), - MediaType.TEXT_ALL); + MediaType.TEXT_ALL); } private String mountJSONResponseAuthenticateToken(Token token) { @@ -118,7 +134,7 @@ private String mountJSONResponseAuthenticateToken(Token token) { String tokenId = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); String tenantId = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); - + JSONObject rootIdTenantToken = new JSONObject(); rootIdTenantToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tenantId); JSONObject rootIdToken = new JSONObject(); @@ -136,11 +152,32 @@ private String mountJSONResponseAuthenticateToken(Token token) { return null; } + private String getIdToken(String jsonCredentials) { + try { + JSONObject root = new JSONObject(jsonCredentials); + return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) + .getJSONObject(OpenStackIdentityPlugin.TOKEN_KEYSTONE) + .getString(OpenStackIdentityPlugin.ID_KEYSTONE).toString(); + } catch (JSONException e) { + return null; + } + } + + private String getTenantName(String jsonCredentials) { + try { + JSONObject root = new JSONObject(jsonCredentials); + return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) + .getString(OpenStackIdentityPlugin.TENANT_NAME_KEYSTONE).toString(); + } catch (JSONException e) { + return null; + } + } + private String getUserFeatureCredentials(String jsonCredentials, String feature) { try { JSONObject root = new JSONObject(jsonCredentials); return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) - .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS) + .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS_KEYSTONE) .getString(feature).toString(); } catch (JSONException e) { return null; diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 92ceb4b3..0c91b5f5 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -4,6 +4,8 @@ import java.util.List; import java.util.Map; +import javax.swing.text.TabableView; + import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; @@ -16,10 +18,12 @@ public class PluginHelper { private Component component; public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; + public static final String VALID_TOKEN = "JgY45SDNFfdh348by89byfjhihjfjhfccv"; public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; public static final String EXPIRATION_DATA = "2014-01-31T15:30:58Z"; public static final String USERNAME_FOGBOW = "admin"; public static final String PASSWORD_FOGBOW = "reverse"; + public static final String TENANTNAME_FOGBOW = "admin"; public static final int PORT_ENDPOINT = 8182; @@ -37,8 +41,9 @@ public void initializeKeystoneComponent() throws Exception { tokenAttributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, EXPIRATION_DATA); Token token = new Token(tokenAttributes); - KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW, - token); + KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW + , TENANTNAME_FOGBOW, VALID_TOKEN, token); + keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); this.component.getDefaultHost().attach(keystoneApplication); From 879631f7893efb79168930ae53ff7250818fd985 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 13 May 2014 11:30:35 -0300 Subject: [PATCH 126/185] Fixing test to consider request validity to infinite. --- .../manager/core/ManagerController.java | 9 +- .../manager/occi/request/Request.java | 4 +- .../manager/core/TestManagerController.java | 457 +++++++----------- .../manager/occi/TestDeleteCompute.java | 2 - .../manager/occi/TestGetCompute.java | 2 - .../manager/occi/TestGetRequest.java | 3 - .../manager/occi/TestOCCIApplication.java | 2 - .../occi/plugins/TestIdentityOpenStack.java | 6 +- .../manager/occi/util/PluginHelper.java | 4 +- 9 files changed, 197 insertions(+), 292 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 2ebba677..0197b3a9 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.core; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -10,8 +11,6 @@ import java.util.TimerTask; import java.util.UUID; -import javax.management.modelmbean.RequiredModelMBean; - import org.apache.http.HttpStatus; import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.model.FederationMember; @@ -33,7 +32,6 @@ import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.xmpp.ManagerPacketHelper; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.jamppa.component.PacketSender; public class ManagerController { @@ -295,11 +293,6 @@ public List createRequests(String authToken, List categories, String user = getUser(authToken); String tokenExpiresDate = identityPlugin.getTokenExpiresDate(authToken); - //TODO check if UNTIL is before token expires date - if (xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()) == null){ - xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), tokenExpiresDate); - } - Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT .getValue())); LOGGER.info("Request " + instanceCount + " instances"); diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 501f0a9c..ed0ab704 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -1,7 +1,6 @@ package org.fogbowcloud.manager.occi.request; import java.text.SimpleDateFormat; -import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -130,6 +129,9 @@ public boolean isIntoValidPeriod() { public boolean isExpired() { String expirationDateSrt = xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()); + if (expirationDateSrt == null){ + return false; + } SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 2370e470..e7e8002d 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -78,33 +78,27 @@ public void testGetFederationMember() throws InterruptedException { String expirationDateStr = getDateISO8601Format(expirationTime); Map attributesTokenReturn = new HashMap(); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_ACCESS_ID, - ACCESS_TOKEN_ID); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_TOKEN_ID); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, - expirationDateStr); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDateStr); Token token = new Token(attributesTokenReturn); Map attributesTokenReturn2 = new HashMap(); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, - ACCESS_TOKEN_ID_2); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_TOKEN_ID_2); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, "data"); Token token2 = new Token(attributesTokenReturn2); - Mockito.when(openStackidentityPlugin.getToken(attributesToken)) - .thenReturn(token, token2); + Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token Token federationUserToken = managerController.getFederationUserToken(); - String accessToken = federationUserToken - .get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String accessToken = federationUserToken.get(OCCIHeaders.X_TOKEN_ACCESS_ID); Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); // Use member token - accessToken = managerController.getFederationUserToken().get( - OCCIHeaders.X_TOKEN_ACCESS_ID); + accessToken = managerController.getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); @@ -112,8 +106,7 @@ public void testGetFederationMember() throws InterruptedException { token.setDateUtils(dateUtils); // Get new token - accessToken = managerController.getFederationUserToken().get( - OCCIHeaders.X_TOKEN_ACCESS_ID); + accessToken = managerController.getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); Assert.assertEquals(ACCESS_TOKEN_ID_2, accessToken); } @@ -130,8 +123,7 @@ public void testGet0ItemsFromIQ() { @Test public void testGet1ItemFromIQ() throws CertificateException, IOException { - FederationMember managerItem = new FederationMember( - managerTestHelper.getResources()); + FederationMember managerItem = new FederationMember(managerTestHelper.getResources()); List items = new LinkedList(); items.add(managerItem); managerController.updateMembers(items); @@ -143,8 +135,7 @@ public void testGet1ItemFromIQ() throws CertificateException, IOException { } @Test - public void testGetManyItemsFromIQ() throws CertificateException, - IOException { + public void testGetManyItemsFromIQ() throws CertificateException, IOException { ArrayList items = new ArrayList(); for (int i = 0; i < 10; i++) { items.add(new FederationMember(managerTestHelper.getResources())); @@ -154,8 +145,7 @@ public void testGetManyItemsFromIQ() throws CertificateException, List members = managerController.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { - Assert.assertEquals("abc", members.get(0).getResourcesInfo() - .getId()); + Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); } Assert.assertEquals(10, managerController.getMembers().size()); } @@ -174,15 +164,11 @@ public void testGetRequestsByUser() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -190,13 +176,11 @@ public void testGetRequestsByUser() throws InterruptedException { managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD * 2); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(USER_NAME, requests.get(0).getUser()); @@ -219,15 +203,11 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -235,13 +215,11 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); @@ -275,18 +253,15 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))) .thenReturn(INSTANCE_ID) .thenThrow( new OCCIException(ErrorType.QUOTA_EXCEEDED, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -294,18 +269,16 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); @@ -315,8 +288,8 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -338,34 +311,28 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(System.currentTimeMillis() + LONG_TIME)); - + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); managerController.setIdentityPlugin(identityPlugin); managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); @@ -375,8 +342,8 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -388,8 +355,8 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } @@ -400,34 +367,28 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); + long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + String.valueOf(getDateISO8601Format(expirationRequestTime))); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( - USER_NAME); - - long expirationTime = System.currentTimeMillis() + SCHEDULER_PERIOD; - String expirationDateStr = getDateISO8601Format(expirationTime); - - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - expirationDateStr); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -437,26 +398,24 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID_2); + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -469,103 +428,90 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); + long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD + GRACE_TIME; + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + getDateISO8601Format(expirationRequestTime)); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( - USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - long expirationTime = System.currentTimeMillis() + SCHEDULER_PERIOD + GRACE_TIME; - String expirationDateStr = getDateISO8601Format(expirationTime); - - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - expirationDateStr); + // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); managerController.setIdentityPlugin(identityPlugin); managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); - - Thread.sleep(SCHEDULER_PERIOD); - + + Thread.sleep(SCHEDULER_PERIOD); + // removing instance - managerController.removeInstance(ACCESS_TOKEN_ID_2, INSTANCE_ID); + managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); Thread.sleep(SCHEDULER_PERIOD); - - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID_2); + + requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + @Test public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); + long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), - RequestConstants.DEFAULT_TYPE); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID_2)).thenReturn( - USER_NAME); - - long expirationTime = System.currentTimeMillis() + SCHEDULER_PERIOD; - String expirationDateStr = getDateISO8601Format(expirationTime); - - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - expirationDateStr); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -575,15 +521,13 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -593,14 +537,14 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + @Test public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -609,29 +553,27 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { long now = System.currentTimeMillis(); long startRequestTime = now + (SCHEDULER_PERIOD * 2); - + long expirationRequestTime = now + LONG_TIME; + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.ONE_TIME.getValue())); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), - getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(now + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -641,15 +583,13 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -658,27 +598,27 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - //request is not in validity period yet + // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //request is in validity period + + // request is in validity period requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - + Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + @Test public void testPersistentRequestValidFromInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -687,29 +627,26 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException long now = System.currentTimeMillis(); long startRequestTime = now + (SCHEDULER_PERIOD * 2); - + long expirationRequestTime = now + LONG_TIME; + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), - RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), - getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(now + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -719,15 +656,13 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -736,27 +671,27 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - //request is not in validity period yet + // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //request is in validity period + + // request is in validity period requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - + Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + @Test public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -766,31 +701,25 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti long now = System.currentTimeMillis(); long startRequestTime = now + (SCHEDULER_PERIOD * 2); long expirationRequestTime = now + (SCHEDULER_PERIOD * 3); - + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), - RequestType.ONE_TIME.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), - getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(now + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -800,52 +729,50 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - //request is not in validity period yet + // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //request is in validity period + + // request is in validity period requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - + Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - - //remove instance + + // remove instance managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); - + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //request is not in validity period anymore + + // request is not in validity period anymore requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - + Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + @Test public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -855,31 +782,25 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce long now = System.currentTimeMillis(); long startRequestTime = now + (SCHEDULER_PERIOD * 2); long expirationRequestTime = now + (SCHEDULER_PERIOD * 3); - + // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), - RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), - getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( - USER_NAME); - Mockito.when(identityPlugin.getTokenExpiresDate(ACCESS_TOKEN_ID)).thenReturn( - getDateISO8601Format(now + LONG_TIME)); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -889,54 +810,52 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, - new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - //request is not in validity period yet + // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //request is in validity period + + // request is in validity period requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - + Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - + Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //remove instance + + // remove instance managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); - - //request is not in validity period anymore + + // request is not in validity period anymore requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - + Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) - .getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), + requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - + public static String getDateISO8601Format(long dateMili) { SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index db7c72ec..4669071f 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -39,8 +39,6 @@ public void setup() throws Exception { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); List requests = new LinkedList(); Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index aa5c0cf8..c75da446 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -55,8 +55,6 @@ public void setup() throws Exception { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); List requests = new LinkedList(); Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 2adaf200..62d78738 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -15,7 +15,6 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; -import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -54,8 +53,6 @@ public void setup() throws Exception { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 2eab1624..78f2cc24 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -57,8 +57,6 @@ public void setUp() { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getTokenExpiresDate(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - TestManagerController.getDateISO8601Format(System.currentTimeMillis() + OCCITestHelper.LONG_TIME)); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 904a89c7..64aad4a1 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -69,7 +69,7 @@ public void testGetToken() { String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); + Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); } @Test @@ -84,7 +84,7 @@ public void testUpgradeToken() { String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); + Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); Map tokenAttributes2 = new HashMap(); tokenAttributes2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, PluginHelper.VALID_TOKEN); @@ -95,7 +95,7 @@ public void testUpgradeToken() { expirationDate = token2.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(PluginHelper.EXPIRATION_DATA, expirationDate); + Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); } @Test(expected = OCCIException.class) diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 0c91b5f5..b5561d87 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -20,7 +20,7 @@ public class PluginHelper { public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; public static final String VALID_TOKEN = "JgY45SDNFfdh348by89byfjhihjfjhfccv"; public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; - public static final String EXPIRATION_DATA = "2014-01-31T15:30:58Z"; + public static final String EXPIRATION_DATE = "2014-01-31T15:30:58Z"; public static final String USERNAME_FOGBOW = "admin"; public static final String PASSWORD_FOGBOW = "reverse"; public static final String TENANTNAME_FOGBOW = "admin"; @@ -38,7 +38,7 @@ public void initializeKeystoneComponent() throws Exception { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, AUTH_TOKEN); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); - tokenAttributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, EXPIRATION_DATA); + tokenAttributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, EXPIRATION_DATE); Token token = new Token(tokenAttributes); KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW From e3d67e5a149ec9e30cab523b30b6ebd12a4538b8 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 14 May 2014 12:29:50 -0300 Subject: [PATCH 127/185] Refactoring Request class to store token instead tokenId and fixing tests --- .../manager/core/ManagerController.java | 17 ++-- .../manager/core/plugins/IdentityPlugin.java | 5 +- .../openstack/OpenStackComputePlugin.java | 5 +- .../openstack/OpenStackIdentityPlugin.java | 98 ++++++++++++------- .../manager/occi/TokenServerResource.java | 6 +- .../manager/occi/core/OCCIHeaders.java | 2 - .../fogbowcloud/manager/occi/core/Token.java | 46 ++++----- .../manager/occi/request/Request.java | 16 ++- .../manager/core/TestManagerController.java | 41 +++++--- .../manager/occi/TestDeleteCompute.java | 34 +++---- .../manager/occi/TestGetCompute.java | 97 +++++++++--------- .../manager/occi/TestGetRequest.java | 9 ++ .../manager/occi/TestOCCIApplication.java | 9 +- .../manager/occi/TestTokenServerResource.java | 35 +++---- .../occi/plugins/TestIdentityOpenStack.java | 22 ++--- .../occi/util/KeystoneApplication.java | 29 ++++-- .../manager/occi/util/OCCITestHelper.java | 5 +- .../manager/occi/util/PluginHelper.java | 24 ++--- .../xmpp/TestDeleteRemoteInstance.java | 13 ++- .../manager/xmpp/TestGetRemoteInstance.java | 11 ++- .../xmpp/TestRequestRemoteInstance.java | 5 +- .../manager/xmpp/util/ManagerTestHelper.java | 27 ++--- 22 files changed, 329 insertions(+), 227 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 0197b3a9..866199a7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -1,7 +1,6 @@ package org.fogbowcloud.manager.core; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -42,7 +41,7 @@ public class ManagerController { private boolean scheduled = false; private Timer timer; - private Token tokenMemberLocal = new Token(new HashMap()); + private Token tokenMemberLocal; private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); private FederationMemberPicker memberPicker = new RoundRobinMemberPicker(); @@ -241,7 +240,7 @@ public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); - String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId();//(OCCIHeaders.X_TOKEN_ACCESS_ID); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); } catch (OCCIException e) { @@ -261,7 +260,7 @@ protected Token getFederationUserToken() { tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - if (tokenMemberLocal.isExpiredToken()) { + if (tokenMemberLocal == null || tokenMemberLocal.isExpiredToken()) { Token token = identityPlugin.getToken(tokenAttributes); this.tokenMemberLocal = token; } @@ -270,7 +269,7 @@ protected Token getFederationUserToken() { public Instance getInstanceForRemoteMember(String instanceId) { LOGGER.info("Getting instance " + instanceId + " for remote member."); - String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId();//get(OCCIHeaders.X_TOKEN_ACCESS_ID); try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { @@ -284,14 +283,16 @@ public Instance getInstanceForRemoteMember(String instanceId) { public void removeInstanceForRemoteMember(String instanceId) { LOGGER.info("Removing instance " + instanceId + " for remote member."); - String token = getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId();//(OCCIHeaders.X_TOKEN_ACCESS_ID); computePlugin.removeInstance(token, instanceId); } public List createRequests(String authToken, List categories, Map xOCCIAtt) { String user = getUser(authToken); - String tokenExpiresDate = identityPlugin.getTokenExpiresDate(authToken); + + Token userToken = identityPlugin.getToken(authToken); + LOGGER.debug("User Token: " + userToken); Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT .getValue())); @@ -300,7 +301,7 @@ public List createRequests(String authToken, List categories, List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, authToken, user, categories, xOCCIAtt); + Request request = new Request(requestId, userToken, user, categories, xOCCIAtt); try { sshTunnel.create(properties, request); } catch (Exception e) { diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index f75b62e7..06158bb7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -4,6 +4,7 @@ import org.fogbowcloud.manager.occi.core.Token; +//TODO Refactor review the need of methods public interface IdentityPlugin { public String getUser(String tokenId); @@ -12,5 +13,7 @@ public interface IdentityPlugin { public Token getToken(Map tokenCredentials); - public Token updateToken(Map tokenAttributes); + public Token updateToken(Token token); + + public Token getToken(String authToken); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 97df11f1..8967431f 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -46,7 +46,6 @@ public class OpenStackComputePlugin implements ComputePlugin { private static final String ABSOLUTE = "absolute"; private static final String LIMITS = "limits"; - private static final Logger LOGGER = Logger.getLogger(OpenStackComputePlugin.class); private static final String TERM_COMPUTE = "compute"; private static final String CLASS_COMPUTE = "kind"; private static final String COMPUTE_ENDPOINT = "/compute/"; @@ -61,6 +60,8 @@ public class OpenStackComputePlugin implements ComputePlugin { private String computeV2APIEndpoint; private Map fogTermToOpensStackCategory = new HashMap(); + private static final Logger LOGGER = Logger.getLogger(OpenStackComputePlugin.class); + public OpenStackComputePlugin(Properties properties) { this.computeOCCIEndpoint = properties.getProperty("compute_openstack_occi_url") + COMPUTE_ENDPOINT; @@ -174,7 +175,7 @@ public ResourcesInfo getResourcesInfo(Token token) { String responseStr = doRequest( "get", computeV2APIEndpoint + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) - + "/limits", token.get(OCCIHeaders.X_TOKEN_ACCESS_ID)).getResponseString(); + + "/limits", token.getAccessId()).getResponseString(); String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); String cpuInUse = getAttFromJson(TOTAL_CORES_USED_ATT, responseStr); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 5a09fb91..d039813c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -1,8 +1,12 @@ package org.fogbowcloud.manager.core.plugins.openstack; +import java.text.SimpleDateFormat; +import java.util.Date; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Properties; +import java.util.TimeZone; import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; @@ -15,13 +19,13 @@ import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; -import org.json.JSONException; import org.json.JSONObject; public class OpenStackIdentityPlugin implements IdentityPlugin { @@ -52,20 +56,22 @@ public OpenStackIdentityPlugin(Properties properties) { @Override public String getTokenExpiresDate(String tokenId) { - return getUserDateExpirationTokenFromJson(getResponseJson(tokenId)); + Token token = getToken(tokenId); + return token.getExpirationDate().toString(); } - public String getUser(String authToken) { - return getUserNameUserFromJson(getResponseJson(authToken)); + public String getUser(String tokenId) { + Token token = getToken(tokenId); + return token.get(OCCIHeaders.X_TOKEN_USER); } - public String getResponseJson(String authToken) { + public String getResponseJson(String tokenId) { HttpResponse response; String responseStr = null; try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.v2Endpoint + "/" + authToken); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, authToken); + HttpGet httpGet = new HttpGet(this.v2Endpoint + "/" + tokenId); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, tokenId); response = httpCLient.execute(httpGet); responseStr = EntityUtils @@ -112,9 +118,9 @@ public Token getToken(Map tokenAttributes) { return getTokenFromJson(responseStr); } - + @Override - public Token updateToken(Map tokenAttributes) { + public Token updateToken(Token token) { HttpResponse response; String responseStr = null; try { @@ -125,10 +131,9 @@ public Token updateToken(Map tokenAttributes) { httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); JSONObject idToken = new JSONObject(); - idToken.put(ID_KEYSTONE, - tokenAttributes.get(OCCIHeaders.X_TOKEN_ACCESS_ID)); + idToken.put(ID_KEYSTONE, token.getAccessId()); JSONObject auth = new JSONObject(); - auth.put(TENANT_NAME_KEYSTONE, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); + auth.put(TENANT_NAME_KEYSTONE, token.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); auth.put(TOKEN_KEYSTONE, idToken); JSONObject root = new JSONObject(); root.put(AUTH_KEYSTONE, auth); @@ -155,43 +160,68 @@ private void checkStatusResponse(HttpResponse response) { } } - private String getUserNameUserFromJson(String responseStr) { + private Token getTokenFromJson(String responseStr) { try { + Map attributes = new HashMap(); JSONObject root = new JSONObject(responseStr); - return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) - .getString(NAME_KEYSTONE); - } catch (JSONException e) { + JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( + TOKEN_KEYSTONE); + String token = tokenKeyStone.getString(ID_KEYSTONE); + String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); + String tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( + NAME_KEYSTONE); + String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); + + attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); + attributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); + + return new Token(token, getDate(expirationDateToken), attributes); + } catch (Exception e) { + LOGGER.error("Exception while getting token from json.", e); return null; } } - private String getUserDateExpirationTokenFromJson(String responseStr) { + private Date getDate(String expirationDateStr) { + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); try { - JSONObject root = new JSONObject(responseStr); - return root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) - .getString(EXPIRES_KEYSTONE); - } catch (JSONException e) { + return dateFormatISO8601.parse(expirationDateStr); + } catch (Exception e) { + LOGGER.error("Exception while getting date from String.", e); return null; } } - private Token getTokenFromJson(String responseStr) { + @Override + public Token getToken(String tokenId) { + String responseJson = getResponseJson(tokenId); + String accessId = tokenId; + long expirationTimeMillis = 0; + String user = null; try { - Map attributes = new HashMap(); - JSONObject root = new JSONObject(responseStr); - JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( - TOKEN_KEYSTONE); - String token = tokenKeyStone.getString(ID_KEYSTONE); - String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); - String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); + //TODO Refactor! This code is repeated at many classes + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - attributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, token); - attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); - attributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDateToken); + JSONObject root = new JSONObject(responseJson); + + user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) + .getString(NAME_KEYSTONE); - return new Token(attributes); + String expirationTime = root.getJSONObject(ACCESS_KEYSTONE) + .getJSONObject(TOKEN_KEYSTONE).getString(EXPIRES_KEYSTONE); + expirationTimeMillis = dateFormatISO8601.parse(expirationTime).getTime(); } catch (Exception e) { - return null; + LOGGER.error(e); } + + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, user); + + return new Token(accessId, new Date(expirationTimeMillis), tokenAttributes); } + } diff --git a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java index 90a5eaf6..5b654e27 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java @@ -31,11 +31,9 @@ public String fetch() { } public String generateResponse(Token token) { - if(token == null || token.getAttributes().size() == 0) { + if (token == null) { return new String(); } - - Map tokenAttributes = token.getAttributes(); - return tokenAttributes.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + return token.getAccessId(); } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java index a51d0b56..28c477e4 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java @@ -10,8 +10,6 @@ public class OCCIHeaders { public static final String X_TOKEN_PASS = "X-Token-Pass"; public static final String X_TOKEN_TENANT_NAME = "X-Token-Tenant-Name"; public static final String X_TOKEN_TENANT_ID = "X-Token-Tenant-Id"; - public static final String X_TOKEN_ACCESS_ID = "X-Token-Access-Id"; - public static final String X_TOKEN_EXPIRATION_DATE = "X-Token-Expiration-Date"; // occi constants public static final String CATEGORY = "Category"; diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index 6fb30ee0..6ad03213 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -1,30 +1,34 @@ package org.fogbowcloud.manager.occi.core; -import java.text.SimpleDateFormat; -import java.util.Locale; +import java.util.Date; import java.util.Map; -import java.util.TimeZone; -import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class Token { private Map attributes; + private String accessId; + private Date expirationDate; private DateUtils dateUtils = new DateUtils(); - public Token(Map attributes) { + //TODO Check invalid values + public Token(String accessId, Date expirationTime, Map attributes) { + this.accessId = accessId; + this.expirationDate = expirationTime; this.attributes = attributes; } public String get(String attributeName) { - try { - return attributes.get(attributeName); - //TODO Which exception could happen here? - } catch (Exception e) { - return null; - } + return attributes.get(attributeName); + } + + public String getAccessId() { + return this.accessId; + } + public Date getExpirationDate() { + return this.expirationDate; } public Map getAttributes() { @@ -32,20 +36,16 @@ public Map getAttributes() { } public boolean isExpiredToken() { - String expirationDateSrt = get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - long expirationDateMillis; - try { - expirationDateMillis = dateFormatISO8601.parse(expirationDateSrt).getTime(); - } catch (Exception e) { - return true; - } + long expirationDateMillis = getExpirationDate().getTime(); return expirationDateMillis < dateUtils.currentTimeMillis(); } - - public void setDateUtils(DateUtils dateUtils){ + + public void setDateUtils(DateUtils dateUtils) { this.dateUtils = dateUtils; } + + public String toString() { + return "AccessId: " + accessId + ", expirationDate: " + expirationDate + " attributes: " + + attributes; + } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index ed0ab704..241b2d64 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -10,12 +10,13 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class Request { private String id; - private String authToken; + private Token token; private String instanceId; private String memberId; private RequestState state; @@ -23,10 +24,10 @@ public class Request { private Map xOCCIAtt; private String user; - public Request(String id, String authToken, String user, List categories, + public Request(String id, Token token, String user, List categories, Map xOCCIAtt) { this.id = id; - this.authToken = authToken; + this.token = token; this.user = user; this.categories = categories; this.xOCCIAtt = xOCCIAtt; @@ -86,8 +87,12 @@ public String toHttpMessageFormat() { return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; } + //TODO Review if we need this method public String getAuthToken() { - return this.authToken; + if (token == null){ + return null; + } + return this.token.getAccessId(); } public Map getxOCCIAtt() { @@ -103,7 +108,7 @@ public void setMemberId(String memberId) { } public String toString() { - return "id: " + id + ", authToken: " + authToken + ", user: " + user + ", instanceId: " + return "id: " + id + ", token: " + token + ", user: " + user + ", instanceId: " + instanceId + ", memberId: " + memberId + ", state: " + state + ", categories: " + categories + ", xOCCIAtt: " + xOCCIAtt; } @@ -132,6 +137,7 @@ public boolean isExpired() { if (expirationDateSrt == null){ return false; } + //TODO Refactor! This code is repeated at many places SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index e7e8002d..9126b480 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -29,6 +29,7 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; @@ -53,10 +54,15 @@ public class TestManagerController { private static final String TENANT_NAME = "tenantName"; private static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; + Token userToken; + @Before public void setUp() throws Exception { managerController = new ManagerController(new Properties()); managerTestHelper = new ManagerTestHelper(); + HashMap tokenAttr = new HashMap(); + tokenAttr.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + userToken = new Token(ACCESS_TOKEN_ID, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); } @Test @@ -73,32 +79,31 @@ public void testGetFederationMember() throws InterruptedException { attributesToken.put(OCCIHeaders.X_TOKEN_PASS, USER_PASS); attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - long expirationTime = System.currentTimeMillis() + 250; - - String expirationDateStr = getDateISO8601Format(expirationTime); + long expirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_TOKEN_ID); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, expirationDateStr); - Token token = new Token(attributesTokenReturn); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + Token token = new Token(ACCESS_TOKEN_ID, new Date(expirationTime), attributesTokenReturn); Map attributesTokenReturn2 = new HashMap(); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_TOKEN_ID_2); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, "data"); - Token token2 = new Token(attributesTokenReturn2); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + + Token token2 = new Token(ACCESS_TOKEN_ID_2, new Date(expirationTime + LONG_TIME), attributesTokenReturn2); Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token Token federationUserToken = managerController.getFederationUserToken(); - String accessToken = federationUserToken.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String accessToken = federationUserToken.getAccessId(); Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); // Use member token - accessToken = managerController.getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); + accessToken = managerController.getFederationUserToken().getAccessId(); Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); @@ -106,7 +111,7 @@ public void testGetFederationMember() throws InterruptedException { token.setDateUtils(dateUtils); // Get new token - accessToken = managerController.getFederationUserToken().get(OCCIHeaders.X_TOKEN_ACCESS_ID); + accessToken = managerController.getFederationUserToken().getAccessId(); Assert.assertEquals(ACCESS_TOKEN_ID_2, accessToken); } @@ -169,6 +174,7 @@ public void testGetRequestsByUser() throws InterruptedException { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -208,6 +214,7 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -262,6 +269,7 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -316,6 +324,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -389,6 +398,7 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -447,6 +457,7 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -512,6 +523,7 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -574,6 +586,7 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -647,6 +660,7 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -720,6 +734,7 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -801,6 +816,7 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -861,6 +877,7 @@ public static String getDateISO8601Format(long dateMili) { FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); String expirationDate = dateFormatISO8601.format(new Date(dateMili)); + System.out.println("exp" + expirationDate); return expirationDate; } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 4669071f..10009df9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.occi; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -9,10 +10,10 @@ import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; -import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; @@ -22,10 +23,10 @@ import org.mockito.Mockito; public class TestDeleteCompute { - + public static String INSTANCE_ID = "1234567ujhgf45hdb4w"; public static String OTHER_INSTANCE_ID = "otherInstanceId"; - + private OCCITestHelper helper; @Before @@ -41,15 +42,16 @@ public void setup() throws Exception { OCCITestHelper.USER_MOCK); List requests = new LinkedList(); - Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, + Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_ID); requests.add(request1); - Request request2 = new Request("1", "otherToken", - "otherUser", null, null); + Request request2 = new Request("1", new Token("otherToken", + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), "otherUser", null, null); request2.setInstanceId(OTHER_INSTANCE_ID); - requests.add(request2); - + requests.add(request2); + this.helper.initializeComponentCompute(computePlugin, identityPlugin, requests); } @@ -68,22 +70,21 @@ public void testDelete() throws Exception { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } - + @Test public void testDeleteSpecificInstanceOtherUser() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + OTHER_INSTANCE_ID); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); - - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); - } + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + } @Test public void testDeleteSpecificInstanceFound() throws Exception { - HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE - + INSTANCE_ID); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_ID); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); @@ -105,8 +106,7 @@ public void testDeleteSpecificInstanceNotFound() throws Exception { @Test public void testWrongAccessToken() throws Exception { - HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE - + INSTANCE_ID); + HttpDelete httpDelete = new HttpDelete(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_ID); httpDelete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpDelete.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index c75da446..f37370d0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -11,11 +11,11 @@ import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; -import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Resource; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; @@ -31,9 +31,9 @@ public class TestGetCompute { private static final String INSTANCE_1_ID = "test1"; private static final String INSTANCE_2_ID = "test2"; private static final String INSTANCE_3_ID_WITHOUT_USER = "test3"; - + private OCCITestHelper helper; - + @Before public void setup() throws Exception { this.helper = new OCCITestHelper(); @@ -43,49 +43,53 @@ public void setup() throws Exception { map.put("test", "test"); Link link = null; Instance instance1 = new Instance(INSTANCE_1_ID, list, map, link); - + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), - Mockito.eq(INSTANCE_1_ID))).thenReturn(instance1); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), - Mockito.eq(INSTANCE_2_ID))).thenReturn(new Instance(INSTANCE_2_ID)); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), - Mockito.eq(INSTANCE_3_ID_WITHOUT_USER))).thenReturn(instance1); - + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.eq(INSTANCE_1_ID))) + .thenReturn(instance1); + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.eq(INSTANCE_2_ID))) + .thenReturn(new Instance(INSTANCE_2_ID)); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), + Mockito.eq(INSTANCE_3_ID_WITHOUT_USER))).thenReturn(instance1); + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); - + List requests = new LinkedList(); - Request request1 = new Request("1", OCCITestHelper.ACCESS_TOKEN, + Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_1_ID); requests.add(request1); - Request request2 = new Request("2", OCCITestHelper.ACCESS_TOKEN, + Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request2.setInstanceId(INSTANCE_2_ID); requests.add(request2); - Request request3 = new Request("3", "token", - "user", null, null); + Request request3 = new Request("3", new Token("token", + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), "user", + null, null); request3.setInstanceId(INSTANCE_3_ID_WITHOUT_USER); - requests.add(request3); - + requests.add(request3); + this.helper.initializeComponentCompute(computePlugin, identityPlugin, requests); } - - @After - public void tearDown() throws Exception{ + + @After + public void tearDown() throws Exception { this.helper.stopComponent(); } - + @Test - public void testGetComputeOk() throws Exception{ + public void testGetComputeOk() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); - + HttpResponse response = client.execute(httpGet); + Assert.assertEquals(3, OCCITestHelper.getRequestLocations(response).size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @@ -96,33 +100,34 @@ public void testGetSpecificInstanceFound() throws Exception { httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); - + HttpResponse response = client.execute(httpGet); + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - } - + } + @Test public void testGetSpecificInstanceNotFound() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + "wrong"); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); - + HttpResponse response = client.execute(httpGet); + Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); } - + @Test public void testGetSpecificInstanceOtherUser() throws Exception { - HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_3_ID_WITHOUT_USER); + HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + + INSTANCE_3_ID_WITHOUT_USER); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); - HttpResponse response = client.execute(httpGet); - - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + HttpResponse response = client.execute(httpGet); + + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } - + @Test public void testWrongContentType() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); @@ -130,7 +135,7 @@ public void testWrongContentType() throws Exception { httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - + Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); } @@ -141,10 +146,10 @@ public void testAccessToken() throws Exception { httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - + Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - } - + } + @Test public void testWrongAccessToken() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE + INSTANCE_1_ID); @@ -152,10 +157,10 @@ public void testWrongAccessToken() throws Exception { httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, "wrong"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); - } - + } + @Test public void testEmptyAccessToken() throws Exception { HttpGet httpGet = new HttpGet(OCCITestHelper.URI_FOGBOW_COMPUTE); @@ -163,7 +168,7 @@ public void testEmptyAccessToken() throws Exception { httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, ""); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpGet); - + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); - } + } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 62d78738..26ba8f34 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.net.URISyntaxException; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -23,6 +24,7 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; @@ -55,6 +57,13 @@ public void setup() throws Exception { OCCITestHelper.USER_MOCK); Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); + + HashMap tokenAttr = new HashMap(); + tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); + Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); + + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn(userToken); requestHelper.initializeComponent(computePlugin, identityPlugin); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 78f2cc24..97ae3c7d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -7,14 +7,15 @@ import java.util.Properties; import org.fogbowcloud.manager.core.ManagerController; -import org.fogbowcloud.manager.core.TestManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; @@ -57,6 +58,12 @@ public void setUp() { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( OCCITestHelper.USER_MOCK); + HashMap tokenAttr = new HashMap(); + tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); + Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); + + Mockito.when(identityPlugin.getToken(Mockito.anyString())).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java index 927ac1f8..5ac6217a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -1,7 +1,6 @@ package org.fogbowcloud.manager.occi; import java.util.HashMap; -import java.util.Map; import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; @@ -24,9 +23,9 @@ import org.mockito.Mockito; public class TestTokenServerResource { - + private final String ACCESS_TOKEN_ID = "e723tgdjscbh1gyFV4GFC3OQ"; - + private OCCITestHelper helper; private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; @@ -54,16 +53,15 @@ public void testGetTokenWrongContentType() throws Exception { Assert.assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatusLine().getStatusCode()); } - + @SuppressWarnings("unchecked") @Test public void testGetToken() throws Exception { - Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, ACCESS_TOKEN_ID); - Token token = new Token(tokenAttributes); - + Token token = new Token(ACCESS_TOKEN_ID, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, + new HashMap()); + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(token); - + this.helper.initializeComponent(computePlugin, identityPlugin); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); @@ -72,18 +70,18 @@ public void testGetToken() throws Exception { HttpResponse response = client.execute(get); String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); - + String.valueOf(Charsets.UTF_8)); + Assert.assertEquals(ACCESS_TOKEN_ID, responseStr); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); - } - + } + @SuppressWarnings("unchecked") @Test public void testGetTokenUnauthorized() throws Exception { - Mockito.when(identityPlugin.getToken(Mockito.anyMap())) - .thenThrow(new OCCIException(ErrorType.UNAUTHORIZED, "")); - + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, "")); + this.helper.initializeComponent(computePlugin, identityPlugin); HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_TOKEN); @@ -91,7 +89,6 @@ public void testGetTokenUnauthorized() throws Exception { HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); - Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine() - .getStatusCode()); - } + Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); + } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 64aad4a1..e254e2f9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.occi.plugins; +import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; @@ -62,11 +63,11 @@ public void testGetToken() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANTNAME_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.getToken(tokenAttributes); - String authToken = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String authToken = token.getAccessId(); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); - String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); @@ -77,22 +78,19 @@ public void testUpgradeToken() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANTNAME_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.getToken(tokenAttributes); - String authToken = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String authToken = token.getAccessId(); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); - String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); - Map tokenAttributes2 = new HashMap(); - tokenAttributes2.put(OCCIHeaders.X_TOKEN_ACCESS_ID, PluginHelper.VALID_TOKEN); - tokenAttributes2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANTNAME_FOGBOW); - Token token2 = this.identityOpenStack.updateToken(tokenAttributes2); - authToken = token2.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + Token token2 = this.identityOpenStack.updateToken(token); + authToken = token2.getAccessId(); tenantID = token2.get(OCCIHeaders.X_TOKEN_TENANT_ID); - expirationDate = token2.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + expirationDate = token2.getExpirationDate(); Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 85fd3a0f..58006f51 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -1,10 +1,14 @@ package org.fogbowcloud.manager.occi.util; import java.io.IOException; +import java.text.SimpleDateFormat; import java.util.HashMap; +import java.util.Locale; import java.util.Map; +import java.util.TimeZone; import org.apache.http.HttpStatus; +import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; @@ -111,17 +115,17 @@ public Representation post(Representation entity) { } catch (IOException e) { } - String tenantNname = getTenantName(jsonCredentials); + String tenantName = getTenantName(jsonCredentials); String idToken = getIdToken(jsonCredentials); if (idToken != null) { - keyStoneApplication.authenticationCheckToken(idToken, tenantNname); + keyStoneApplication.authenticationCheckToken(idToken, tenantName); } else { String username = getUserFeatureCredentials(jsonCredentials, OpenStackIdentityPlugin.USERNAME_KEYSTONE); String password = getUserFeatureCredentials(jsonCredentials, OpenStackIdentityPlugin.PASSWORD_KEYSTONE); - keyStoneApplication.checkAuthenticationCredentials(username, password, tenantNname); + keyStoneApplication.checkAuthenticationCredentials(username, password, tenantName); } return new StringRepresentation( @@ -131,16 +135,23 @@ public Representation post(Representation entity) { private String mountJSONResponseAuthenticateToken(Token token) { try { - String tokenId = token.get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String tokenAccessId = token.getAccessId(); String tenantId = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); - String expirationDate = token.get(OCCIHeaders.X_TOKEN_EXPIRATION_DATE); + String tenantName = token.get(OCCIHeaders.X_TOKEN_TENANT_NAME); + + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + String expirationDate = dateFormatISO8601.format(token.getExpirationDate()); - JSONObject rootIdTenantToken = new JSONObject(); - rootIdTenantToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tenantId); JSONObject rootIdToken = new JSONObject(); - rootIdToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tokenId); + + JSONObject rootTenant = new JSONObject(); + rootTenant.put(OpenStackIdentityPlugin.ID_KEYSTONE, tenantId); + rootTenant.put(OpenStackIdentityPlugin.NAME_KEYSTONE, tenantName); + rootIdToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tokenAccessId); rootIdToken.put(OpenStackIdentityPlugin.EXPIRES_KEYSTONE, expirationDate); - rootIdToken.put(OpenStackIdentityPlugin.TENANT_KEYSTONE, rootIdTenantToken); + rootIdToken.put(OpenStackIdentityPlugin.TENANT_KEYSTONE, rootTenant); JSONObject rootToken = new JSONObject(); rootToken.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdToken); JSONObject rootAccess = new JSONObject(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 51a0f79b..44a17bd0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -19,6 +20,7 @@ import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.mockito.Mockito; @@ -27,7 +29,7 @@ public class OCCITestHelper { - public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; + public static final String ACCESS_TOKEN = "HgjhgYUDFTGBgrbelihBDFGB40uyrb"; public static final String INVALID_TOKEN = "invalid-token"; public static final String CONTENT_TYPE_OCCI = "text/occi"; public static final String URI_FOGBOW_REQUEST = "http://localhost:8182/request"; @@ -38,6 +40,7 @@ public class OCCITestHelper { public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; public static final long LONG_TIME = 24 * 60 * 60 * 1000; //one day + public static final Date TOKEN_FUTURE_EXPIRATION = new Date(System.currentTimeMillis() + LONG_TIME); private Component component; private RequestRepository requests; diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index b5561d87..1bc65c06 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -1,11 +1,10 @@ package org.fogbowcloud.manager.occi.util; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.swing.text.TabableView; - import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; @@ -20,10 +19,12 @@ public class PluginHelper { public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; public static final String VALID_TOKEN = "JgY45SDNFfdh348by89byfjhihjfjhfccv"; public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; - public static final String EXPIRATION_DATE = "2014-01-31T15:30:58Z"; + public static final String TENANT_NAME = "admin"; + + public static final Date EXPIRATION_DATE = new Date(System.currentTimeMillis() + + OCCITestHelper.LONG_TIME); public static final String USERNAME_FOGBOW = "admin"; public static final String PASSWORD_FOGBOW = "reverse"; - public static final String TENANTNAME_FOGBOW = "admin"; public static final int PORT_ENDPOINT = 8182; @@ -36,14 +37,15 @@ public void initializeKeystoneComponent() throws Exception { this.component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, AUTH_TOKEN); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); - tokenAttributes.put(OCCIHeaders.X_TOKEN_EXPIRATION_DATE, EXPIRATION_DATE); - Token token = new Token(tokenAttributes); - - KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, PASSWORD_FOGBOW - , TENANTNAME_FOGBOW, VALID_TOKEN, token); - + tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + Token token = new Token(AUTH_TOKEN, EXPIRATION_DATE, tokenAttributes); + + // TODO Refactor! We really need all these args to KeytoneApplication? + KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, + PASSWORD_FOGBOW, TENANT_NAME, VALID_TOKEN, token); + keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); this.component.getDefaultHost().attach(keystoneApplication); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java index 988cfa53..549e76ab 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -1,9 +1,13 @@ package org.fogbowcloud.manager.xmpp; +import java.util.HashMap; + import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.jivesoftware.smack.XMPPException; import org.junit.After; @@ -36,7 +40,8 @@ public void tearDown() throws Exception { @Test public void testDeleteRemoteInstance() throws Exception { - Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token("anyvalue", + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -46,7 +51,8 @@ public void testDeleteRemoteInstance() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstaceNotFound() throws Exception { - Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -61,7 +67,8 @@ public void testDeleteRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstanceUnauthorized() throws Exception { - Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_OTHER_USER); request.setMemberId(MANAGER_COMPONENT_URL); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 25dcf5ad..add7868c 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -10,9 +10,11 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.Resource; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.jivesoftware.smack.XMPPException; import org.junit.After; @@ -74,7 +76,8 @@ public void testGetRemoteInstance() throws Exception { .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_DEFAULT))) .thenReturn(instance); - Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token("anyvalue", + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -96,7 +99,8 @@ public void testGetRemoteInstance() throws Exception { @Test public void testGetRemoteInstaceNotFound() throws Exception { - Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token( WRONG_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -112,7 +116,8 @@ public void testGetRemoteInstaceNotFound() throws Exception { @Test(expected=OCCIException.class) public void testGetRemoteInstanceUnauthorized() throws Exception { - Request request = new Request("anyvalue", WRONG_TOKEN, USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token( WRONG_TOKEN, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_OTHER_USER); request.setMemberId(MANAGER_COMPONENT_URL); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index a0b31554..4698fb3d 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -9,7 +9,9 @@ import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.jivesoftware.smack.XMPPException; import org.junit.After; @@ -61,7 +63,8 @@ private Request createRequest() { Map attributes = new HashMap(); attributes.put("key1", "value1"); attributes.put("key2", "value2"); - Request request = new Request("anyvalue", "anyvalue", USER_DEFAULT, categories, attributes); + Request request = new Request("anyvalue", new Token("anyvalue", + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, categories, attributes); request.setInstanceId(INSTANCE_DEFAULT); return request; } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index ef3171b8..82da205e 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -5,6 +5,7 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -23,6 +24,7 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; import org.jamppa.client.plugin.xep0077.XEP0077; @@ -44,8 +46,9 @@ public class ManagerTestHelper { private static final String CLIENT_ADRESS = "client@test.com"; private static final String CLIENT_PASS = "password"; private static final String SMACK_ENDING = "/Smack"; - private static final Token TOKEN = new Token(new HashMap()); - + // private static final Token TOKEN = new Token(new HashMap()); + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String MANAGER_COMPONENT_PASS = "password"; @@ -57,7 +60,6 @@ public class ManagerTestHelper { public final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; - private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; @@ -65,9 +67,9 @@ public class ManagerTestHelper { public ManagerTestHelper() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_ACCESS_ID, "token"); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); - this.tokenDefault = new Token(tokenAttributes); + this.tokenDefault = new Token("token", new Date(System.currentTimeMillis() + + OCCITestHelper.LONG_TIME), tokenAttributes); } public ResourcesInfo getResources() throws CertificateException, IOException { @@ -233,8 +235,8 @@ public void shutdown() throws ComponentException { } @SuppressWarnings("unchecked") - public List getItemsFromIQ(Packet response) - throws CertificateException, IOException { + public List getItemsFromIQ(Packet response) throws CertificateException, + IOException { Element queryElement = response.getElement().element("query"); Iterator itemIterator = queryElement.elementIterator("item"); ArrayList aliveItems = new ArrayList(); @@ -243,8 +245,8 @@ public List getItemsFromIQ(Packet response) Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); Element statusEl = itemEl.element("status"); - Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl - .element("cert").getText()); + Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl.element("cert") + .getText()); String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); String memIdle = statusEl.element("mem-idle").getText(); @@ -275,16 +277,15 @@ public Properties getProperties() throws IOException { properties.load(input); return properties; } - + public Properties getProperties(String path) throws IOException { Properties properties = new Properties(); FileInputStream input = new FileInputStream(path); properties.load(input); return properties; } - - public Certificate getCertificate() throws CertificateException, - IOException { + + public Certificate getCertificate() throws CertificateException, IOException { return CertificateHandlerHelper.getCertificate(getProperties()); } } From 8ee2eade81d00b565673b21d3e5871e484d2c2fe Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 14 May 2014 14:19:16 -0300 Subject: [PATCH 128/185] Fixing PluginHelper. --- .../org/fogbowcloud/manager/occi/util/KeystoneApplication.java | 2 +- .../java/org/fogbowcloud/manager/occi/util/PluginHelper.java | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 58006f51..12687762 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -108,7 +108,7 @@ public String fetch() { @Post public Representation post(Representation entity) { KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); - + String jsonCredentials = ""; try { jsonCredentials = entity.getText(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 1bc65c06..83f45f1e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -17,7 +17,6 @@ public class PluginHelper { private Component component; public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; - public static final String VALID_TOKEN = "JgY45SDNFfdh348by89byfjhihjfjhfccv"; public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; public static final String TENANT_NAME = "admin"; @@ -44,7 +43,7 @@ public void initializeKeystoneComponent() throws Exception { // TODO Refactor! We really need all these args to KeytoneApplication? KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, - PASSWORD_FOGBOW, TENANT_NAME, VALID_TOKEN, token); + PASSWORD_FOGBOW, TENANT_NAME, AUTH_TOKEN, token); keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); From a1cfe9e9e54d5ff892016ed6971e980a1548024f Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 14 May 2014 15:02:42 -0300 Subject: [PATCH 129/185] Implement timer to update request token --- manager.conf.example | 1 + .../manager/core/ManagerController.java | 78 +++++++++++++++---- .../manager/occi/request/Request.java | 12 +-- 3 files changed, 69 insertions(+), 22 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index e513baa4..c30455be 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -23,6 +23,7 @@ federation_user_tenant_name=demo cert_path= scheduler_period=30000 +token_update_period=300000 ssh_tunnel_host=10.0.0.1 ssh_tunnel_user=fogbow diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 866199a7..8d75bdb2 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -31,15 +31,19 @@ import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.xmpp.ManagerPacketHelper; +import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.jamppa.component.PacketSender; public class ManagerController { private static final Logger LOGGER = Logger.getLogger(ManagerController.class); - public static final long DEFAULT_SCHEDULER_PERIOD = 30000; + public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds + private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes private boolean scheduled = false; - private Timer timer; + private boolean tokenUpdaterOn = false; + private Timer requestSchedulerTimer; + private Timer tokenUpdaterTimer; private Token tokenMemberLocal; private List members = new LinkedList(); @@ -240,7 +244,7 @@ public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); - String token = getFederationUserToken().getAccessId();//(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId();// (OCCIHeaders.X_TOKEN_ACCESS_ID); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); } catch (OCCIException e) { @@ -250,7 +254,7 @@ public String submitRequestForRemoteMember(List categories, throw e; } } - + protected Token getFederationUserToken() { Map tokenAttributes = new HashMap(); String username = properties.getProperty("federation_user_name"); @@ -259,17 +263,17 @@ protected Token getFederationUserToken() { tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, username); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - + if (tokenMemberLocal == null || tokenMemberLocal.isExpiredToken()) { Token token = identityPlugin.getToken(tokenAttributes); this.tokenMemberLocal = token; } return this.tokenMemberLocal; - } + } public Instance getInstanceForRemoteMember(String instanceId) { LOGGER.info("Getting instance " + instanceId + " for remote member."); - String token = getFederationUserToken().getAccessId();//get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId();// get(OCCIHeaders.X_TOKEN_ACCESS_ID); try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { @@ -283,7 +287,7 @@ public Instance getInstanceForRemoteMember(String instanceId) { public void removeInstanceForRemoteMember(String instanceId) { LOGGER.info("Removing instance " + instanceId + " for remote member."); - String token = getFederationUserToken().getAccessId();//(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId();// (OCCIHeaders.X_TOKEN_ACCESS_ID); computePlugin.removeInstance(token, instanceId); } @@ -293,7 +297,7 @@ public List createRequests(String authToken, List categories, Token userToken = identityPlugin.getToken(authToken); LOGGER.debug("User Token: " + userToken); - + Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT .getValue())); LOGGER.info("Request " + instanceCount + " instances"); @@ -315,9 +319,51 @@ public List createRequests(String authToken, List categories, if (!scheduled) { scheduleRequests(); } + if (!tokenUpdaterOn) { + turnOnTokenUpdater(); + } return currentRequests; } + private void turnOnTokenUpdater() { + tokenUpdaterOn = true; + String tokenUpdaterPeriodStr = properties.getProperty("token_update_period"); + final long tokenUpdatePeriod = tokenUpdaterPeriodStr == null ? DEFAULT_TOKEN_UPDATE_PERIOD + : Long.valueOf(tokenUpdaterPeriodStr); + + tokenUpdaterTimer = new Timer(); + tokenUpdaterTimer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + checkAndUpdateRequestToken(tokenUpdatePeriod); + } + }, 0, tokenUpdatePeriod); + } + + // TODO Refactor! Think about not call updateToken to requests of same user + protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { + List allRequests = requests.getAll(); + boolean turnOffTimer = true; + for (Request request : allRequests) { + if (!request.getState().equals(RequestState.CLOSED) + && !request.getState().equals(RequestState.FAILED)) { + turnOffTimer = false; + long validInterval = request.getToken().getExpirationDate().getTime() + - new DateUtils().currentTimeMillis(); + if (validInterval < 2 * tokenUpdatePeriod) { + Token newToken = identityPlugin.updateToken(request.getToken()); + request.setToken(newToken); + } + } + } + + if (turnOffTimer) { + LOGGER.info("There are not requests."); + tokenUpdaterTimer.cancel(); + tokenUpdaterOn = false; + } + } + private boolean submitRemoteRequest(Request request) { FederationMember member = memberPicker.pick(this); if (member == null) { @@ -346,7 +392,7 @@ private boolean submitLocalRequest(Request request) { LOGGER.info("Submiting local request " + request); try { - instanceId = computePlugin.requestInstance(request.getAuthToken(), + instanceId = computePlugin.requestInstance(request.getToken().getAccessId(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { // TODO check if this is the error code! @@ -373,8 +419,8 @@ private void scheduleRequests() { long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long .valueOf(schedulerPeriodStr); - timer = new Timer(); - timer.scheduleAtFixedRate(new TimerTask() { + requestSchedulerTimer = new Timer(); + requestSchedulerTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkAndSubmitOpenRequests(); @@ -387,13 +433,13 @@ private void checkAndSubmitOpenRequests() { LOGGER.debug("Checking and submiting requests."); for (Request request : requests.get(RequestState.OPEN)) { - Map xOCCIAtt = request.getxOCCIAtt(); - if (request.isIntoValidPeriod()){ + Map xOCCIAtt = request.getxOCCIAtt(); + if (request.isIntoValidPeriod()) { for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); - } else if (request.isExpired()){ + } else if (request.isExpired()) { request.setState(RequestState.CLOSED); } else { allFulfilled = false; @@ -401,7 +447,7 @@ private void checkAndSubmitOpenRequests() { } if (allFulfilled) { LOGGER.info("All request fulfilled."); - timer.cancel(); + requestSchedulerTimer.cancel(); scheduled = false; } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 241b2d64..ba09b333 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -87,12 +87,12 @@ public String toHttpMessageFormat() { return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; } - //TODO Review if we need this method - public String getAuthToken() { - if (token == null){ - return null; - } - return this.token.getAccessId(); + public Token getToken() { + return this.token; + } + + public void setToken(Token token) { + this.token = token; } public Map getxOCCIAtt() { From 99f23341ebd330d139951af55b104df259f8be3f Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 14 May 2014 16:24:10 -0300 Subject: [PATCH 130/185] Implement instance monitoring. Fixes #29 --- manager.conf.example | 1 + .../manager/core/ManagerController.java | 80 ++++++++++++++++--- .../manager/occi/request/RequestState.java | 2 +- 3 files changed, 72 insertions(+), 11 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index c30455be..d03deda6 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -24,6 +24,7 @@ cert_path= scheduler_period=30000 token_update_period=300000 +instance_monitoring_period=120000 ssh_tunnel_host=10.0.0.1 ssh_tunnel_user=fogbow diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 8d75bdb2..8a5eb3ef 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -39,11 +39,14 @@ public class ManagerController { private static final Logger LOGGER = Logger.getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes + private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; //2 minutes private boolean scheduled = false; - private boolean tokenUpdaterOn = false; + private boolean tokenUpdatingOn = false; + private boolean instanceMonitoringOn = false; private Timer requestSchedulerTimer; private Timer tokenUpdaterTimer; + private Timer instanceMonitoringTimer; private Token tokenMemberLocal; private List members = new LinkedList(); @@ -151,6 +154,7 @@ public Instance getInstance(String authToken, String instanceId) { return getInstance(authToken, instanceId, request); } + //TODO Review the needs of these args. Request object already has othe information private Instance getInstance(String authToken, String instanceId, Request request) { Instance instance = null; if (isLocal(request)) { @@ -199,6 +203,10 @@ private void removeInstance(String authToken, String instanceId, Request request } request.setInstanceId(null); request.setMemberId(null); + updateRequestState(request); + } + + private void updateRequestState(Request request) { if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null && request.getAttValue(RequestAttribute.TYPE.getValue()).equals( RequestType.PERSISTENT.getValue())) { @@ -319,17 +327,63 @@ public List createRequests(String authToken, List categories, if (!scheduled) { scheduleRequests(); } - if (!tokenUpdaterOn) { - turnOnTokenUpdater(); + if (!tokenUpdatingOn) { + turnOnTokenUpdating(); } + return currentRequests; } - private void turnOnTokenUpdater() { - tokenUpdaterOn = true; - String tokenUpdaterPeriodStr = properties.getProperty("token_update_period"); - final long tokenUpdatePeriod = tokenUpdaterPeriodStr == null ? DEFAULT_TOKEN_UPDATE_PERIOD - : Long.valueOf(tokenUpdaterPeriodStr); + private void turnOnInstancesMonitoring() { + instanceMonitoringOn = true; + String instanceMonitoringPeriodStr = properties.getProperty("instance_monitoring_period"); + final long instanceMonitoringPeriod = instanceMonitoringPeriodStr == null ? DEFAULT_INSTANCE_MONITORING_PERIOD + : Long.valueOf(instanceMonitoringPeriodStr); + + instanceMonitoringTimer = new Timer(); + instanceMonitoringTimer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + monitorInstances(); + } + }, 0, instanceMonitoringPeriod); + } + + protected void monitorInstances() { + boolean turnOffTimer = true; + + //monitoring fulfilled requests + for (Request request : requests.get(RequestState.FULFILLED)) { + turnOffTimer = false; + try { + getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); + } catch (OCCIException e) { //TODO Only NOT FOUND exception type? + updateRequestState(requests.get(request.getId())); + } + } + + //monitoring deleted requests + for (Request request : requests.get(RequestState.DELETED)) { + turnOffTimer = false; + try { + getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); + } catch (OCCIException e) { + requests.remove(request.getId()); + } + } + + if (turnOffTimer) { + LOGGER.info("There are not requests."); + instanceMonitoringTimer.cancel(); + instanceMonitoringOn = false; + } + } + + private void turnOnTokenUpdating() { + tokenUpdatingOn = true; + String tokenUpdatePeriodStr = properties.getProperty("token_update_period"); + final long tokenUpdatePeriod = tokenUpdatePeriodStr == null ? DEFAULT_TOKEN_UPDATE_PERIOD + : Long.valueOf(tokenUpdatePeriodStr); tokenUpdaterTimer = new Timer(); tokenUpdaterTimer.scheduleAtFixedRate(new TimerTask() { @@ -352,7 +406,7 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { - new DateUtils().currentTimeMillis(); if (validInterval < 2 * tokenUpdatePeriod) { Token newToken = identityPlugin.updateToken(request.getToken()); - request.setToken(newToken); + requests.get(request.getId()).setToken(newToken); } } } @@ -360,7 +414,7 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { if (turnOffTimer) { LOGGER.info("There are not requests."); tokenUpdaterTimer.cancel(); - tokenUpdaterOn = false; + tokenUpdatingOn = false; } } @@ -382,6 +436,9 @@ private boolean submitRemoteRequest(Request request) { request.setState(RequestState.FULFILLED); request.setInstanceId(remoteInstanceId); + if(!instanceMonitoringOn){ + turnOnInstancesMonitoring(); + } return true; } @@ -410,6 +467,9 @@ private boolean submitLocalRequest(Request request) { request.setInstanceId(instanceId); request.setState(RequestState.FULFILLED); LOGGER.debug("Fulfilled Request: " + request); + if (!instanceMonitoringOn){ + turnOnInstancesMonitoring(); + } return true; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java index 2c4d83bb..b3852d77 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java @@ -17,7 +17,7 @@ public enum RequestState { * subsequently was interrupted or terminated), or was not fulfilled within * the period specified. */ - OPEN("open"), FAILED("failed"), FULFILLED("fulfilled"), CANCELED("canceled"), CLOSED("closed"); + OPEN("open"), FAILED("failed"), FULFILLED("fulfilled"), DELETED("deleted"), CLOSED("closed"); private String value; From fd58cc8996a245bfe727bb7d94197048176ab2d5 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Thu, 15 May 2014 10:26:00 -0300 Subject: [PATCH 131/185] Adding Certificate validation part --- .../core/CertificateHandlerHelper.java | 32 +++++-- .../DefaultFederationMemberValidator.java | 71 +++++++++++--- .../core/FederationMemberValidator.java | 11 +-- .../manager/core/model/ResourcesInfo.java | 12 +-- .../manager/xmpp/ManagerPacketHelper.java | 4 +- .../TestDefaultFederationMemberValidator.java | 93 ++++++++++++------- .../manager/xmpp/util/ManagerTestHelper.java | 6 +- .../resources/manager.conf.testdefaultFMV | 1 - src/test/resources/server1.crt | 0 src/test/resources/server2.crt | 19 ---- 10 files changed, 162 insertions(+), 87 deletions(-) delete mode 100644 src/test/resources/manager.conf.testdefaultFMV delete mode 100644 src/test/resources/server1.crt delete mode 100644 src/test/resources/server2.crt diff --git a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java index 438a63a4..a0c910a1 100644 --- a/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java +++ b/src/main/java/org/fogbowcloud/manager/core/CertificateHandlerHelper.java @@ -13,7 +13,6 @@ import java.util.logging.Logger; import org.apache.commons.codec.binary.Base64; -import org.restlet.engine.log.LoggerFacade; public class CertificateHandlerHelper { private static final String CERTIFICATE_KEY = "certificate"; @@ -32,7 +31,7 @@ public static String getBase64Certificate(Properties properties) return new String(base64Certificate); } - public static Certificate getCertificate(Properties properties) + public static X509Certificate getCertificate(Properties properties) throws CertificateException { String path = properties.getProperty(CERTIFICATE_KEY); if (path == null || path.isEmpty()) { @@ -48,10 +47,10 @@ public static Certificate getCertificate(Properties properties) LOGGER.warning("File does not Exist." + e1); return null; } - Certificate cert = null; + X509Certificate cert = null; try { try { - cert = (Certificate) certFactory + cert = (X509Certificate) certFactory .generateCertificate(new FileInputStream(path)); } catch (FileNotFoundException e) { LOGGER.warning("Wring Path, File does not Exist." + e); @@ -70,8 +69,29 @@ public static Certificate getCertificate(Properties properties) } return cert; } - - public static Certificate parseCertificate(String base64StringCertificate) + + public static X509Certificate getCertificate(String path) + throws CertificateException { + + CertificateFactory certFactory; + certFactory = CertificateFactory.getInstance("X.509"); + X509Certificate cert = null; + try { + try { + cert = (X509Certificate) certFactory + .generateCertificate(new FileInputStream(path)); + } catch (FileNotFoundException e) { + LOGGER.warning("Wring Path, File does not Exist." + e); + return null; + } + } catch (CertificateException e) { + LOGGER.warning("Certificate does not Exist" + e); + return null; + } + return cert; + } + + public static X509Certificate parseCertificate(String base64StringCertificate) throws CertificateException { byte[] base64BytesCertificate; try { diff --git a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java index 0731779a..40eac357 100644 --- a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java @@ -1,28 +1,75 @@ package org.fogbowcloud.manager.core; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SignatureException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.util.LinkedList; import java.util.List; -import javax.security.auth.x500.X500Principal; - import org.fogbowcloud.manager.core.model.FederationMember; public class DefaultFederationMemberValidator implements FederationMemberValidator { - + + List validCAs = new LinkedList(); + @Override - public boolean validateDonatorMember(FederationMember member) { - // TODO Auto-generated method stub - return false; + public boolean canDonateTo(FederationMember member) { + boolean canDonate = false; + X509Certificate cert = member.getResourcesInfo().getCert(); + + for (X509Certificate ca: validCAs) { + try { + cert.verify(ca.getPublicKey()); + canDonate = true; + } catch (InvalidKeyException e) { + } catch (CertificateException e) { + } catch (NoSuchAlgorithmException e) { + } catch (NoSuchProviderException e) { + } catch (SignatureException e) { + } + } + + try { + cert.checkValidity(); + } catch (Exception e) { + canDonate = false; + } + return canDonate ; } @Override - public boolean validateReceivingMember(FederationMember member) { - // TODO Auto-generated method stub - return false; + public boolean canReceiveFrom(FederationMember member) { + boolean canDonate = false; + X509Certificate cert = member.getResourcesInfo().getCert(); + for (X509Certificate ca: validCAs) { + try { + cert.verify(ca.getPublicKey()); + canDonate = true; + } catch (InvalidKeyException e) { + } catch (CertificateException e) { + } catch (NoSuchAlgorithmException e) { + } catch (NoSuchProviderException e) { + } catch (SignatureException e) { + } + } + + try { + cert.checkValidity(); + } catch (CertificateExpiredException e) { + canDonate = false; + } catch (CertificateNotYetValidException e) { + canDonate = false; + } + return canDonate ; } - @Override - public void setValidCAs(List list) { - // TODO Auto-generated method stub + public void setValidCAs(List list) { + this.validCAs = list; } diff --git a/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java index 2637e822..71cd7d77 100644 --- a/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java @@ -1,15 +1,14 @@ package org.fogbowcloud.manager.core; -import java.util.List; - -import javax.security.auth.x500.X500Principal; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateNotYetValidException; import org.fogbowcloud.manager.core.model.FederationMember; public interface FederationMemberValidator { - public boolean validateDonatorMember(FederationMember member); - public boolean validateReceivingMember(FederationMember member); - public void setValidCAs(List list); + public boolean canDonateTo(FederationMember member) throws CertificateExpiredException, CertificateNotYetValidException; + + public boolean canReceiveFrom(FederationMember member); } diff --git a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java index ccfceb1b..906b4e0e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/ResourcesInfo.java @@ -1,6 +1,6 @@ package org.fogbowcloud.manager.core.model; -import java.security.cert.Certificate; +import java.security.cert.X509Certificate; import java.util.List; public class ResourcesInfo { @@ -11,10 +11,10 @@ public class ResourcesInfo { private String memIdle; private String memInUse; private List flavours; - private Certificate cert; + private X509Certificate cert; public ResourcesInfo(String id, String cpuIdle, String cpuInUse, - String memIdle, String memInUse, List flavours, Certificate cert) { + String memIdle, String memInUse, List flavours, X509Certificate cert) { setCert(cert); setId(id); setCpuIdle(cpuIdle); @@ -25,7 +25,7 @@ public ResourcesInfo(String id, String cpuIdle, String cpuInUse, } public ResourcesInfo(String cpuIdle, String cpuInUse, - String memIdle, String memInUse, List flavours, Certificate cert) { + String memIdle, String memInUse, List flavours, X509Certificate cert) { this(null, cpuIdle, cpuInUse, memIdle, memInUse, flavours, cert); } @@ -93,11 +93,11 @@ public void setFlavours(List flavours) { this.flavours = flavours; } - public Certificate getCert() { + public X509Certificate getCert() { return cert; } - public void setCert(Certificate cert) { + public void setCert(X509Certificate cert) { this.cert = cert; } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java index 707a693a..9cf0609c 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/ManagerPacketHelper.java @@ -2,8 +2,8 @@ import java.io.FileInputStream; import java.io.IOException; -import java.security.cert.Certificate; import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -89,7 +89,7 @@ private static ArrayList getMembersFromIQ(IQ responseFromWhoIs while (itemIterator.hasNext()) { Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); - Certificate cert = null; + X509Certificate cert = null; try { cert = CertificateHandlerHelper.parseCertificate(itemEl.element("cert").getText()); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java index b7d9cd60..bcc86398 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java @@ -1,58 +1,87 @@ package org.fogbowcloud.manager.core; import java.io.IOException; -import java.security.cert.Certificate; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.SignatureException; import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; -import javax.security.auth.x500.X500Principal; - import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.Flavor; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; public class TestDefaultFederationMemberValidator { ManagerTestHelper helper; - FederationMemberValidator validator; - + DefaultFederationMemberValidator validator; + X509Certificate mockCA; + X509Certificate mockCertificate; + FederationMember member; + PublicKey publicKey; + @Before - public void setUp() { + public void setUp() throws NoSuchAlgorithmException { + KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA"); + KeyPair keys = keyGenerator.generateKeyPair(); + publicKey = keys.getPublic(); helper = new ManagerTestHelper(); validator = new DefaultFederationMemberValidator(); - X500Principal ca = new X500Principal( - "O=Internet Widgits Pty Ltd, L=Campina Gande, ST=Paraiba, C=BR"); - X500Principal ca2 = new X500Principal( - "O=Internet Widgits Pty Ltd, ST=Some-State, C=BR"); - List list = new LinkedList(); - list.add(ca); - list.add(ca2); + X509Certificate mockCA = Mockito.mock(X509Certificate.class); + Mockito.doReturn(publicKey).when(mockCA).getPublicKey(); + List list = new LinkedList(); + list.add(mockCA); validator.setValidCAs(list); + mockCertificate = Mockito.mock(X509Certificate.class); + member = new FederationMember(new ResourcesInfo("cpuIdle", "cpuInUse", + "memIdle", "memInUse", new LinkedList(), + mockCertificate)); + } - + @Test - public void testValidMember() throws CertificateException, IOException { - - ManagerTestHelper helper = new ManagerTestHelper(); - Certificate cert = CertificateHandlerHelper.getCertificate(helper - .getProperties()); - FederationMemberValidator validator = new DefaultFederationMemberValidator(); - //see if is this cert in the helper - FederationMember member = new FederationMember(helper.getResources()); - Assert.assertTrue(validator.validateDonatorMember(member)); + public void testValidMember() throws CertificateException, IOException, + InvalidKeyException, NoSuchAlgorithmException, + NoSuchProviderException, SignatureException { + + Mockito.doNothing().when(mockCertificate).checkValidity(); + Mockito.doNothing().when(mockCertificate).verify(publicKey); + Assert.assertTrue(validator.canDonateTo(member)); } - + + @Test + public void testInvalidMember() throws CertificateException, IOException, + InvalidKeyException, NoSuchAlgorithmException, + NoSuchProviderException, SignatureException { + + Mockito.doThrow(new SignatureException()).when(mockCertificate) + .verify(publicKey); + Mockito.doNothing().when(mockCertificate).checkValidity(); + Assert.assertFalse(validator.canDonateTo(member)); + } + @Test - public void testExpiredMember() throws CertificateException, IOException { + public void testExpiredMember() throws CertificateException, IOException, + InvalidKeyException, NoSuchAlgorithmException, + NoSuchProviderException, SignatureException { + // this method is invalid to get the exception here-- how to do that? + // use a real expired certificate? + + //gambiarra + Mockito.doThrow(new IllegalArgumentException()) + .when(mockCertificate).checkValidity(); - Certificate cert = CertificateHandlerHelper.getCertificate(helper - .getProperties(/*add expired certificate*/)); - FederationMemberValidator validator = new DefaultFederationMemberValidator(); - - FederationMember member = new FederationMember(helper.getResources()); - Assert.assertTrue(validator.validateDonatorMember(member)); + Mockito.doNothing().when(mockCertificate).verify(publicKey); + Assert.assertFalse(validator.canDonateTo(member)); } - } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index ef3171b8..6c3638f4 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -2,8 +2,8 @@ import java.io.FileInputStream; import java.io.IOException; -import java.security.cert.Certificate; import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -243,7 +243,7 @@ public List getItemsFromIQ(Packet response) Element itemEl = (Element) itemIterator.next(); Attribute id = itemEl.attribute("id"); Element statusEl = itemEl.element("status"); - Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl + X509Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl .element("cert").getText()); String cpuIdle = statusEl.element("cpu-idle").getText(); String cpuInUse = statusEl.element("cpu-inuse").getText(); @@ -283,7 +283,7 @@ public Properties getProperties(String path) throws IOException { return properties; } - public Certificate getCertificate() throws CertificateException, + public X509Certificate getCertificate() throws CertificateException, IOException { return CertificateHandlerHelper.getCertificate(getProperties()); } diff --git a/src/test/resources/manager.conf.testdefaultFMV b/src/test/resources/manager.conf.testdefaultFMV deleted file mode 100644 index 1adb14a9..00000000 --- a/src/test/resources/manager.conf.testdefaultFMV +++ /dev/null @@ -1 +0,0 @@ -certificate=src/test/resources/newreq.pem \ No newline at end of file diff --git a/src/test/resources/server1.crt b/src/test/resources/server1.crt deleted file mode 100644 index e69de29b..00000000 diff --git a/src/test/resources/server2.crt b/src/test/resources/server2.crt deleted file mode 100644 index 838051ff..00000000 --- a/src/test/resources/server2.crt +++ /dev/null @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDBjCCAe4CCQCVxx1VVABlZjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJC -UjETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 -cyBQdHkgTHRkMB4XDTE0MDUwNzEyNDE1OFoXDTE1MDUwNzEyNDE1OFowRTELMAkG -A1UEBhMCQlIxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 -IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -ANcJCqfDLEzODSRuZ+09RI1k2agqRac/86ycf8PUmE3uMBjg14G8HU0MJKBcaftt -uIO9DOg5a00ZV7cIOzlG5qx7HKzTe+UKSiQQP/vXL7joeGI3ksfitNJJh6r9VEo8 -yHKdG4a3ozr758kC5IMrUMbLLRowYnaiIgKFmNrVlWDy5jU4zUerj69PYGrYCA7m -bbYXfQcMNIGfAke0DiRRbspOhscA2wNvwr+nmHUB4tVPIZLz7pDMkBTh6Lhe+w9a -Cr1nwjTwDK4BrU5oCFdUtHD2qvwneEOauzod0PmfY6QCfsXg9YEyFGdaUobwblNF -bi1dB6GXITGhjKzCGxWz2E8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAYW6WHqw8 -NwwUu6gJ7oaT3RJtb3ByLWA8l43tUSBVPd3YrhRnRFtYUsMxG5R829eLvHKN2Rwk -JIB3ozzZuwbOPNhwBVnd444lBcI06JIJ3jdA8F5BxwTDdA1B31rpa5ZJwu98IUrL -BX2xNtQhkAFynNbi+3UKQi1U2W+zRLza1kl7+CZgqVx0QK97tiwo1eH//OE4x0rf -CoaTtukQYKsgY2eR2ZfqVErBOZrH3kaxK3Elm+SsqOZZTV2kUhKXegWC+dr0QmOe -DWdE9FzhcL8Z+IbHluzTnCDg3IICm4zVf3jWYf8QlrtAD7/9D1vQOm0ikW7LMARR -gn36ucRyCF0OFQ== ------END CERTIFICATE----- From a408b8c7f0363638817183d7bee0017df1098c20 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Thu, 15 May 2014 10:58:03 -0300 Subject: [PATCH 132/185] Adding managerTestHelper --- .../manager/xmpp/util/ManagerTestHelper.java | 291 ++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java new file mode 100644 index 00000000..3724a7f3 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -0,0 +1,291 @@ +package org.fogbowcloud.manager.xmpp.util; + +import java.io.FileInputStream; +import java.io.IOException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.dom4j.Attribute; +import org.dom4j.Element; +import org.fogbowcloud.manager.core.CertificateHandlerHelper; +import org.fogbowcloud.manager.core.ManagerController; +import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.Flavor; +import org.fogbowcloud.manager.core.model.ResourcesInfo; +import org.fogbowcloud.manager.core.plugins.ComputePlugin; +import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.occi.core.Token; +import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; +import org.jamppa.client.XMPPClient; +import org.jamppa.client.plugin.xep0077.XEP0077; +import org.jamppa.component.PacketSender; +import org.jivesoftware.smack.PacketCollector; +import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.filter.PacketFilter; +import org.jivesoftware.smack.filter.PacketIDFilter; +import org.mockito.Mockito; +import org.xmpp.component.ComponentException; +import org.xmpp.packet.IQ; +import org.xmpp.packet.Packet; + +public class ManagerTestHelper { + + private static final int SERVER_CLIENT_PORT = 5222; + private static final int SERVER_COMPONENT_PORT = 5347; + private static final String SERVER_HOST = "localhost"; + private static final String CLIENT_ADRESS = "client@test.com"; + private static final String CLIENT_PASS = "password"; + private static final String SMACK_ENDING = "/Smack"; + // private static final Token TOKEN = new Token(new HashMap()); + + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; + public static final String MANAGER_COMPONENT_PASS = "password"; + + public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; + public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; + + public static final int TEST_DEFAULT_TIMEOUT = 10000; + public static final int TIMEOUT_GRACE = 500; + + public final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; + + private ManagerXmppComponent managerXmppComponent; + private ComputePlugin computePlugin; + private IdentityPlugin identityPlugin; + private Token tokenDefault; + + public ManagerTestHelper() { + Map tokenAttributes = new HashMap(); + tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); + this.tokenDefault = new Token("token", new Date(System.currentTimeMillis() + + OCCITestHelper.LONG_TIME), tokenAttributes); + } + + public ResourcesInfo getResources() throws CertificateException, IOException { + List flavours = new LinkedList(); + flavours.add(new Flavor("small", "cpu", "mem", 2)); + flavours.add(new Flavor("small", "cpu", "mem", 3)); + ResourcesInfo resources = new ResourcesInfo("abc", "value1", "value2", "value3", "value4", + flavours, getCertificate()); + return resources; + } + + public IQ createWhoIsAliveResponse(ArrayList aliveIds, IQ iq) + throws CertificateException, IOException { + IQ resultIQ = IQ.createResultIQ(iq); + Element queryElement = resultIQ.getElement().addElement("query", WHOISALIVE_NAMESPACE); + for (FederationMember rendezvousItem : aliveIds) { + Element itemEl = queryElement.addElement("item"); + itemEl.addAttribute("id", rendezvousItem.getResourcesInfo().getId()); + itemEl.addElement("cert").setText( + CertificateHandlerHelper.getBase64Certificate(getProperties())); + Element statusEl = itemEl.addElement("status"); + statusEl.addElement("cpu-idle").setText(rendezvousItem.getResourcesInfo().getCpuIdle()); + statusEl.addElement("cpu-inuse").setText( + rendezvousItem.getResourcesInfo().getCpuInUse()); + statusEl.addElement("mem-idle").setText(rendezvousItem.getResourcesInfo().getMemIdle()); + statusEl.addElement("mem-inuse").setText( + rendezvousItem.getResourcesInfo().getMemInUse()); + + List flavours = rendezvousItem.getResourcesInfo().getFlavours(); + for (Flavor f : flavours) { + Element flavorElement = statusEl.addElement("flavor"); + flavorElement.addElement("name").setText(f.getName()); + flavorElement.addElement("cpu").setText(f.getCpu()); + flavorElement.addElement("mem").setText(f.getMem()); + flavorElement.addElement("capacity").setText(f.getCapacity().toString()); + } + statusEl.addElement("cert"); + statusEl.addElement("updated").setText( + String.valueOf(rendezvousItem.getFormattedTime())); + } + return resultIQ; + } + + public XMPPClient createXMPPClient() throws XMPPException { + + XMPPClient xmppClient = new XMPPClient(CLIENT_ADRESS, CLIENT_PASS, SERVER_HOST, + SERVER_CLIENT_PORT); + XEP0077 register = new XEP0077(); + xmppClient.registerPlugin(register); + xmppClient.connect(); + try { + register.createAccount(CLIENT_ADRESS, CLIENT_PASS); + } catch (XMPPException e) { + } + + xmppClient.login(); + xmppClient.process(false); + + return xmppClient; + } + + public PacketSender createPacketSender() throws XMPPException { + final XMPPClient xmppClient = createXMPPClient(); + PacketSender sender = new PacketSender() { + @Override + public Packet syncSendPacket(Packet packet) { + PacketFilter responseFilter = new PacketIDFilter(packet.getID()); + PacketCollector response = xmppClient.getConnection().createPacketCollector( + responseFilter); + xmppClient.getConnection().sendPacket(packet); + Packet result = response.nextResult(5000); + response.cancel(); + return result; + } + + @Override + public void sendPacket(Packet packet) { + xmppClient.send(packet); + } + }; + return sender; + } + + public ComputePlugin getComputePlugin() { + return computePlugin; + } + + public IdentityPlugin getIdentityPlugin() { + return identityPlugin; + } + + public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Exception { + + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); + + Properties properties = new Properties(); + properties.put("federation_user_name", "fogbow"); + properties.put("federation_user_password", "fogbow"); + properties.put("federation_user_tenant_name", "fogbow"); + properties.put("xmpp_jid", "manager.test.com"); + + ManagerController managerFacade = new ManagerController(properties); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setIdentityPlugin(identityPlugin); + + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); + + Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( + getResources()); + + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(tokenDefault); + + managerXmppComponent.setDescription("Manager Component"); + managerXmppComponent.setName("Manager"); + managerXmppComponent.setRendezvousAddress(CLIENT_ADRESS + SMACK_ENDING); + managerXmppComponent.connect(); + managerXmppComponent.process(); + if (init) { + managerXmppComponent.init(); + } + return managerXmppComponent; + } + + public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Exception { + + this.computePlugin = Mockito.mock(ComputePlugin.class); + this.identityPlugin = Mockito.mock(IdentityPlugin.class); + + Properties properties = new Properties(); + properties.put("federation_user_name", "fogbow"); + properties.put("federation_user_password", "fogbow"); + properties.put("xmpp_jid", "manager.test.com"); + + ManagerController managerFacade = new ManagerController(properties); + managerFacade.setComputePlugin(computePlugin); + managerFacade.setIdentityPlugin(identityPlugin); + + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); + + Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( + getResources()); + + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(tokenDefault); + + managerXmppComponent.setDescription("Manager Component"); + managerXmppComponent.setName("Manager"); + managerXmppComponent.setRendezvousAddress(CLIENT_ADRESS + SMACK_ENDING); + managerXmppComponent.connect(); + managerXmppComponent.process(); + return managerXmppComponent; + } + + public IQ CreateImAliveResponse(IQ iq) { + IQ response = IQ.createResultIQ(iq); + return response; + } + + public void shutdown() throws ComponentException { + managerXmppComponent.disconnect(); + } + + @SuppressWarnings("unchecked") + public List getItemsFromIQ(Packet response) throws CertificateException, + IOException { + Element queryElement = response.getElement().element("query"); + Iterator itemIterator = queryElement.elementIterator("item"); + ArrayList aliveItems = new ArrayList(); + + while (itemIterator.hasNext()) { + Element itemEl = (Element) itemIterator.next(); + Attribute id = itemEl.attribute("id"); + Element statusEl = itemEl.element("status"); + X509Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl.element("cert") + .getText()); + String cpuIdle = statusEl.element("cpu-idle").getText(); + String cpuInUse = statusEl.element("cpu-inuse").getText(); + String memIdle = statusEl.element("mem-idle").getText(); + String memInUse = statusEl.element("mem-inuse").getText(); + List flavoursList = new LinkedList(); + Iterator flavourIterator = itemEl.elementIterator("flavor"); + while (flavourIterator.hasNext()) { + Element flavour = (Element) itemIterator.next(); + String name = flavour.element("name").getText(); + String cpu = flavour.element("cpu").getText(); + String mem = flavour.element("mem").getText(); + int capacity = Integer.parseInt(flavour.element("capacity").getText()); + Flavor flavor = new Flavor(name, cpu, mem, capacity); + flavoursList.add(flavor); + } + + ResourcesInfo resources = new ResourcesInfo(id.getValue(), cpuIdle, cpuInUse, memIdle, + memInUse, flavoursList, cert); + FederationMember item = new FederationMember(resources); + aliveItems.add(item); + } + return aliveItems; + } + + public Properties getProperties() throws IOException { + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(CONFIG_PATH); + properties.load(input); + return properties; + } + + public Properties getProperties(String path) throws IOException { + Properties properties = new Properties(); + FileInputStream input = new FileInputStream(path); + properties.load(input); + return properties; + } + + public X509Certificate getCertificate() throws CertificateException, IOException { + return CertificateHandlerHelper.getCertificate(getProperties()); + } +} From efdee64f4c71073d0e6b858dd3b7fb7166507d5a Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 15 May 2014 16:49:33 -0300 Subject: [PATCH 133/185] Implemeing tests to instance monitoring. fixes #47 --- .../manager/core/TestManagerController.java | 326 +++++++++++++++++- 1 file changed, 318 insertions(+), 8 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 9126b480..7b6e2cc1 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -2,9 +2,9 @@ import java.io.IOException; import java.security.cert.CertificateException; -import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -16,6 +16,7 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; @@ -24,9 +25,11 @@ import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; +import org.fogbowcloud.manager.occi.instance.Instance; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.occi.util.OCCITestHelper; @@ -42,9 +45,6 @@ public class TestManagerController { private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; - ManagerController managerController; - ManagerTestHelper managerTestHelper; - private static final Long SCHEDULER_PERIOD = 500L; public static final String USER_NAME = "user"; public static final String USER_PASS = "password"; @@ -54,7 +54,9 @@ public class TestManagerController { private static final String TENANT_NAME = "tenantName"; private static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; - Token userToken; + private Token userToken; + private ManagerController managerController; + private ManagerTestHelper managerTestHelper; @Before public void setUp() throws Exception { @@ -84,7 +86,7 @@ public void testGetFederationMember() throws InterruptedException { Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); Token token = new Token(ACCESS_TOKEN_ID, new Date(expirationTime), attributesTokenReturn); Map attributesTokenReturn2 = new HashMap(); @@ -92,7 +94,8 @@ public void testGetFederationMember() throws InterruptedException { attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token2 = new Token(ACCESS_TOKEN_ID_2, new Date(expirationTime + LONG_TIME), attributesTokenReturn2); + Token token2 = new Token(ACCESS_TOKEN_ID_2, new Date(expirationTime + LONG_TIME), + attributesTokenReturn2); Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); managerController.setIdentityPlugin(openStackidentityPlugin); @@ -115,6 +118,303 @@ public void testGetFederationMember() throws InterruptedException { Assert.assertEquals(ACCESS_TOKEN_ID_2, accessToken); } + @Test + public void testcheckAndUpdateRequestToken() throws InterruptedException { + final String firstTokenId = "firstTokenId"; + final String secontTokenId = "secondTokenId"; + final int timeDefault = 100; + final long now = System.currentTimeMillis(); + + Properties properties = new Properties(); + properties.put("token_update_period", Integer.toString(timeDefault)); + managerController = new ManagerController(properties); + + DateUtils dateUtils = Mockito.mock(DateUtils.class); + + RequestRepository requestRepository = new RequestRepository(); + + Token token = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + new HashMap()); + Request request1 = new Request("id1", token, USER_NAME, null, null); + request1.setState(RequestState.OPEN); + Request request2 = new Request("id2", token, USER_NAME, null, null); + request2.setState(RequestState.OPEN); + Request request3 = new Request("id3", token, USER_NAME, null, null); + request3.setState(RequestState.OPEN); + Request request4 = new Request("id4", token, USER_NAME, null, null); + request4.setState(RequestState.CLOSED); + requestRepository.addRequest(USER_NAME, request1); + requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(USER_NAME, request3); + requestRepository.addRequest(USER_NAME, request4); + managerController.setRequests(requestRepository); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Token tokenUpdatedFirstTime = new Token(secontTokenId, new Date(System.currentTimeMillis() + + timeDefault), new HashMap()); + Mockito.when(identityPlugin.updateToken(Mockito.any(Token.class))).thenReturn( + tokenUpdatedFirstTime); + + managerController.setIdentityPlugin(identityPlugin); + + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); + managerController.setDateUtils(dateUtils); + managerController.turnOnTokenUpdating(); + + List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + if (request.getState().equals(RequestState.OPEN)) { + Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + } else if (request.getState().equals(RequestState.CLOSED)) { + Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + } + } + + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now + (3 * timeDefault)); + managerController.setDateUtils(dateUtils); + + Thread.sleep(timeDefault * 2); + + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + if (request.getState().equals(RequestState.OPEN)) { + Assert.assertEquals(secontTokenId, request.getToken().getAccessId()); + } else if (request.getState().equals(RequestState.CLOSED)) { + Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + } + } + } + + @Test + public void testMonitoringInstancesDeleted() throws InterruptedException { + final int timeDefault = 100; + + Properties properties = new Properties(); + properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + managerController = new ManagerController(properties); + + Token token = new Token("id", new Date(), new HashMap()); + Request request1 = new Request("id1", token, USER_NAME, null, null); + request1.setState(RequestState.DELETED); + Request request2 = new Request("id2", token, USER_NAME, null, null); + request2.setState(RequestState.DELETED); + Request request3 = new Request("id3", token, USER_NAME, null, null); + request3.setState(RequestState.DELETED); + RequestRepository requestRepository = new RequestRepository(); + requestRepository.addRequest(USER_NAME, request1); + requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(USER_NAME, request3); + managerController.setRequests(requestRepository); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + managerController.setIdentityPlugin(identityPlugin); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + managerController.setComputePlugin(computePlugin); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + + managerController.removeAllRequests(ACCESS_TOKEN_ID); + + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenReturn(new Instance("id")); + + Assert.assertEquals(requestRepository.getAll().size(), + managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); + + managerController.turnOnInstancesMonitoring(); + + Assert.assertEquals(requestRepository.getAll().size(), + managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); + + Thread.sleep(timeDefault * 2); + + Assert.assertEquals(requestRepository.getAll().size(), + managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size());; + } + + @Test + public void testMonitoringLostInstancesDeleted() throws InterruptedException { + final int timeDefault = 100; + + Properties properties = new Properties(); + properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + managerController = new ManagerController(properties); + + Token token = new Token("id", new Date(), new HashMap()); + Request request1 = new Request("id1", token, USER_NAME, null, null); + request1.setState(RequestState.DELETED); + Request request2 = new Request("id2", token, USER_NAME, null, null); + request2.setState(RequestState.DELETED); + RequestRepository requestRepository = new RequestRepository(); + requestRepository.addRequest(USER_NAME, request1); + requestRepository.addRequest(USER_NAME, request2); + managerController.setRequests(requestRepository); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + managerController.setIdentityPlugin(identityPlugin); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + managerController.setComputePlugin(computePlugin); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + + Assert.assertEquals(requestRepository.getAll().size(), + managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); + + managerController.turnOnInstancesMonitoring(); + + Assert.assertEquals(requestRepository.getAll().size(), + managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); + + Thread.sleep(timeDefault * 2); + + Assert.assertEquals(requestRepository.getAll().size(), + managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size());; + } + + @Test + public void testMonitoringLostInstances() throws InterruptedException { + final int timeDefault = 100; + + Properties properties = new Properties(); + properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + managerController = new ManagerController(properties); + + Token token = new Token("id", new Date(), new HashMap()); + Request request1 = new Request("id1", token, USER_NAME, null, null); + request1.setState(RequestState.FULFILLED); + Request request2 = new Request("id2", token, USER_NAME, null, null); + request2.setState(RequestState.FULFILLED); + RequestRepository requestRepository = new RequestRepository(); + requestRepository.addRequest(USER_NAME, request1); + requestRepository.addRequest(USER_NAME, request2); + managerController.setRequests(requestRepository); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + managerController.setIdentityPlugin(identityPlugin); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + managerController.setComputePlugin(computePlugin); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + + managerController.turnOnInstancesMonitoring(); + + List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); + } + + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + + Thread.sleep(timeDefault * 2); + + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); + } + } + + @Test + public void testMonitoringLostInstancesPersistent() throws InterruptedException { + final int timeDefault = 100; + + Properties properties = new Properties(); + properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + properties.put("scheduler_period", Integer.toString(timeDefault)); + + managerController = new ManagerController(properties); + + Token token = new Token("id", new Date(), new HashMap()); + Map map = new HashMap(); + map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); + Request request1 = new Request("id1", token, USER_NAME, null, map); + request1.setState(RequestState.FULFILLED); + Request request2 = new Request("id2", token, USER_NAME, null, map); + request2.setState(RequestState.FULFILLED); + RequestRepository requestRepository = new RequestRepository(); + requestRepository.addRequest(USER_NAME, request1); + requestRepository.addRequest(USER_NAME, request2); + managerController.setRequests(requestRepository); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + managerController.setIdentityPlugin(identityPlugin); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + managerController.setComputePlugin(computePlugin); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + + List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); + } + + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + managerController.turnOnInstancesMonitoring(); + + boolean wasOpen = false; + for (int i = 0; i < 10; i++) { + Thread.sleep(20); + for (Request request : requestsFromUser) { + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + if(request.getState().equals(RequestState.OPEN)) { + wasOpen = true; + } + } + } + + Assert.assertTrue(wasOpen); + + Thread.sleep(timeDefault); + + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); + } + } + + @Test + public void testMonitoringInstances() throws InterruptedException { + final int timeDefault = 100; + + Properties properties = new Properties(); + properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + managerController = new ManagerController(properties); + + Token token = new Token("id", new Date(), new HashMap()); + Request request1 = new Request("id1", token, USER_NAME, null, null); + request1.setState(RequestState.FULFILLED); + Request request2 = new Request("id2", token, USER_NAME, null, null); + request2.setState(RequestState.FULFILLED); + RequestRepository requestRepository = new RequestRepository(); + requestRepository.addRequest(USER_NAME, request1); + requestRepository.addRequest(USER_NAME, request2); + managerController.setRequests(requestRepository); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + managerController.setIdentityPlugin(identityPlugin); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + managerController.setComputePlugin(computePlugin); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + + managerController.turnOnInstancesMonitoring(); + + List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); + } + + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenReturn(new Instance("id")); + + Thread.sleep(timeDefault * 2); + + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + for (Request request : requestsFromUser) { + Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); + } + } + @Test(expected = IllegalArgumentException.class) public void testConstructorException() throws Exception { new ManagerController(null); @@ -155,6 +455,7 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { Assert.assertEquals(10, managerController.getMembers().size()); } + @SuppressWarnings("unchecked") @Test public void testGetRequestsByUser() throws InterruptedException { @@ -195,6 +496,7 @@ public void testGetRequestsByUser() throws InterruptedException { Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { @@ -244,6 +546,7 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { @@ -303,6 +606,7 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { @@ -370,6 +674,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { Properties properties = new Properties(); @@ -431,6 +736,7 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { @@ -496,6 +802,7 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Properties properties = new Properties(); @@ -557,6 +864,7 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { } + @SuppressWarnings("unchecked") @Test public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -632,6 +940,7 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testPersistentRequestValidFromInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -706,6 +1015,7 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -788,6 +1098,7 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { Properties properties = new Properties(); @@ -877,7 +1188,6 @@ public static String getDateISO8601Format(long dateMili) { FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); String expirationDate = dateFormatISO8601.format(new Date(dateMili)); - System.out.println("exp" + expirationDate); return expirationDate; } } From dc71dbb04f229f233196b2147232b97af998e396 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 16 May 2014 11:28:25 -0300 Subject: [PATCH 134/185] Implementing set request state to DELETED. fixes #48 --- .../manager/core/ManagerController.java | 35 +++-- .../occi/request/RequestRepository.java | 39 ++++- .../manager/core/TestManagerController.java | 147 ++++++++---------- 3 files changed, 121 insertions(+), 100 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 8a5eb3ef..7f4d12ca 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -39,7 +39,8 @@ public class ManagerController { private static final Logger LOGGER = Logger.getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes - private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; //2 minutes + private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 + // minutes private boolean scheduled = false; private boolean tokenUpdatingOn = false; @@ -58,6 +59,7 @@ public class ManagerController { private Properties properties; private PacketSender packetSender; + private DateUtils dateUtils = new DateUtils(); private SSHTunnel sshTunnel = new DefaultSSHTunnel(); public ManagerController(Properties properties) { @@ -120,7 +122,7 @@ public void removeAllRequests(String authToken) { public void removeRequest(String authToken, String requestId) { LOGGER.debug("Removing requestId: " + requestId); checkRequestId(authToken, requestId); - requests.remove(requestId); + requests.remove(requestId); } private void checkRequestId(String authToken, String requestId) { @@ -154,7 +156,8 @@ public Instance getInstance(String authToken, String instanceId) { return getInstance(authToken, instanceId, request); } - //TODO Review the needs of these args. Request object already has othe information + // TODO Review the needs of these args. Request object already has othe + // information private Instance getInstance(String authToken, String instanceId, Request request) { Instance instance = null; if (isLocal(request)) { @@ -334,7 +337,7 @@ public List createRequests(String authToken, List categories, return currentRequests; } - private void turnOnInstancesMonitoring() { + protected void turnOnInstancesMonitoring() { instanceMonitoringOn = true; String instanceMonitoringPeriodStr = properties.getProperty("instance_monitoring_period"); final long instanceMonitoringPeriod = instanceMonitoringPeriodStr == null ? DEFAULT_INSTANCE_MONITORING_PERIOD @@ -352,26 +355,26 @@ public void run() { protected void monitorInstances() { boolean turnOffTimer = true; - //monitoring fulfilled requests + // monitoring fulfilled requests for (Request request : requests.get(RequestState.FULFILLED)) { turnOffTimer = false; try { getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); - } catch (OCCIException e) { //TODO Only NOT FOUND exception type? + } catch (OCCIException e) { // TODO Only NOT FOUND exception type? updateRequestState(requests.get(request.getId())); } } - - //monitoring deleted requests + + // monitoring deleted requests for (Request request : requests.get(RequestState.DELETED)) { turnOffTimer = false; try { getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); } catch (OCCIException e) { - requests.remove(request.getId()); + requests.excluding(request.getId()); } } - + if (turnOffTimer) { LOGGER.info("There are not requests."); instanceMonitoringTimer.cancel(); @@ -403,7 +406,7 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { && !request.getState().equals(RequestState.FAILED)) { turnOffTimer = false; long validInterval = request.getToken().getExpirationDate().getTime() - - new DateUtils().currentTimeMillis(); + - dateUtils.currentTimeMillis(); if (validInterval < 2 * tokenUpdatePeriod) { Token newToken = identityPlugin.updateToken(request.getToken()); requests.get(request.getId()).setToken(newToken); @@ -436,7 +439,7 @@ private boolean submitRemoteRequest(Request request) { request.setState(RequestState.FULFILLED); request.setInstanceId(remoteInstanceId); - if(!instanceMonitoringOn){ + if (!instanceMonitoringOn) { turnOnInstancesMonitoring(); } return true; @@ -467,9 +470,9 @@ private boolean submitLocalRequest(Request request) { request.setInstanceId(instanceId); request.setState(RequestState.FULFILLED); LOGGER.debug("Fulfilled Request: " + request); - if (!instanceMonitoringOn){ + if (!instanceMonitoringOn) { turnOnInstancesMonitoring(); - } + } return true; } @@ -527,4 +530,8 @@ public Token getToken(Map attributesToken) { public Properties getProperties() { return properties; } + + public void setDateUtils(DateUtils dateUtils) { + this.dateUtils = dateUtils; + } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index 1d18b459..7383afca 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -68,17 +68,49 @@ public Request get(String user, String requestId) { public List getByUser(String user) { LOGGER.debug("Getting instances by user " + user); List userRequests = requests.get(user); - return userRequests == null ? new LinkedList() : new LinkedList( - userRequests); + // return userRequests == null ? new LinkedList() : new + // LinkedList( + // userRequests); + return userRequests == null ? new LinkedList() + : normalizeRequestsByUser(userRequests); + + } + + private List normalizeRequestsByUser(List userRequests) { + List requests = new LinkedList(); + for (Request userRequest : userRequests) { + if (!userRequest.getState().equals(RequestState.DELETED)) { + requests.add(userRequest); + } + } + return requests; } public void removeByUser(String user) { - requests.remove(user); + List requestsByUser = requests.get(user); + if (requestsByUser != null) { + for (Request request : requestsByUser) { + remove(request.getId()); + } + } } public void remove(String requestId) { LOGGER.debug("Removing requestId " + requestId); + for (List userRequests : requests.values()) { + for (Request request : userRequests) { + if (request.getId().equals(requestId)) { + request.setState(RequestState.DELETED); + return; + } + } + } + } + + public void excluding(String requestId) { + LOGGER.debug("Excluing requestId " + requestId); + for (List userRequests : requests.values()) { Iterator iterator = userRequests.iterator(); while (iterator.hasNext()) { @@ -89,6 +121,7 @@ public void remove(String requestId) { } } } + } public List getAll() { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 7b6e2cc1..f56f3680 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -16,7 +16,6 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; @@ -128,11 +127,9 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { Properties properties = new Properties(); properties.put("token_update_period", Integer.toString(timeDefault)); managerController = new ManagerController(properties); - DateUtils dateUtils = Mockito.mock(DateUtils.class); RequestRepository requestRepository = new RequestRepository(); - Token token = new Token(firstTokenId, new Date(now + (4 * timeDefault)), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); @@ -155,13 +152,11 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { + timeDefault), new HashMap()); Mockito.when(identityPlugin.updateToken(Mockito.any(Token.class))).thenReturn( tokenUpdatedFirstTime); - managerController.setIdentityPlugin(identityPlugin); - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); managerController.setDateUtils(dateUtils); - managerController.turnOnTokenUpdating(); + managerController.checkAndUpdateRequestToken(timeDefault); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().equals(RequestState.OPEN)) { @@ -174,8 +169,7 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now + (3 * timeDefault)); managerController.setDateUtils(dateUtils); - Thread.sleep(timeDefault * 2); - + managerController.checkAndUpdateRequestToken(timeDefault); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().equals(RequestState.OPEN)) { @@ -187,11 +181,9 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { } @Test - public void testMonitoringInstancesDeleted() throws InterruptedException { - final int timeDefault = 100; - + public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); Token token = new Token("id", new Date(), new HashMap()); @@ -199,45 +191,43 @@ public void testMonitoringInstancesDeleted() throws InterruptedException { request1.setState(RequestState.DELETED); Request request2 = new Request("id2", token, USER_NAME, null, null); request2.setState(RequestState.DELETED); - Request request3 = new Request("id3", token, USER_NAME, null, null); - request3.setState(RequestState.DELETED); RequestRepository requestRepository = new RequestRepository(); requestRepository.addRequest(USER_NAME, request1); requestRepository.addRequest(USER_NAME, request2); - requestRepository.addRequest(USER_NAME, request3); managerController.setRequests(requestRepository); + RequestRepository requestRepositoryCopy = new RequestRepository(); + requestRepositoryCopy.addRequest(USER_NAME, request1); + requestRepositoryCopy.addRequest(USER_NAME, request2); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - - managerController.removeAllRequests(ACCESS_TOKEN_ID); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance("id")); + .thenReturn(new Instance("id")); - Assert.assertEquals(requestRepository.getAll().size(), - managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); - - managerController.turnOnInstancesMonitoring(); - - Assert.assertEquals(requestRepository.getAll().size(), - managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); + Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); - Thread.sleep(timeDefault * 2); + managerController.monitorInstances(); + Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); + } - Assert.assertEquals(requestRepository.getAll().size(), - managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size());; + private List getRequestsDeleted(RequestRepository requestRepository) { + List requests = new ArrayList(); + for (Request request : requestRepository.get(RequestState.DELETED)) { + try { + requests.add(managerController.getRequest(ACCESS_TOKEN_ID, request.getId())); + } catch (Exception e) { + } + } + return requests; } - - @Test - public void testMonitoringLostInstancesDeleted() throws InterruptedException { - final int timeDefault = 100; + @Test + public void testMonitoringDeletedRequestAndNotFoundInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); Token token = new Token("id", new Date(), new HashMap()); @@ -245,40 +235,36 @@ public void testMonitoringLostInstancesDeleted() throws InterruptedException { request1.setState(RequestState.DELETED); Request request2 = new Request("id2", token, USER_NAME, null, null); request2.setState(RequestState.DELETED); + Request request3 = new Request("id3", token, USER_NAME, null, null); + request3.setState(RequestState.OPEN); RequestRepository requestRepository = new RequestRepository(); requestRepository.addRequest(USER_NAME, request1); requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(USER_NAME, request3); managerController.setRequests(requestRepository); + RequestRepository requestRepositoryCopy = new RequestRepository(); + requestRepositoryCopy.addRequest(USER_NAME, request1); + requestRepositoryCopy.addRequest(USER_NAME, request2); + requestRepositoryCopy.addRequest(USER_NAME, request3); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); - - Assert.assertEquals(requestRepository.getAll().size(), - managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); - - managerController.turnOnInstancesMonitoring(); - - Assert.assertEquals(requestRepository.getAll().size(), - managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size()); + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); - Thread.sleep(timeDefault * 2); + Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); - Assert.assertEquals(requestRepository.getAll().size(), - managerController.getRequestsFromUser(ACCESS_TOKEN_ID).size());; + managerController.monitorInstances(); + Assert.assertEquals(0, getRequestsDeleted(requestRepositoryCopy).size()); } - - @Test - public void testMonitoringLostInstances() throws InterruptedException { - final int timeDefault = 100; + @Test + public void testMonitoringFulfilledRequestAndNotFoundInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); Token token = new Token("id", new Date(), new HashMap()); @@ -297,8 +283,7 @@ public void testMonitoringLostInstances() throws InterruptedException { managerController.setComputePlugin(computePlugin); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - managerController.turnOnInstancesMonitoring(); - + managerController.monitorInstances(); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); @@ -307,24 +292,23 @@ public void testMonitoringLostInstances() throws InterruptedException { Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); - Thread.sleep(timeDefault * 2); - + managerController.monitorInstances(); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); } } + @SuppressWarnings("unchecked") @Test - public void testMonitoringLostInstancesPersistent() throws InterruptedException { + public void testMonitoringFulfilledRequestAndPesistentInstance() throws InterruptedException { final int timeDefault = 100; - + final int timeDefaultSchedulePeriod = 10; Properties properties = new Properties(); properties.put("instance_monitoring_period", Integer.toString(timeDefault)); - properties.put("scheduler_period", Integer.toString(timeDefault)); - - managerController = new ManagerController(properties); + properties.put("scheduler_period", Integer.toString(timeDefaultSchedulePeriod)); + managerController = new ManagerController(properties); Token token = new Token("id", new Date(), new HashMap()); Map map = new HashMap(); map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); @@ -342,6 +326,9 @@ public void testMonitoringLostInstancesPersistent() throws InterruptedException ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), + Mockito.anyMap())).thenReturn("ok"); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { @@ -350,35 +337,33 @@ public void testMonitoringLostInstancesPersistent() throws InterruptedException Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); - managerController.turnOnInstancesMonitoring(); - + + managerController.monitorInstances(); boolean wasOpen = false; - for (int i = 0; i < 10; i++) { - Thread.sleep(20); - for (Request request : requestsFromUser) { + for (int i = 0; i < 50; i++) { + Thread.sleep(1); + for (Request request : requestsFromUser) { requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - if(request.getState().equals(RequestState.OPEN)) { + if (request.getState().equals(RequestState.OPEN)) { wasOpen = true; } } } - + Assert.assertTrue(wasOpen); - - Thread.sleep(timeDefault); + + Thread.sleep(timeDefaultSchedulePeriod * 100); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - for (Request request : requestsFromUser) { + for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); - } + } } @Test - public void testMonitoringInstances() throws InterruptedException { - final int timeDefault = 100; - + public void testMonitoringFulfilledRequestAndOnetimeInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Integer.toString(timeDefault)); + properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); Token token = new Token("id", new Date(), new HashMap()); @@ -397,8 +382,7 @@ public void testMonitoringInstances() throws InterruptedException { managerController.setComputePlugin(computePlugin); Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - managerController.turnOnInstancesMonitoring(); - + managerController.monitorInstances(); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); @@ -407,8 +391,7 @@ public void testMonitoringInstances() throws InterruptedException { Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenReturn(new Instance("id")); - Thread.sleep(timeDefault * 2); - + managerController.monitorInstances(); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); @@ -549,7 +532,6 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { - Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); @@ -609,9 +591,8 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + properties.put("scheduler_period", Long.toString(SCHEDULER_PERIOD)); managerController = new ManagerController(properties); // default instance count value is 1 From f9c272b1a42b99aa32f84aabd4718c28a946499f Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 19 May 2014 11:14:21 -0300 Subject: [PATCH 135/185] Refatoring ManagerController. --- .../manager/core/ManagerController.java | 53 ++++++++++++------- .../manager/occi/core/HeaderUtils.java | 1 - .../fogbowcloud/manager/occi/core/Token.java | 4 ++ .../manager/core/TestManagerController.java | 25 ++++++--- .../manager/occi/util/OCCITestHelper.java | 1 - 5 files changed, 58 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 7f4d12ca..68ce5c4a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -122,7 +122,7 @@ public void removeAllRequests(String authToken) { public void removeRequest(String authToken, String requestId) { LOGGER.debug("Removing requestId: " + requestId); checkRequestId(authToken, requestId); - requests.remove(requestId); + requests.remove(requestId); } private void checkRequestId(String authToken, String requestId) { @@ -143,7 +143,8 @@ public List getInstances(String authToken) { continue; } try { - instances.add(getInstance(authToken, instanceId, request)); + + instances.add(getInstance(request)); } catch (Exception e) { LOGGER.warn("Exception thown while getting instance " + instanceId + ".", e); } @@ -153,26 +154,25 @@ public List getInstances(String authToken) { public Instance getInstance(String authToken, String instanceId) { Request request = getRequestFromInstance(authToken, instanceId); - return getInstance(authToken, instanceId, request); + return getInstance(request); } - // TODO Review the needs of these args. Request object already has othe - // information - private Instance getInstance(String authToken, String instanceId, Request request) { + private Instance getInstance(Request request) { Instance instance = null; if (isLocal(request)) { - LOGGER.debug(instanceId + " is local, getting its information in the local cloud."); - instance = this.computePlugin.getInstance(authToken, instanceId); + LOGGER.debug(request.getInstanceId() + + " is local, getting its information in the local cloud."); + instance = this.computePlugin.getInstance(request.getToken().getAccessId(), + request.getInstanceId()); } else { - LOGGER.debug(instanceId + " is remote, going out to " + request.getMemberId() - + " to get its information."); + LOGGER.debug(request.getInstanceId() + " is remote, going out to " + + request.getMemberId() + " to get its information."); instance = getRemoteInstance(request); } String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); if (sshAddress != null) { instance.addAttribute(DefaultSSHTunnel.SSH_ADDRESS_ATT, sshAddress); } - return instance; } @@ -359,8 +359,8 @@ protected void monitorInstances() { for (Request request : requests.get(RequestState.FULFILLED)) { turnOffTimer = false; try { - getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); - } catch (OCCIException e) { // TODO Only NOT FOUND exception type? + getInstance(request); + } catch (OCCIException e) { updateRequestState(requests.get(request.getId())); } } @@ -369,7 +369,7 @@ protected void monitorInstances() { for (Request request : requests.get(RequestState.DELETED)) { turnOffTimer = false; try { - getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); + getInstance(request); } catch (OCCIException e) { requests.excluding(request.getId()); } @@ -397,19 +397,37 @@ public void run() { }, 0, tokenUpdatePeriod); } - // TODO Refactor! Think about not call updateToken to requests of same user protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { List allRequests = requests.getAll(); boolean turnOffTimer = true; + List usersUpdated = new ArrayList(); for (Request request : allRequests) { + boolean isUserUpdated = false; + for (String user : usersUpdated) { + if (user.equals(request.getUser())) { + isUserUpdated = true; + break; + } + } + if (!request.getState().equals(RequestState.CLOSED) - && !request.getState().equals(RequestState.FAILED)) { + && !request.getState().equals(RequestState.FAILED) && !isUserUpdated) { turnOffTimer = false; long validInterval = request.getToken().getExpirationDate().getTime() - dateUtils.currentTimeMillis(); if (validInterval < 2 * tokenUpdatePeriod) { Token newToken = identityPlugin.updateToken(request.getToken()); requests.get(request.getId()).setToken(newToken); + + for (Request requestByUser : requests.getByUser(request.getUser())) { + if (!requestByUser.getState().equals(RequestState.CLOSED) + && !requestByUser.getState().equals(RequestState.FAILED)) { + requests.get(requestByUser.getId()).getToken() + .setAccessId(newToken.getAccessId()); + } + } + + usersUpdated.add(request.getUser()); } } } @@ -455,7 +473,6 @@ private boolean submitLocalRequest(Request request) { instanceId = computePlugin.requestInstance(request.getToken().getAccessId(), request.getCategories(), request.getxOCCIAtt()); } catch (OCCIException e) { - // TODO check if this is the error code! if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; @@ -530,7 +547,7 @@ public Token getToken(Map attributesToken) { public Properties getProperties() { return properties; } - + public void setDateUtils(DateUtils dateUtils) { this.dateUtils = dateUtils; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java b/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java index 2b93512f..cde3070f 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/HeaderUtils.java @@ -4,7 +4,6 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index 6ad03213..4c8e3672 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -26,6 +26,10 @@ public String get(String attributeName) { public String getAccessId() { return this.accessId; } + + public void setAccessId(String accessId) { + this.accessId = accessId; + } public Date getExpirationDate() { return this.expirationDate; diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index f56f3680..b7f0768f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -132,18 +132,29 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { RequestRepository requestRepository = new RequestRepository(); Token token = new Token(firstTokenId, new Date(now + (4 * timeDefault)), new HashMap()); + Token token2 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + new HashMap()); + Token token3 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + new HashMap()); + Token token4 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + new HashMap()); + Token token5 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.OPEN); - Request request2 = new Request("id2", token, USER_NAME, null, null); + Request request2 = new Request("id2", token2, USER_NAME, null, null); request2.setState(RequestState.OPEN); - Request request3 = new Request("id3", token, USER_NAME, null, null); + Request request3 = new Request("id3", token3, USER_NAME, null, null); request3.setState(RequestState.OPEN); - Request request4 = new Request("id4", token, USER_NAME, null, null); + Request request4 = new Request("id4", token4, USER_NAME, null, null); request4.setState(RequestState.CLOSED); + Request request5 = new Request("id5", token5, USER_NAME, null, null); + request5.setState(RequestState.FAILED); requestRepository.addRequest(USER_NAME, request1); requestRepository.addRequest(USER_NAME, request2); requestRepository.addRequest(USER_NAME, request3); requestRepository.addRequest(USER_NAME, request4); + requestRepository.addRequest(USER_NAME, request5); managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); @@ -161,7 +172,8 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { for (Request request : requestsFromUser) { if (request.getState().equals(RequestState.OPEN)) { Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); - } else if (request.getState().equals(RequestState.CLOSED)) { + } else if (request.getState().equals(RequestState.CLOSED) + || request.getState().equals(RequestState.FAILED)) { Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); } } @@ -174,7 +186,8 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { for (Request request : requestsFromUser) { if (request.getState().equals(RequestState.OPEN)) { Assert.assertEquals(secontTokenId, request.getToken().getAccessId()); - } else if (request.getState().equals(RequestState.CLOSED)) { + } else if (request.getState().equals(RequestState.CLOSED) + || request.getState().equals(RequestState.FAILED)) { Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); } } @@ -353,7 +366,7 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup Assert.assertTrue(wasOpen); Thread.sleep(timeDefaultSchedulePeriod * 100); - + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 44a17bd0..02b7bc88 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -20,7 +20,6 @@ import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.occi.core.HeaderUtils; -import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.request.RequestRepository; import org.mockito.Mockito; From be4e9061540d9dd0a770e5abf1562473e9bc1761 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Mon, 19 May 2014 14:16:31 -0300 Subject: [PATCH 136/185] Adding certificate validation to ManagerController --- .../DefaultFederationMemberValidator.java | 22 ++- .../core/FederationMemberValidator.java | 5 +- .../manager/core/ManagerController.java | 128 +++++++++++------- .../manager/core/RoundRobinMemberPicker.java | 10 +- .../manager/xmpp/RequestInstanceHandler.java | 17 +-- .../TestDefaultFederationMemberValidator.java | 19 ++- 6 files changed, 114 insertions(+), 87 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java index 40eac357..c2ae6dbd 100644 --- a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java @@ -19,27 +19,23 @@ public class DefaultFederationMemberValidator implements FederationMemberValidat @Override public boolean canDonateTo(FederationMember member) { - boolean canDonate = false; X509Certificate cert = member.getResourcesInfo().getCert(); + try { + cert.checkValidity(); + } catch (Exception e) { + return false; + } + for (X509Certificate ca: validCAs) { try { cert.verify(ca.getPublicKey()); - canDonate = true; - } catch (InvalidKeyException e) { - } catch (CertificateException e) { - } catch (NoSuchAlgorithmException e) { - } catch (NoSuchProviderException e) { - } catch (SignatureException e) { + return true; + } catch (Exception e) { } } - try { - cert.checkValidity(); - } catch (Exception e) { - canDonate = false; - } - return canDonate ; + return false; } @Override diff --git a/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java index 71cd7d77..cc57d565 100644 --- a/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/FederationMemberValidator.java @@ -1,13 +1,10 @@ package org.fogbowcloud.manager.core; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateNotYetValidException; - import org.fogbowcloud.manager.core.model.FederationMember; public interface FederationMemberValidator { - public boolean canDonateTo(FederationMember member) throws CertificateExpiredException, CertificateNotYetValidException; + public boolean canDonateTo(FederationMember member); public boolean canReceiveFrom(FederationMember member); diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 7f4d12ca..e68f1745 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -36,7 +36,8 @@ public class ManagerController { - private static final Logger LOGGER = Logger.getLogger(ManagerController.class); + private static final Logger LOGGER = Logger + .getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 @@ -58,6 +59,7 @@ public class ManagerController { private IdentityPlugin identityPlugin; private Properties properties; private PacketSender packetSender; + private FederationMemberValidator validator = new DefaultFederationMemberValidator(); private DateUtils dateUtils = new DateUtils(); private SSHTunnel sshTunnel = new DefaultSSHTunnel(); @@ -122,14 +124,16 @@ public void removeAllRequests(String authToken) { public void removeRequest(String authToken, String requestId) { LOGGER.debug("Removing requestId: " + requestId); checkRequestId(authToken, requestId); - requests.remove(requestId); + requests.remove(requestId); } private void checkRequestId(String authToken, String requestId) { String user = getUser(authToken); if (requests.get(user, requestId) == null) { - LOGGER.debug("User " + user + " does not have requesId " + requestId); - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + LOGGER.debug("User " + user + " does not have requesId " + + requestId); + throw new OCCIException(ErrorType.NOT_FOUND, + ResponseConstants.NOT_FOUND); } } @@ -145,7 +149,8 @@ public List getInstances(String authToken) { try { instances.add(getInstance(authToken, instanceId, request)); } catch (Exception e) { - LOGGER.warn("Exception thown while getting instance " + instanceId + ".", e); + LOGGER.warn("Exception thown while getting instance " + + instanceId + ".", e); } } return instances; @@ -158,17 +163,20 @@ public Instance getInstance(String authToken, String instanceId) { // TODO Review the needs of these args. Request object already has othe // information - private Instance getInstance(String authToken, String instanceId, Request request) { + private Instance getInstance(String authToken, String instanceId, + Request request) { Instance instance = null; if (isLocal(request)) { - LOGGER.debug(instanceId + " is local, getting its information in the local cloud."); + LOGGER.debug(instanceId + + " is local, getting its information in the local cloud."); instance = this.computePlugin.getInstance(authToken, instanceId); } else { - LOGGER.debug(instanceId + " is remote, going out to " + request.getMemberId() - + " to get its information."); + LOGGER.debug(instanceId + " is remote, going out to " + + request.getMemberId() + " to get its information."); instance = getRemoteInstance(request); } - String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); + String sshAddress = request + .getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); if (sshAddress != null) { instance.addAttribute(DefaultSSHTunnel.SSH_ADDRESS_ATT, sshAddress); } @@ -197,7 +205,8 @@ public void removeInstance(String authToken, String instanceId) { removeInstance(authToken, instanceId, request); } - private void removeInstance(String authToken, String instanceId, Request request) { + private void removeInstance(String authToken, String instanceId, + Request request) { sshTunnel.release(request); if (isLocal(request)) { this.computePlugin.removeInstance(authToken, instanceId); @@ -211,8 +220,8 @@ private void removeInstance(String authToken, String instanceId, Request request private void updateRequestState(Request request) { if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null - && request.getAttValue(RequestAttribute.TYPE.getValue()).equals( - RequestType.PERSISTENT.getValue())) { + && request.getAttValue(RequestAttribute.TYPE.getValue()) + .equals(RequestType.PERSISTENT.getValue())) { request.setState(RequestState.OPEN); if (!scheduled) { scheduleRequests(); @@ -233,12 +242,14 @@ public Request getRequestFromInstance(String authToken, String instanceId) { for (Request request : userRequests) { if (instanceId.equals(request.getInstanceId())) { if (!request.getUser().equals(user)) { - throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); + throw new OCCIException(ErrorType.UNAUTHORIZED, + ResponseConstants.UNAUTHORIZED); } return request; } } - throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); + throw new OCCIException(ErrorType.NOT_FOUND, + ResponseConstants.NOT_FOUND); } private boolean isLocal(Request request) { @@ -251,26 +262,34 @@ public Request getRequest(String authToken, String requestId) { return requests.get(requestId); } - public String submitRequestForRemoteMember(List categories, + public String submitRequestForRemoteMember(String memberId, List categories, Map xOCCIAtt) { - LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " - + xOCCIAtt + " for remote member."); - String token = getFederationUserToken().getAccessId();// (OCCIHeaders.X_TOKEN_ACCESS_ID); - try { - return computePlugin.requestInstance(token, categories, xOCCIAtt); - } catch (OCCIException e) { - if (e.getStatus().getCode() == HttpStatus.SC_BAD_REQUEST) { - return null; + for (FederationMember member: members) { + if (member.getResourcesInfo().getId().equals(memberId)) { + if (validator.canReceiveFrom(member)) { + LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + + xOCCIAtt + " for remote member."); + String token = getFederationUserToken().getAccessId();// (OCCIHeaders.X_TOKEN_ACCESS_ID); + try { + return computePlugin.requestInstance(token, categories, xOCCIAtt); + } catch (OCCIException e) { + if (e.getStatus().getCode() == HttpStatus.SC_BAD_REQUEST) { + return null; + } + throw e; + } + } } - throw e; } + return null; } protected Token getFederationUserToken() { Map tokenAttributes = new HashMap(); String username = properties.getProperty("federation_user_name"); String password = properties.getProperty("federation_user_password"); - String tenantName = properties.getProperty("federation_user_tenant_name"); + String tenantName = properties + .getProperty("federation_user_tenant_name"); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, username); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); @@ -288,7 +307,8 @@ public Instance getInstanceForRemoteMember(String instanceId) { try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { - LOGGER.warn("Exception while getting instance " + instanceId + " for remote member.", e); + LOGGER.warn("Exception while getting instance " + instanceId + + " for remote member.", e); if (e.getStatus().getCode() == HttpStatus.SC_NOT_FOUND) { return null; } @@ -302,21 +322,22 @@ public void removeInstanceForRemoteMember(String instanceId) { computePlugin.removeInstance(token, instanceId); } - public List createRequests(String authToken, List categories, - Map xOCCIAtt) { + public List createRequests(String authToken, + List categories, Map xOCCIAtt) { String user = getUser(authToken); Token userToken = identityPlugin.getToken(authToken); LOGGER.debug("User Token: " + userToken); - Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT - .getValue())); + Integer instanceCount = Integer.valueOf(xOCCIAtt + .get(RequestAttribute.INSTANCE_COUNT.getValue())); LOGGER.info("Request " + instanceCount + " instances"); List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, userToken, user, categories, xOCCIAtt); + Request request = new Request(requestId, userToken, user, + categories, xOCCIAtt); try { sshTunnel.create(properties, request); } catch (Exception e) { @@ -339,7 +360,8 @@ public List createRequests(String authToken, List categories, protected void turnOnInstancesMonitoring() { instanceMonitoringOn = true; - String instanceMonitoringPeriodStr = properties.getProperty("instance_monitoring_period"); + String instanceMonitoringPeriodStr = properties + .getProperty("instance_monitoring_period"); final long instanceMonitoringPeriod = instanceMonitoringPeriodStr == null ? DEFAULT_INSTANCE_MONITORING_PERIOD : Long.valueOf(instanceMonitoringPeriodStr); @@ -359,7 +381,8 @@ protected void monitorInstances() { for (Request request : requests.get(RequestState.FULFILLED)) { turnOffTimer = false; try { - getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); + getInstance(request.getToken().getAccessId(), + request.getInstanceId(), request); } catch (OCCIException e) { // TODO Only NOT FOUND exception type? updateRequestState(requests.get(request.getId())); } @@ -369,7 +392,8 @@ protected void monitorInstances() { for (Request request : requests.get(RequestState.DELETED)) { turnOffTimer = false; try { - getInstance(request.getToken().getAccessId(), request.getInstanceId(), request); + getInstance(request.getToken().getAccessId(), + request.getInstanceId(), request); } catch (OCCIException e) { requests.excluding(request.getId()); } @@ -384,7 +408,8 @@ protected void monitorInstances() { private void turnOnTokenUpdating() { tokenUpdatingOn = true; - String tokenUpdatePeriodStr = properties.getProperty("token_update_period"); + String tokenUpdatePeriodStr = properties + .getProperty("token_update_period"); final long tokenUpdatePeriod = tokenUpdatePeriodStr == null ? DEFAULT_TOKEN_UPDATE_PERIOD : Long.valueOf(tokenUpdatePeriodStr); @@ -405,10 +430,12 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { if (!request.getState().equals(RequestState.CLOSED) && !request.getState().equals(RequestState.FAILED)) { turnOffTimer = false; - long validInterval = request.getToken().getExpirationDate().getTime() + long validInterval = request.getToken().getExpirationDate() + .getTime() - dateUtils.currentTimeMillis(); if (validInterval < 2 * tokenUpdatePeriod) { - Token newToken = identityPlugin.updateToken(request.getToken()); + Token newToken = identityPlugin.updateToken(request + .getToken()); requests.get(request.getId()).setToken(newToken); } } @@ -429,10 +456,11 @@ private boolean submitRemoteRequest(Request request) { String memberAddress = member.getResourcesInfo().getId(); request.setMemberId(memberAddress); - LOGGER.info("Submiting request " + request + " to member " + memberAddress); + LOGGER.info("Submiting request " + request + " to member " + + memberAddress); - String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, memberAddress, - packetSender); + String remoteInstanceId = ManagerPacketHelper.remoteRequest(request, + memberAddress, packetSender); if (remoteInstanceId == null) { return false; } @@ -452,8 +480,9 @@ private boolean submitLocalRequest(Request request) { LOGGER.info("Submiting local request " + request); try { - instanceId = computePlugin.requestInstance(request.getToken().getAccessId(), - request.getCategories(), request.getxOCCIAtt()); + instanceId = computePlugin.requestInstance(request.getToken() + .getAccessId(), request.getCategories(), request + .getxOCCIAtt()); } catch (OCCIException e) { // TODO check if this is the error code! if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { @@ -479,8 +508,8 @@ private boolean submitLocalRequest(Request request) { private void scheduleRequests() { scheduled = true; String schedulerPeriodStr = properties.getProperty("scheduler_period"); - long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long - .valueOf(schedulerPeriodStr); + long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD + : Long.valueOf(schedulerPeriodStr); requestSchedulerTimer = new Timer(); requestSchedulerTimer.scheduleAtFixedRate(new TimerTask() { @@ -501,7 +530,8 @@ private void checkAndSubmitOpenRequests() { for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } - allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); + allFulfilled &= submitLocalRequest(request) + || submitRemoteRequest(request); } else if (request.isExpired()) { request.setState(RequestState.CLOSED); } else { @@ -530,8 +560,12 @@ public Token getToken(Map attributesToken) { public Properties getProperties() { return properties; } - + public void setDateUtils(DateUtils dateUtils) { this.dateUtils = dateUtils; } + + public FederationMemberValidator getValidator() { + return validator; + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java index 5c4e05d4..af5cd6ed 100644 --- a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java @@ -7,7 +7,7 @@ public class RoundRobinMemberPicker implements FederationMemberPicker { private int current = -1; - + @Override public FederationMember pick(ManagerController facade) { List members = facade.getMembers(); @@ -16,13 +16,15 @@ public FederationMember pick(ManagerController facade) { } current = (current + 1) % members.size(); FederationMember currentMember = members.get(current); - + String myJid = facade.getProperties().getProperty("xmpp_jid"); - if (currentMember.getResourcesInfo().getId().equals(myJid) && members.size() > 1) { + if (currentMember.getResourcesInfo().getId().equals(myJid) + && members.size() > 1 + && facade.getValidator().canDonateTo(currentMember)) { current = (current + 1) % members.size(); currentMember = members.get(current); } - + return members.get(current); } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java index fdd68cb3..d4483f37 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java @@ -29,26 +29,27 @@ public IQ handle(IQ query) { List categories = new LinkedList(); List categoriesEl = queryEl.elements("category"); for (Element categoryEl : categoriesEl) { - Category category = new Category( - categoryEl.elementText("term"), - categoryEl.elementText("scheme"), + Category category = new Category(categoryEl.elementText("term"), + categoryEl.elementText("scheme"), categoryEl.elementText("class")); categories.add(category); } Map xOCCIAtt = new HashMap(); List attributesEl = queryEl.elements("attribute"); for (Element attributeEl : attributesEl) { - xOCCIAtt.put(attributeEl.attributeValue("var"), attributeEl.element("value").getText()); + xOCCIAtt.put(attributeEl.attributeValue("var"), attributeEl + .element("value").getText()); } - + IQ response = IQ.createResultIQ(query); try { - String instanceId = facade.submitRequestForRemoteMember(categories, xOCCIAtt); + String instanceId = facade.submitRequestForRemoteMember(query + .getFrom().toBareJID(), categories, xOCCIAtt); if (instanceId == null) { response.setError(Condition.item_not_found); } else { - Element queryResponseEl = response.getElement().addElement("query", - ManagerXmppComponent.REQUEST_NAMESPACE); + Element queryResponseEl = response.getElement().addElement( + "query", ManagerXmppComponent.REQUEST_NAMESPACE); queryResponseEl.addElement("instance").addElement("id") .setText(instanceId); } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java index bcc86398..85c7be0f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java @@ -9,6 +9,7 @@ import java.security.PublicKey; import java.security.SignatureException; import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; @@ -57,6 +58,7 @@ public void testValidMember() throws CertificateException, IOException, Mockito.doNothing().when(mockCertificate).checkValidity(); Mockito.doNothing().when(mockCertificate).verify(publicKey); Assert.assertTrue(validator.canDonateTo(member)); + Assert.assertTrue(validator.canReceiveFrom(member)); } @Test @@ -68,20 +70,15 @@ public void testInvalidMember() throws CertificateException, IOException, .verify(publicKey); Mockito.doNothing().when(mockCertificate).checkValidity(); Assert.assertFalse(validator.canDonateTo(member)); + Assert.assertFalse(validator.canReceiveFrom(member)); } @Test - public void testExpiredMember() throws CertificateException, IOException, - InvalidKeyException, NoSuchAlgorithmException, - NoSuchProviderException, SignatureException { - // this method is invalid to get the exception here-- how to do that? - // use a real expired certificate? - - //gambiarra - Mockito.doThrow(new IllegalArgumentException()) - .when(mockCertificate).checkValidity(); - - Mockito.doNothing().when(mockCertificate).verify(publicKey); + public void testExpiredMember() throws Exception { + Mockito.doThrow(new CertificateExpiredException()) + .when(mockCertificate).checkValidity(); + Mockito.doNothing().when(mockCertificate).verify(publicKey); Assert.assertFalse(validator.canDonateTo(member)); + Assert.assertFalse(validator.canReceiveFrom(member)); } } From fae690dfabbb34989fac493c82f2651ea753b7c8 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 19 May 2014 14:38:24 -0300 Subject: [PATCH 137/185] Refatoring ManagerController --- .../org/fogbowcloud/manager/core/ManagerController.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 68ce5c4a..717a347e 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -39,8 +39,7 @@ public class ManagerController { private static final Logger LOGGER = Logger.getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes - private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 - // minutes + private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 minutes private boolean scheduled = false; private boolean tokenUpdatingOn = false; @@ -255,7 +254,7 @@ public String submitRequestForRemoteMember(List categories, Map xOCCIAtt) { LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); - String token = getFederationUserToken().getAccessId();// (OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId(); try { return computePlugin.requestInstance(token, categories, xOCCIAtt); } catch (OCCIException e) { @@ -284,7 +283,7 @@ protected Token getFederationUserToken() { public Instance getInstanceForRemoteMember(String instanceId) { LOGGER.info("Getting instance " + instanceId + " for remote member."); - String token = getFederationUserToken().getAccessId();// get(OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId(); try { return computePlugin.getInstance(token, instanceId); } catch (OCCIException e) { @@ -298,7 +297,7 @@ public Instance getInstanceForRemoteMember(String instanceId) { public void removeInstanceForRemoteMember(String instanceId) { LOGGER.info("Removing instance " + instanceId + " for remote member."); - String token = getFederationUserToken().getAccessId();// (OCCIHeaders.X_TOKEN_ACCESS_ID); + String token = getFederationUserToken().getAccessId(); computePlugin.removeInstance(token, instanceId); } From 8c1c6905ce78b3ad8bbb59f2f8a20a7cb571088f Mon Sep 17 00:00:00 2001 From: giovannifs Date: Mon, 19 May 2014 18:05:21 -0300 Subject: [PATCH 138/185] Refactor (There are tests not OK yet) --- .../manager/core/ManagerController.java | 160 +++++++----------- .../manager/core/ManagerTimer.java | 28 +++ .../manager/core/plugins/IdentityPlugin.java | 15 +- .../openstack/OpenStackIdentityPlugin.java | 39 ++--- .../fogbowcloud/manager/occi/core/Token.java | 18 +- .../occi/request/RequestRepository.java | 3 +- .../manager/occi/request/RequestState.java | 18 ++ .../manager/xmpp/RequestInstanceHandler.java | 2 +- .../manager/core/TestManagerController.java | 72 ++++---- .../manager/occi/TestDeleteCompute.java | 6 +- .../manager/occi/TestDeleteRequest.java | 6 +- .../manager/occi/TestGetCompute.java | 10 +- .../manager/occi/TestGetRequest.java | 12 +- .../manager/occi/TestOCCIApplication.java | 6 +- .../manager/occi/TestPostRequest.java | 6 +- .../manager/occi/TestTokenServerResource.java | 6 +- .../occi/plugins/TestIdentityOpenStack.java | 18 +- .../manager/occi/util/PluginHelper.java | 2 +- .../xmpp/TestDeleteRemoteInstance.java | 6 +- .../manager/xmpp/TestGetRemoteInstance.java | 6 +- .../xmpp/TestRequestRemoteInstance.java | 2 +- .../manager/xmpp/util/ManagerTestHelper.java | 9 +- 22 files changed, 230 insertions(+), 220 deletions(-) create mode 100644 src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 717a347e..ab36fe25 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -6,7 +6,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.Timer; import java.util.TimerTask; import java.util.UUID; @@ -41,14 +40,11 @@ public class ManagerController { private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 minutes - private boolean scheduled = false; - private boolean tokenUpdatingOn = false; - private boolean instanceMonitoringOn = false; - private Timer requestSchedulerTimer; - private Timer tokenUpdaterTimer; - private Timer instanceMonitoringTimer; + private ManagerTimer requestSchedulerTimer = new ManagerTimer(); + private ManagerTimer tokenUpdaterTimer = new ManagerTimer(); + private ManagerTimer instanceMonitoringTimer = new ManagerTimer(); - private Token tokenMemberLocal; + private Token federationUserToken; private List members = new LinkedList(); private RequestRepository requests = new RequestRepository(); private FederationMemberPicker memberPicker = new RoundRobinMemberPicker(); @@ -103,8 +99,8 @@ public ResourcesInfo getResourcesInfo() { return resourcesInfo; } - public String getUser(String authToken) { - return identityPlugin.getUser(authToken); + public String getUser(String accessId) { + return identityPlugin.getToken(accessId).getUser(); } public List getRequestsFromUser(String authToken) { @@ -152,7 +148,7 @@ public List getInstances(String authToken) { } public Instance getInstance(String authToken, String instanceId) { - Request request = getRequestFromInstance(authToken, instanceId); + Request request = getRequestForInstance(authToken, instanceId); return getInstance(request); } @@ -192,7 +188,7 @@ public void removeInstances(String authToken) { } public void removeInstance(String authToken, String instanceId) { - Request request = getRequestFromInstance(authToken, instanceId); + Request request = getRequestForInstance(authToken, instanceId); removeInstance(authToken, instanceId, request); } @@ -205,15 +201,13 @@ private void removeInstance(String authToken, String instanceId, Request request } request.setInstanceId(null); request.setMemberId(null); - updateRequestState(request); + instanceRemoved(request); } - private void updateRequestState(Request request) { - if (request.getAttValue(RequestAttribute.TYPE.getValue()) != null - && request.getAttValue(RequestAttribute.TYPE.getValue()).equals( - RequestType.PERSISTENT.getValue())) { + private void instanceRemoved(Request request) { + if (isPersistent(request)) { request.setState(RequestState.OPEN); - if (!scheduled) { + if (!requestSchedulerTimer.isScheduled()) { scheduleRequests(); } } else { @@ -221,12 +215,18 @@ private void updateRequestState(Request request) { } } + private boolean isPersistent(Request request) { + return request.getAttValue(RequestAttribute.TYPE.getValue()) != null + && request.getAttValue(RequestAttribute.TYPE.getValue()).equals( + RequestType.PERSISTENT.getValue()); + } + private void removeRemoteInstance(Request request) { ManagerPacketHelper.deleteRemoteInstace(request, packetSender); } - public Request getRequestFromInstance(String authToken, String instanceId) { - String user = getUser(authToken); + public Request getRequestForInstance(String accessId, String instanceId) { + String user = getUser(accessId); LOGGER.debug("Getting instance " + instanceId + " of user " + user); List userRequests = requests.getAll(); for (Request request : userRequests) { @@ -244,13 +244,13 @@ private boolean isLocal(Request request) { return request.getMemberId() == null; } - public Request getRequest(String authToken, String requestId) { + public Request getRequest(String accessId, String requestId) { LOGGER.debug("Getting requestId " + requestId); - checkRequestId(authToken, requestId); + checkRequestId(accessId, requestId); return requests.get(requestId); } - public String submitRequestForRemoteMember(List categories, + public String createInstanceForRemoteMember(List categories, Map xOCCIAtt) { LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); @@ -266,19 +266,22 @@ public String submitRequestForRemoteMember(List categories, } protected Token getFederationUserToken() { - Map tokenAttributes = new HashMap(); + if (federationUserToken != null + && identityPlugin.isValid(federationUserToken.getAccessId())) { + return this.federationUserToken; + } + + Map federationUserCredentials = new HashMap(); String username = properties.getProperty("federation_user_name"); String password = properties.getProperty("federation_user_password"); String tenantName = properties.getProperty("federation_user_tenant_name"); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, username); - tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, password); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); + federationUserCredentials.put(OCCIHeaders.X_TOKEN_USER, username); + federationUserCredentials.put(OCCIHeaders.X_TOKEN_PASS, password); + federationUserCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - if (tokenMemberLocal == null || tokenMemberLocal.isExpiredToken()) { - Token token = identityPlugin.getToken(tokenAttributes); - this.tokenMemberLocal = token; - } - return this.tokenMemberLocal; + Token token = identityPlugin.createToken(federationUserCredentials); + this.federationUserToken = token; + return federationUserToken; } public Instance getInstanceForRemoteMember(String instanceId) { @@ -326,23 +329,21 @@ public List createRequests(String authToken, List categories, currentRequests.add(request); requests.addRequest(user, request); } - if (!scheduled) { + if (!requestSchedulerTimer.isScheduled()) { scheduleRequests(); } - if (!tokenUpdatingOn) { - turnOnTokenUpdating(); + if (!tokenUpdaterTimer.isScheduled()) { + triggerTokenUpdater(); } return currentRequests; } - protected void turnOnInstancesMonitoring() { - instanceMonitoringOn = true; + protected void triggerInstancesMonitor() { String instanceMonitoringPeriodStr = properties.getProperty("instance_monitoring_period"); final long instanceMonitoringPeriod = instanceMonitoringPeriodStr == null ? DEFAULT_INSTANCE_MONITORING_PERIOD : Long.valueOf(instanceMonitoringPeriodStr); - instanceMonitoringTimer = new Timer(); instanceMonitoringTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { @@ -353,41 +354,33 @@ public void run() { protected void monitorInstances() { boolean turnOffTimer = true; - - // monitoring fulfilled requests - for (Request request : requests.get(RequestState.FULFILLED)) { - turnOffTimer = false; - try { - getInstance(request); - } catch (OCCIException e) { - updateRequestState(requests.get(request.getId())); - } - } - - // monitoring deleted requests - for (Request request : requests.get(RequestState.DELETED)) { - turnOffTimer = false; - try { - getInstance(request); - } catch (OCCIException e) { - requests.excluding(request.getId()); - } + + for (Request request : requests.getAll()) { + if (request.getState().in(RequestState.FULFILLED, RequestState.DELETED)){ + turnOffTimer = false; + try { + getInstance(request); + } catch (OCCIException e) { + if (request.getState().in(RequestState.FULFILLED)){ + instanceRemoved(requests.get(request.getId())); + } else if (request.getState().in(RequestState.DELETED)){ + requests.exclude(request.getId()); + } + } + } } if (turnOffTimer) { LOGGER.info("There are not requests."); instanceMonitoringTimer.cancel(); - instanceMonitoringOn = false; } } - private void turnOnTokenUpdating() { - tokenUpdatingOn = true; + private void triggerTokenUpdater() { String tokenUpdatePeriodStr = properties.getProperty("token_update_period"); final long tokenUpdatePeriod = tokenUpdatePeriodStr == null ? DEFAULT_TOKEN_UPDATE_PERIOD : Long.valueOf(tokenUpdatePeriodStr); - tokenUpdaterTimer = new Timer(); tokenUpdaterTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { @@ -399,34 +392,15 @@ public void run() { protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { List allRequests = requests.getAll(); boolean turnOffTimer = true; - List usersUpdated = new ArrayList(); - for (Request request : allRequests) { - boolean isUserUpdated = false; - for (String user : usersUpdated) { - if (user.equals(request.getUser())) { - isUserUpdated = true; - break; - } - } - if (!request.getState().equals(RequestState.CLOSED) - && !request.getState().equals(RequestState.FAILED) && !isUserUpdated) { + for (Request request : allRequests) { + if (request.getState().notIn(RequestState.CLOSED, RequestState.FAILED)) { turnOffTimer = false; long validInterval = request.getToken().getExpirationDate().getTime() - dateUtils.currentTimeMillis(); if (validInterval < 2 * tokenUpdatePeriod) { - Token newToken = identityPlugin.updateToken(request.getToken()); + Token newToken = identityPlugin.createToken(request.getToken()); requests.get(request.getId()).setToken(newToken); - - for (Request requestByUser : requests.getByUser(request.getUser())) { - if (!requestByUser.getState().equals(RequestState.CLOSED) - && !requestByUser.getState().equals(RequestState.FAILED)) { - requests.get(requestByUser.getId()).getToken() - .setAccessId(newToken.getAccessId()); - } - } - - usersUpdated.add(request.getUser()); } } } @@ -434,11 +408,10 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { if (turnOffTimer) { LOGGER.info("There are not requests."); tokenUpdaterTimer.cancel(); - tokenUpdatingOn = false; } } - private boolean submitRemoteRequest(Request request) { + private boolean createRemoteInstance(Request request) { FederationMember member = memberPicker.pick(this); if (member == null) { return false; @@ -456,13 +429,13 @@ private boolean submitRemoteRequest(Request request) { request.setState(RequestState.FULFILLED); request.setInstanceId(remoteInstanceId); - if (!instanceMonitoringOn) { - turnOnInstancesMonitoring(); + if (!instanceMonitoringTimer.isScheduled()) { + triggerInstancesMonitor(); } return true; } - private boolean submitLocalRequest(Request request) { + private boolean createLocalInstance(Request request) { request.setMemberId(null); String instanceId = null; @@ -486,19 +459,17 @@ private boolean submitLocalRequest(Request request) { request.setInstanceId(instanceId); request.setState(RequestState.FULFILLED); LOGGER.debug("Fulfilled Request: " + request); - if (!instanceMonitoringOn) { - turnOnInstancesMonitoring(); + if (!instanceMonitoringTimer.isScheduled()) { + triggerInstancesMonitor(); } return true; } private void scheduleRequests() { - scheduled = true; String schedulerPeriodStr = properties.getProperty("scheduler_period"); long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long .valueOf(schedulerPeriodStr); - requestSchedulerTimer = new Timer(); requestSchedulerTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { @@ -517,7 +488,7 @@ private void checkAndSubmitOpenRequests() { for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } - allFulfilled &= submitLocalRequest(request) || submitRemoteRequest(request); + allFulfilled &= createLocalInstance(request) || createRemoteInstance(request); } else if (request.isExpired()) { request.setState(RequestState.CLOSED); } else { @@ -527,7 +498,6 @@ private void checkAndSubmitOpenRequests() { if (allFulfilled) { LOGGER.info("All request fulfilled."); requestSchedulerTimer.cancel(); - scheduled = false; } } @@ -540,7 +510,7 @@ public void setRequests(RequestRepository requests) { } public Token getToken(Map attributesToken) { - return identityPlugin.getToken(attributesToken); + return identityPlugin.createToken(attributesToken); } public Properties getProperties() { diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java b/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java new file mode 100644 index 00000000..22b067af --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java @@ -0,0 +1,28 @@ +package org.fogbowcloud.manager.core; + +import java.util.Timer; +import java.util.TimerTask; + +public class ManagerTimer { + + private Timer timer; + private boolean scheduled; + + public void scheduleAtFixedRate(TimerTask task, long delay, long period) { + timer = new Timer(); + timer.scheduleAtFixedRate(task, delay, period); + scheduled = true; + } + + public void cancel() { + if (timer != null) { + timer.cancel(); + } + scheduled = false; + } + + public boolean isScheduled() { + return scheduled; + } + +} diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index 06158bb7..97167dd0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -4,16 +4,13 @@ import org.fogbowcloud.manager.occi.core.Token; -//TODO Refactor review the need of methods public interface IdentityPlugin { - public String getUser(String tokenId); - - public String getTokenExpiresDate(String tokenId); - - public Token getToken(Map tokenCredentials); - - public Token updateToken(Token token); + public Token createToken(Map userCredentials); - public Token getToken(String authToken); + public Token createToken(Token token); + + public Token getToken(String accessId); + + public boolean isValid(String accessId); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index d039813c..8b149f72 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -54,17 +54,6 @@ public OpenStackIdentityPlugin(Properties properties) { this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } - @Override - public String getTokenExpiresDate(String tokenId) { - Token token = getToken(tokenId); - return token.getExpirationDate().toString(); - } - - public String getUser(String tokenId) { - Token token = getToken(tokenId); - return token.get(OCCIHeaders.X_TOKEN_USER); - } - public String getResponseJson(String tokenId) { HttpResponse response; String responseStr = null; @@ -86,7 +75,7 @@ public String getResponseJson(String tokenId) { } @Override - public Token getToken(Map tokenAttributes) { + public Token createToken(Map tokenAttributes) { HttpResponse response; String responseStr = null; try { @@ -120,7 +109,7 @@ public Token getToken(Map tokenAttributes) { } @Override - public Token updateToken(Token token) { + public Token createToken(Token token) { HttpResponse response; String responseStr = null; try { @@ -170,12 +159,15 @@ private Token getTokenFromJson(String responseStr) { String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); String tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( NAME_KEYSTONE); - String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); + String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); + + String user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) + .getString(NAME_KEYSTONE); attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); attributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - return new Token(token, getDate(expirationDateToken), attributes); + return new Token(token, user, getDate(expirationDateToken), attributes); } catch (Exception e) { LOGGER.error("Exception while getting token from json.", e); return null; @@ -195,9 +187,8 @@ private Date getDate(String expirationDateStr) { } @Override - public Token getToken(String tokenId) { - String responseJson = getResponseJson(tokenId); - String accessId = tokenId; + public Token getToken(String accessId) { + String responseJson = getResponseJson(accessId); long expirationTimeMillis = 0; String user = null; try { @@ -221,7 +212,17 @@ public Token getToken(String tokenId) { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, user); - return new Token(accessId, new Date(expirationTimeMillis), tokenAttributes); + return new Token(accessId, user, new Date(expirationTimeMillis), tokenAttributes); + } + + @Override + public boolean isValid(String accessId) { + try{ + getToken(accessId); + return true; + } catch (OCCIException e){ + return false; + } } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index 4c8e3672..09b9c223 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -9,12 +9,14 @@ public class Token { private Map attributes; private String accessId; + private String user; private Date expirationDate; private DateUtils dateUtils = new DateUtils(); - //TODO Check invalid values - public Token(String accessId, Date expirationTime, Map attributes) { + // TODO Check invalid values + public Token(String accessId, String user, Date expirationTime, Map attributes) { this.accessId = accessId; + this.user = user; this.expirationDate = expirationTime; this.attributes = attributes; } @@ -26,10 +28,6 @@ public String get(String attributeName) { public String getAccessId() { return this.accessId; } - - public void setAccessId(String accessId) { - this.accessId = accessId; - } public Date getExpirationDate() { return this.expirationDate; @@ -49,7 +47,11 @@ public void setDateUtils(DateUtils dateUtils) { } public String toString() { - return "AccessId: " + accessId + ", expirationDate: " + expirationDate + " attributes: " - + attributes; + return "AccessId: " + accessId + ", User: " + user + ", expirationDate: " + expirationDate + + " attributes: " + attributes; + } + + public String getUser() { + return this.user; } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index 7383afca..aa6fc5f2 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -108,7 +108,7 @@ public void remove(String requestId) { } } - public void excluding(String requestId) { + public void exclude(String requestId) { LOGGER.debug("Excluing requestId " + requestId); for (List userRequests : requests.values()) { @@ -121,7 +121,6 @@ public void excluding(String requestId) { } } } - } public List getAll() { diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java index b3852d77..12954da3 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java @@ -28,4 +28,22 @@ private RequestState(String value) { public String getValue() { return this.value; } + + public boolean in(RequestState... requestStates) { + for (RequestState requestState : requestStates) { + if (requestState.equals(this)){ + return true; + } + } + return false; + } + + public boolean notIn(RequestState... requestStates) { + for (RequestState requestState : requestStates) { + if (requestState.equals(this)){ + return false; + } + } + return true; + } } diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java index fdd68cb3..d516d649 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/RequestInstanceHandler.java @@ -43,7 +43,7 @@ public IQ handle(IQ query) { IQ response = IQ.createResultIQ(query); try { - String instanceId = facade.submitRequestForRemoteMember(categories, xOCCIAtt); + String instanceId = facade.createInstanceForRemoteMember(categories, xOCCIAtt); if (instanceId == null) { response.setError(Condition.item_not_found); } else { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index b7f0768f..e44299e5 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -62,8 +62,8 @@ public void setUp() throws Exception { managerController = new ManagerController(new Properties()); managerTestHelper = new ManagerTestHelper(); HashMap tokenAttr = new HashMap(); - tokenAttr.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - userToken = new Token(ACCESS_TOKEN_ID, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); +// tokenAttr.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + userToken = new Token(ACCESS_TOKEN_ID, USER_NAME, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); } @Test @@ -85,18 +85,18 @@ public void testGetFederationMember() throws InterruptedException { Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token = new Token(ACCESS_TOKEN_ID, new Date(expirationTime), attributesTokenReturn); +// attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(expirationTime), attributesTokenReturn); Map attributesTokenReturn2 = new HashMap(); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); +// attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token2 = new Token(ACCESS_TOKEN_ID_2, new Date(expirationTime + LONG_TIME), + Token token2 = new Token(ACCESS_TOKEN_ID_2, USER_NAME, new Date(expirationTime + LONG_TIME), attributesTokenReturn2); - Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); + Mockito.when(openStackidentityPlugin.createToken(attributesToken)).thenReturn(token, token2); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token @@ -130,15 +130,15 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { DateUtils dateUtils = Mockito.mock(DateUtils.class); RequestRepository requestRepository = new RequestRepository(); - Token token = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), new HashMap()); - Token token2 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token2 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), new HashMap()); - Token token3 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token3 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), new HashMap()); - Token token4 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token4 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), new HashMap()); - Token token5 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token5 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.OPEN); @@ -158,10 +158,10 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Token tokenUpdatedFirstTime = new Token(secontTokenId, new Date(System.currentTimeMillis() +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Token tokenUpdatedFirstTime = new Token(secontTokenId, USER_NAME, new Date(System.currentTimeMillis() + timeDefault), new HashMap()); - Mockito.when(identityPlugin.updateToken(Mockito.any(Token.class))).thenReturn( + Mockito.when(identityPlugin.createToken(Mockito.any(Token.class))).thenReturn( tokenUpdatedFirstTime); managerController.setIdentityPlugin(identityPlugin); Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); @@ -199,7 +199,7 @@ public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedExc properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", new Date(), new HashMap()); + Token token = new Token("id", USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.DELETED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -216,7 +216,7 @@ public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedExc managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenReturn(new Instance("id")); @@ -243,7 +243,7 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", new Date(), new HashMap()); + Token token = new Token("id", USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.DELETED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -264,7 +264,7 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); @@ -280,7 +280,7 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", new Date(), new HashMap()); + Token token = new Token("id", USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -294,7 +294,7 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); managerController.monitorInstances(); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); @@ -322,7 +322,7 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup properties.put("scheduler_period", Integer.toString(timeDefaultSchedulePeriod)); managerController = new ManagerController(properties); - Token token = new Token("id", new Date(), new HashMap()); + Token token = new Token("id", USER_NAME, new Date(), new HashMap()); Map map = new HashMap(); map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); Request request1 = new Request("id1", token, USER_NAME, null, map); @@ -338,7 +338,7 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), Mockito.anyMap())).thenReturn("ok"); @@ -379,7 +379,7 @@ public void testMonitoringFulfilledRequestAndOnetimeInstance() throws Interrupte properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", new Date(), new HashMap()); + Token token = new Token("id", USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -393,7 +393,7 @@ public void testMonitoringFulfilledRequestAndOnetimeInstance() throws Interrupte managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); managerController.monitorInstances(); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); @@ -470,7 +470,7 @@ public void testGetRequestsByUser() throws InterruptedException { Mockito.any(Map.class))).thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -511,7 +511,7 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio Mockito.any(Map.class))).thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -566,7 +566,7 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -621,7 +621,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Mockito.any(Map.class))).thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -696,7 +696,7 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel @@ -756,7 +756,7 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel @@ -823,7 +823,7 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel @@ -887,7 +887,7 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel @@ -962,7 +962,7 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel @@ -1037,7 +1037,7 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel @@ -1120,7 +1120,7 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); +// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 10009df9..dd75c881 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -38,16 +38,14 @@ public void setup() throws Exception { Mockito.doNothing().when(computePlugin) .removeInstance(OCCITestHelper.ACCESS_TOKEN, INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - OCCITestHelper.USER_MOCK); List requests = new LinkedList(); - Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, + Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_ID); requests.add(request1); - Request request2 = new Request("1", new Token("otherToken", + Request request2 = new Request("1", new Token("otherToken", "otherUser", OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), "otherUser", null, null); request2.setInstanceId(OTHER_INSTANCE_ID); requests.add(request2); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index 7d2636d6..823cec9e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -43,9 +43,9 @@ public void setup() throws Exception { .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( - new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( +// new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index f37370d0..26ec782c 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -54,21 +54,21 @@ public void setup() throws Exception { Mockito.eq(INSTANCE_3_ID_WITHOUT_USER))).thenReturn(instance1); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - OCCITestHelper.USER_MOCK); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( +// OCCITestHelper.USER_MOCK); List requests = new LinkedList(); - Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, + Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_1_ID); requests.add(request1); - Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, + Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request2.setInstanceId(INSTANCE_2_ID); requests.add(request2); - Request request3 = new Request("3", new Token("token", + Request request3 = new Request("3", new Token("token", "user", OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), "user", null, null); request3.setInstanceId(INSTANCE_3_ID_WITHOUT_USER); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 26ba8f34..bb63fa32 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -53,14 +53,14 @@ public void setup() throws Exception { Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( - new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( +// OCCITestHelper.USER_MOCK); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( +// new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); HashMap tokenAttr = new HashMap(); - tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); - Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, +// tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); + Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 97ae3c7d..0cddf6f8 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -56,11 +56,9 @@ public void setUp() { ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - OCCITestHelper.USER_MOCK); HashMap tokenAttr = new HashMap(); - tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); - Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, +// tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); + Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(Mockito.anyString())).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index 6928f4ee..af12e085 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -41,9 +41,9 @@ public void setup() throws Exception { .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); - Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( - new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); +// Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( +// new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java index 5ac6217a..661999d7 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -57,10 +57,10 @@ public void testGetTokenWrongContentType() throws Exception { @SuppressWarnings("unchecked") @Test public void testGetToken() throws Exception { - Token token = new Token(ACCESS_TOKEN_ID, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, + Token token = new Token(ACCESS_TOKEN_ID, "user", OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()); - Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(token); + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(token); this.helper.initializeComponent(computePlugin, identityPlugin); @@ -79,7 +79,7 @@ public void testGetToken() throws Exception { @SuppressWarnings("unchecked") @Test public void testGetTokenUnauthorized() throws Exception { - Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenThrow( + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, "")); this.helper.initializeComponent(computePlugin, identityPlugin); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index e254e2f9..00b1358a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -39,23 +39,23 @@ public void tearDown() throws Exception { @Test public void testValidToken() { Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, - this.identityOpenStack.getUser(PluginHelper.AUTH_TOKEN)); + this.identityOpenStack.getToken(PluginHelper.AUTH_TOKEN).getUser()); } @Test(expected = ResourceException.class) public void testInvalidToken() { - identityOpenStack.getUser("Invalid Token"); + identityOpenStack.getToken("Invalid Token"); } @Test public void testGetNameUserFromToken() { Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, - this.identityOpenStack.getUser(PluginHelper.AUTH_TOKEN)); + this.identityOpenStack.getToken(PluginHelper.AUTH_TOKEN).getUser()); } @Test(expected = ResourceException.class) public void testGetNameUserFromTokenInvalid() { - this.identityOpenStack.getUser("invalid_token"); + this.identityOpenStack.getToken("invalid_token"); } @Test @@ -64,7 +64,7 @@ public void testGetToken() { tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANT_NAME); - Token token = this.identityOpenStack.getToken(tokenAttributes); + Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); Date expirationDate = token.getExpirationDate(); @@ -79,7 +79,7 @@ public void testUpgradeToken() { tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANT_NAME); - Token token = this.identityOpenStack.getToken(tokenAttributes); + Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); Date expirationDate = token.getExpirationDate(); @@ -87,7 +87,7 @@ public void testUpgradeToken() { Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); - Token token2 = this.identityOpenStack.updateToken(token); + Token token2 = this.identityOpenStack.createToken(token); authToken = token2.getAccessId(); tenantID = token2.get(OCCIHeaders.X_TOKEN_TENANT_ID); expirationDate = token2.getExpirationDate(); @@ -102,7 +102,7 @@ public void testGetTokenWrongUsername() { tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, "wrong"); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); - this.identityOpenStack.getToken(tokenAttributes); + this.identityOpenStack.createToken(tokenAttributes); } @Test(expected = OCCIException.class) @@ -111,6 +111,6 @@ public void testGetTokenWrongPassword() { tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, "worng"); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); - this.identityOpenStack.getToken(tokenAttributes); + this.identityOpenStack.createToken(tokenAttributes); } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 83f45f1e..846e9073 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -39,7 +39,7 @@ public void initializeKeystoneComponent() throws Exception { tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - Token token = new Token(AUTH_TOKEN, EXPIRATION_DATE, tokenAttributes); + Token token = new Token(AUTH_TOKEN, USERNAME_FOGBOW, EXPIRATION_DATE, tokenAttributes); // TODO Refactor! We really need all these args to KeytoneApplication? KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java index 549e76ab..a20fe3ab 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -40,7 +40,7 @@ public void tearDown() throws Exception { @Test public void testDeleteRemoteInstance() throws Exception { - Request request = new Request("anyvalue", new Token("anyvalue", + Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -51,7 +51,7 @@ public void testDeleteRemoteInstance() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstaceNotFound() throws Exception { - Request request = new Request("anyvalue", new Token(WRONG_TOKEN, + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -67,7 +67,7 @@ public void testDeleteRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstanceUnauthorized() throws Exception { - Request request = new Request("anyvalue", new Token(WRONG_TOKEN, + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_OTHER_USER); request.setMemberId(MANAGER_COMPONENT_URL); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index add7868c..7f60e37d 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -76,7 +76,7 @@ public void testGetRemoteInstance() throws Exception { .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_DEFAULT))) .thenReturn(instance); - Request request = new Request("anyvalue", new Token("anyvalue", + Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -99,7 +99,7 @@ public void testGetRemoteInstance() throws Exception { @Test public void testGetRemoteInstaceNotFound() throws Exception { - Request request = new Request("anyvalue", new Token( WRONG_TOKEN, + Request request = new Request("anyvalue", new Token( WRONG_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_DEFAULT); request.setMemberId(MANAGER_COMPONENT_URL); @@ -116,7 +116,7 @@ public void testGetRemoteInstaceNotFound() throws Exception { @Test(expected=OCCIException.class) public void testGetRemoteInstanceUnauthorized() throws Exception { - Request request = new Request("anyvalue", new Token( WRONG_TOKEN, + Request request = new Request("anyvalue", new Token( WRONG_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); request.setInstanceId(INSTANCE_OTHER_USER); request.setMemberId(MANAGER_COMPONENT_URL); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index 4698fb3d..0e8f236b 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -63,7 +63,7 @@ private Request createRequest() { Map attributes = new HashMap(); attributes.put("key1", "value1"); attributes.put("key2", "value2"); - Request request = new Request("anyvalue", new Token("anyvalue", + Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, categories, attributes); request.setInstanceId(INSTANCE_DEFAULT); return request; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 3724a7f3..9c1e5cf3 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -46,8 +46,6 @@ public class ManagerTestHelper { private static final String CLIENT_ADRESS = "client@test.com"; private static final String CLIENT_PASS = "password"; private static final String SMACK_ENDING = "/Smack"; - // private static final Token TOKEN = new Token(new HashMap()); public static final String MANAGER_COMPONENT_URL = "manager.test.com"; public static final String MANAGER_COMPONENT_PASS = "password"; @@ -68,7 +66,7 @@ public class ManagerTestHelper { public ManagerTestHelper() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); - this.tokenDefault = new Token("token", new Date(System.currentTimeMillis() + this.tokenDefault = new Token("token", "user", new Date(System.currentTimeMillis() + OCCITestHelper.LONG_TIME), tokenAttributes); } @@ -123,6 +121,7 @@ public XMPPClient createXMPPClient() throws XMPPException { try { register.createAccount(CLIENT_ADRESS, CLIENT_PASS); } catch (XMPPException e) { + e.printStackTrace(); } xmppClient.login(); @@ -182,7 +181,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); - Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(tokenDefault); + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(tokenDefault); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -215,7 +214,7 @@ public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Excepti Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); - Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn(tokenDefault); + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(tokenDefault); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); From 338e9c80a6aa6419cf66c4102060f8e985e81d9a Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Tue, 20 May 2014 09:02:28 -0300 Subject: [PATCH 139/185] Adding test to ManagerController's submitRequestForRemoteMember, renaming MemberValidator and adding a new DefaultMembervalidator --- .../manager/core/ManagerController.java | 12 +- ...r.java => RestrictCAsMemberValidator.java} | 2 +- .../TestDefaultFederationMemberValidator.java | 4 +- .../manager/core/TestManagerController.java | 569 ++++++++++++------ 4 files changed, 382 insertions(+), 205 deletions(-) rename src/main/java/org/fogbowcloud/manager/core/{DefaultFederationMemberValidator.java => RestrictCAsMemberValidator.java} (95%) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 8ccff704..4b614061 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -40,7 +40,8 @@ public class ManagerController { .getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes - private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 minutes + private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 + // minutes private boolean scheduled = false; private boolean tokenUpdatingOn = false; @@ -58,7 +59,7 @@ public class ManagerController { private IdentityPlugin identityPlugin; private Properties properties; private PacketSender packetSender; - private FederationMemberValidator validator = new DefaultFederationMemberValidator(); + private FederationMemberValidator validator = new RestrictCAsMemberValidator(); private DateUtils dateUtils = new DateUtils(); private SSHTunnel sshTunnel = new DefaultSSHTunnel(); @@ -271,7 +272,8 @@ public FederationMember getFederationMember(String memberId) { public String submitRequestForRemoteMember(String memberId, List categories, Map xOCCIAtt) { - if (!validator.canDonateTo(getFederationMember(memberId))) { + FederationMember member = getFederationMember(memberId); + if (!validator.canDonateTo(member)) { return null; } LOGGER.info("Submiting request with categories: " + categories @@ -590,4 +592,8 @@ public void setDateUtils(DateUtils dateUtils) { public FederationMemberValidator getValidator() { return validator; } + + public void setValidator(FederationMemberValidator validator) { + this.validator = validator; + } } diff --git a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java similarity index 95% rename from src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java rename to src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java index 65586064..45db8068 100644 --- a/src/main/java/org/fogbowcloud/manager/core/DefaultFederationMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java @@ -6,7 +6,7 @@ import org.fogbowcloud.manager.core.model.FederationMember; -public class DefaultFederationMemberValidator implements +public class RestrictCAsMemberValidator implements FederationMemberValidator { List validCAs = new LinkedList(); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java index 8a838cb5..79fc6e7f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java @@ -25,7 +25,7 @@ public class TestDefaultFederationMemberValidator { ManagerTestHelper helper; - DefaultFederationMemberValidator validator; + RestrictCAsMemberValidator validator; X509Certificate mockCA; X509Certificate mockCertificate; FederationMember member; @@ -37,7 +37,7 @@ public void setUp() throws NoSuchAlgorithmException { KeyPair keys = keyGenerator.generateKeyPair(); publicKey = keys.getPublic(); helper = new ManagerTestHelper(); - validator = new DefaultFederationMemberValidator(); + validator = new RestrictCAsMemberValidator(); X509Certificate mockCA = Mockito.mock(X509Certificate.class); Mockito.doReturn(publicKey).when(mockCA).getPublicKey(); List list = new LinkedList(); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index b7f0768f..858d1b09 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -4,18 +4,23 @@ import java.security.cert.CertificateException; import java.text.SimpleDateFormat; import java.util.ArrayList; +import java.util.Collection; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.ListIterator; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.TimeZone; import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; @@ -56,14 +61,16 @@ public class TestManagerController { private Token userToken; private ManagerController managerController; private ManagerTestHelper managerTestHelper; - + private HashMap tokenAttr ; + @Before public void setUp() throws Exception { managerController = new ManagerController(new Properties()); managerTestHelper = new ManagerTestHelper(); - HashMap tokenAttr = new HashMap(); + tokenAttr = new HashMap(); tokenAttr.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - userToken = new Token(ACCESS_TOKEN_ID, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); + userToken = new Token(ACCESS_TOKEN_ID, + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); } @Test @@ -86,17 +93,20 @@ public void testGetFederationMember() throws InterruptedException { attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token = new Token(ACCESS_TOKEN_ID, new Date(expirationTime), attributesTokenReturn); + Token token = new Token(ACCESS_TOKEN_ID, new Date(expirationTime), + attributesTokenReturn); Map attributesTokenReturn2 = new HashMap(); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + attributesTokenReturn2 + .put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token2 = new Token(ACCESS_TOKEN_ID_2, new Date(expirationTime + LONG_TIME), - attributesTokenReturn2); + Token token2 = new Token(ACCESS_TOKEN_ID_2, new Date(expirationTime + + LONG_TIME), attributesTokenReturn2); - Mockito.when(openStackidentityPlugin.getToken(attributesToken)).thenReturn(token, token2); + Mockito.when(openStackidentityPlugin.getToken(attributesToken)) + .thenReturn(token, token2); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token @@ -109,7 +119,8 @@ public void testGetFederationMember() throws InterruptedException { Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(expirationTime + GRACE_TIME); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn( + expirationTime + GRACE_TIME); token.setDateUtils(dateUtils); // Get new token @@ -130,15 +141,20 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { DateUtils dateUtils = Mockito.mock(DateUtils.class); RequestRepository requestRepository = new RequestRepository(); - Token token = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token = new Token(firstTokenId, + new Date(now + (4 * timeDefault)), new HashMap()); - Token token2 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token2 = new Token(firstTokenId, + new Date(now + (4 * timeDefault)), new HashMap()); - Token token3 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token3 = new Token(firstTokenId, + new Date(now + (4 * timeDefault)), new HashMap()); - Token token4 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token4 = new Token(firstTokenId, + new Date(now + (4 * timeDefault)), new HashMap()); - Token token5 = new Token(firstTokenId, new Date(now + (4 * timeDefault)), + Token token5 = new Token(firstTokenId, + new Date(now + (4 * timeDefault)), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.OPEN); @@ -158,43 +174,53 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Token tokenUpdatedFirstTime = new Token(secontTokenId, new Date(System.currentTimeMillis() - + timeDefault), new HashMap()); - Mockito.when(identityPlugin.updateToken(Mockito.any(Token.class))).thenReturn( - tokenUpdatedFirstTime); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Token tokenUpdatedFirstTime = new Token(secontTokenId, new Date( + System.currentTimeMillis() + timeDefault), + new HashMap()); + Mockito.when(identityPlugin.updateToken(Mockito.any(Token.class))) + .thenReturn(tokenUpdatedFirstTime); managerController.setIdentityPlugin(identityPlugin); Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); managerController.setDateUtils(dateUtils); managerController.checkAndUpdateRequestToken(timeDefault); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().equals(RequestState.OPEN)) { - Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + Assert.assertEquals(firstTokenId, request.getToken() + .getAccessId()); } else if (request.getState().equals(RequestState.CLOSED) || request.getState().equals(RequestState.FAILED)) { - Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + Assert.assertEquals(firstTokenId, request.getToken() + .getAccessId()); } } - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now + (3 * timeDefault)); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn( + now + (3 * timeDefault)); managerController.setDateUtils(dateUtils); managerController.checkAndUpdateRequestToken(timeDefault); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().equals(RequestState.OPEN)) { - Assert.assertEquals(secontTokenId, request.getToken().getAccessId()); + Assert.assertEquals(secontTokenId, request.getToken() + .getAccessId()); } else if (request.getState().equals(RequestState.CLOSED) || request.getState().equals(RequestState.FAILED)) { - Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + Assert.assertEquals(firstTokenId, request.getToken() + .getAccessId()); } } } @Test - public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedException { + public void testMonitoringDeletedRequestAndFoundInstance() + throws InterruptedException { Properties properties = new Properties(); properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); @@ -216,9 +242,11 @@ public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedExc managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance("id")); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), + Mockito.anyString())).thenReturn(new Instance("id")); Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); @@ -230,7 +258,8 @@ private List getRequestsDeleted(RequestRepository requestRepository) { List requests = new ArrayList(); for (Request request : requestRepository.get(RequestState.DELETED)) { try { - requests.add(managerController.getRequest(ACCESS_TOKEN_ID, request.getId())); + requests.add(managerController.getRequest(ACCESS_TOKEN_ID, + request.getId())); } catch (Exception e) { } } @@ -238,7 +267,8 @@ private List getRequestsDeleted(RequestRepository requestRepository) { } @Test - public void testMonitoringDeletedRequestAndNotFoundInstance() throws InterruptedException { + public void testMonitoringDeletedRequestAndNotFoundInstance() + throws InterruptedException { Properties properties = new Properties(); properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); @@ -264,9 +294,12 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), + Mockito.anyString())).thenThrow( + new OCCIException(ErrorType.NOT_FOUND, "")); Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); @@ -275,7 +308,8 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted } @Test - public void testMonitoringFulfilledRequestAndNotFoundInstance() throws InterruptedException { + public void testMonitoringFulfilledRequestAndNotFoundInstance() + throws InterruptedException { Properties properties = new Properties(); properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); @@ -294,19 +328,24 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); managerController.monitorInstances(); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), + Mockito.anyString())).thenThrow( + new OCCIException(ErrorType.NOT_FOUND, "")); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); } @@ -314,17 +353,21 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt @SuppressWarnings("unchecked") @Test - public void testMonitoringFulfilledRequestAndPesistentInstance() throws InterruptedException { + public void testMonitoringFulfilledRequestAndPesistentInstance() + throws InterruptedException { final int timeDefault = 100; final int timeDefaultSchedulePeriod = 10; Properties properties = new Properties(); - properties.put("instance_monitoring_period", Integer.toString(timeDefault)); - properties.put("scheduler_period", Integer.toString(timeDefaultSchedulePeriod)); + properties.put("instance_monitoring_period", + Integer.toString(timeDefault)); + properties.put("scheduler_period", + Integer.toString(timeDefaultSchedulePeriod)); managerController = new ManagerController(properties); Token token = new Token("id", new Date(), new HashMap()); Map map = new HashMap(); - map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); + map.put(RequestAttribute.TYPE.getValue(), + RequestType.PERSISTENT.getValue()); Request request1 = new Request("id1", token, USER_NAME, null, map); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", token, USER_NAME, null, map); @@ -338,25 +381,30 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), - Mockito.anyMap())).thenReturn("ok"); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.anyList(), Mockito.anyMap())).thenReturn("ok"); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), + Mockito.anyString())).thenThrow( + new OCCIException(ErrorType.NOT_FOUND, "")); managerController.monitorInstances(); boolean wasOpen = false; for (int i = 0; i < 50; i++) { Thread.sleep(1); for (Request request : requestsFromUser) { - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); if (request.getState().equals(RequestState.OPEN)) { wasOpen = true; } @@ -367,14 +415,16 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup Thread.sleep(timeDefaultSchedulePeriod * 100); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } } @Test - public void testMonitoringFulfilledRequestAndOnetimeInstance() throws InterruptedException { + public void testMonitoringFulfilledRequestAndOnetimeInstance() + throws InterruptedException { Properties properties = new Properties(); properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); @@ -393,19 +443,23 @@ public void testMonitoringFulfilledRequestAndOnetimeInstance() throws Interrupte managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); managerController.monitorInstances(); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance("id")); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), + Mockito.anyString())).thenReturn(new Instance("id")); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } @@ -424,7 +478,8 @@ public void testGet0ItemsFromIQ() { @Test public void testGet1ItemFromIQ() throws CertificateException, IOException { - FederationMember managerItem = new FederationMember(managerTestHelper.getResources()); + FederationMember managerItem = new FederationMember( + managerTestHelper.getResources()); List items = new LinkedList(); items.add(managerItem); managerController.updateMembers(items); @@ -436,7 +491,8 @@ public void testGet1ItemFromIQ() throws CertificateException, IOException { } @Test - public void testGetManyItemsFromIQ() throws CertificateException, IOException { + public void testGetManyItemsFromIQ() throws CertificateException, + IOException { ArrayList items = new ArrayList(); for (int i = 0; i < 10; i++) { items.add(new FederationMember(managerTestHelper.getResources())); @@ -446,7 +502,8 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { List members = managerController.getMembers(); Assert.assertEquals(10, members.size()); for (int i = 0; i < 10; i++) { - Assert.assertEquals("abc", members.get(0).getResourcesInfo().getId()); + Assert.assertEquals("abc", members.get(0).getResourcesInfo() + .getId()); } Assert.assertEquals(10, managerController.getMembers().size()); } @@ -466,12 +523,15 @@ public void testGetRequestsByUser() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -479,11 +539,13 @@ public void testGetRequestsByUser() throws InterruptedException { managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD * 2); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(USER_NAME, requests.get(0).getUser()); @@ -494,7 +556,8 @@ public void testGetRequestsByUser() throws InterruptedException { @SuppressWarnings("unchecked") @Test - public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { + public void testOneTimeRequestSetFulfilledAndClosed() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); @@ -507,12 +570,15 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -520,11 +586,13 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); @@ -544,7 +612,8 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio @SuppressWarnings("unchecked") @Test - public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { + public void testPersistentRequestSetFulfilledAndOpen() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); @@ -558,16 +627,18 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))) + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) .thenReturn(INSTANCE_ID) .thenThrow( new OCCIException(ErrorType.QUOTA_EXCEEDED, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -575,16 +646,18 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); @@ -594,8 +667,8 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -603,7 +676,8 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti @SuppressWarnings("unchecked") @Test - public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { + public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", Long.toString(SCHEDULER_PERIOD)); managerController = new ManagerController(properties); @@ -617,12 +691,15 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -630,16 +707,18 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); @@ -649,8 +728,8 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -662,20 +741,22 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } @SuppressWarnings("unchecked") @Test - public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { + public void testPersistentRequestSetOpenAndClosed() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); - long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + + SCHEDULER_PERIOD; // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -689,15 +770,18 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -707,13 +791,15 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -723,8 +809,8 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -732,13 +818,15 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException @SuppressWarnings("unchecked") @Test - public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { + public void testPersistentRequestSetFulfilledAndClosed() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); - long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD + GRACE_TIME; + long expirationRequestTime = System.currentTimeMillis() + + SCHEDULER_PERIOD + GRACE_TIME; // default instance count value is 1 Map xOCCIAtt = new HashMap(); @@ -751,13 +839,16 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -766,16 +857,18 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(SCHEDULER_PERIOD); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); @@ -789,8 +882,8 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -798,33 +891,39 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep @SuppressWarnings("unchecked") @Test - public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { + public void testOneTimeRequestSetOpenAndClosed() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); - long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + + SCHEDULER_PERIOD; // default instance count value is 1 Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestConstants.DEFAULT_TYPE); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -834,13 +933,15 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -850,8 +951,8 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -860,7 +961,8 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { @SuppressWarnings("unchecked") @Test - public void testOneTimeRequestValidFromInFuture() throws InterruptedException { + public void testOneTimeRequestValidFromInFuture() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); @@ -875,20 +977,24 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.ONE_TIME.getValue())); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -898,13 +1004,15 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -915,8 +1023,8 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -927,8 +1035,8 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -936,7 +1044,8 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { @SuppressWarnings("unchecked") @Test - public void testPersistentRequestValidFromInFuture() throws InterruptedException { + public void testPersistentRequestValidFromInFuture() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); @@ -949,21 +1058,26 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestType.PERSISTENT.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -973,13 +1087,15 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -990,8 +1106,8 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1002,8 +1118,8 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1011,7 +1127,8 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException @SuppressWarnings("unchecked") @Test - public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { + public void testOneTimeRequestValidityPeriodInFuture() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); @@ -1024,21 +1141,26 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestType.ONE_TIME.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -1048,9 +1170,11 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); @@ -1058,8 +1182,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1070,8 +1194,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1085,8 +1209,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.ONE_TIME.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1094,7 +1218,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti @SuppressWarnings("unchecked") @Test - public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { + public void testPersistentRequestValidityPeriodInFuture() + throws InterruptedException { Properties properties = new Properties(); properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); @@ -1107,21 +1232,26 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Map xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), + RequestType.PERSISTENT.getValue()); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), getDateISO8601Format(expirationRequestTime)); // mocking compute ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(INSTANCE_ID); // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn( + USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn( + userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -1131,9 +1261,11 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce managerController.setSSHTunnel(sshTunnel); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(ACCESS_TOKEN_ID); Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); @@ -1141,8 +1273,8 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce // request is not in validity period yet Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.OPEN, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1153,8 +1285,8 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1170,8 +1302,8 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(RequestType.PERSISTENT.getValue(), - requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); + Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0) + .getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); @@ -1184,4 +1316,43 @@ public static String getDateISO8601Format(long dateMili) { String expirationDate = dateFormatISO8601.format(new Date(dateMili)); return expirationDate; } + + @Test + public void testSubmitRequestForRemoteMemberValidation() { + ResourcesInfo resources = Mockito.mock(ResourcesInfo.class); + Mockito.doReturn("abc").when(resources).getId(); + + FederationMember member = Mockito.mock(FederationMember.class); + Mockito.doReturn(resources).when(member).getResourcesInfo(); + List list = new LinkedList(); + list.add(member); + managerController.setMembers(list); + + RestrictCAsMemberValidator validatorMock = Mockito + .mock(RestrictCAsMemberValidator.class); + Mockito.doReturn(true).when(validatorMock).canDonateTo(member); + managerController.setValidator(validatorMock); + + Token token = Mockito.mock(Token.class); + Mockito.doReturn(null).when(token).getAccessId(); + + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getToken(Mockito.anyMap())).thenReturn( + token); + managerController.setIdentityPlugin(identityPlugin); + + ComputePlugin plugin = Mockito.mock(OpenStackComputePlugin.class); + Mockito.doReturn("answer") + .when(plugin) + .requestInstance(null, null, null); + + managerController.setComputePlugin(plugin); + Assert.assertEquals("answer", managerController + .submitRequestForRemoteMember("abc", null, null)); + + Mockito.doReturn(false).when(validatorMock).canDonateTo(member); + managerController.setValidator(validatorMock); + Assert.assertEquals(null, managerController + .submitRequestForRemoteMember("abc", null, null)); + } } From 5e8f4881debdf323ade45099d18aa88877dfe727 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Tue, 20 May 2014 09:03:42 -0300 Subject: [PATCH 140/185] Adding new DefaultMemberValidator. --- .../manager/core/DefaultMemberValidator.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java diff --git a/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java new file mode 100644 index 00000000..4358a66e --- /dev/null +++ b/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java @@ -0,0 +1,17 @@ +package org.fogbowcloud.manager.core; + +import org.fogbowcloud.manager.core.model.FederationMember; + +public class DefaultMemberValidator implements FederationMemberValidator { + + @Override + public boolean canDonateTo(FederationMember member) { + return true; + } + + @Override + public boolean canReceiveFrom(FederationMember member) { + return true; + } + +} From 14b89942fdd3a8c33ce7e667092c4b34e84595da Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 20 May 2014 12:32:44 -0300 Subject: [PATCH 141/185] Fixing TestIdentityOpenStack. --- .../plugins/openstack/OpenStackIdentityPlugin.java | 1 + .../manager/occi/util/KeystoneApplication.java | 11 +++++++---- .../fogbowcloud/manager/occi/util/PluginHelper.java | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 8b149f72..06b4dd21 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -169,6 +169,7 @@ private Token getTokenFromJson(String responseStr) { return new Token(token, user, getDate(expirationDateToken), attributes); } catch (Exception e) { + e.printStackTrace(); LOGGER.error("Exception while getting token from json.", e); return null; } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 12687762..50f0d5cd 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -152,11 +152,14 @@ private String mountJSONResponseAuthenticateToken(Token token) { rootIdToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tokenAccessId); rootIdToken.put(OpenStackIdentityPlugin.EXPIRES_KEYSTONE, expirationDate); rootIdToken.put(OpenStackIdentityPlugin.TENANT_KEYSTONE, rootTenant); - JSONObject rootToken = new JSONObject(); - rootToken.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdToken); JSONObject rootAccess = new JSONObject(); - rootAccess.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, rootToken); - return rootAccess.toString(); + rootAccess.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdToken); + JSONObject rootUserName = new JSONObject(); + rootUserName.put(OpenStackIdentityPlugin.NAME_KEYSTONE, token.getUser()); + rootAccess.put(OpenStackIdentityPlugin.USER_KEYSTONE, rootUserName); + JSONObject rootMain = new JSONObject(); + rootMain.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, rootAccess); + return rootMain.toString(); } catch (JSONException e) { e.printStackTrace(); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 846e9073..677bce9b 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -37,7 +37,7 @@ public void initializeKeystoneComponent() throws Exception { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); +// tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); Token token = new Token(AUTH_TOKEN, USERNAME_FOGBOW, EXPIRATION_DATE, tokenAttributes); From f991bb7652c47c77a3b39daee03eb343ae63ff75 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 20 May 2014 14:54:34 -0300 Subject: [PATCH 142/185] Fixing TestGetRequest. --- .../manager/occi/TestGetRequest.java | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index bb63fa32..720a4648 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.net.URISyntaxException; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -39,8 +40,9 @@ public class TestGetRequest { private OCCITestHelper requestHelper; - private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + OCCITestHelper.ENDPOINT_PORT - + ComputeApplication.TARGET + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + private String instanceLocation = HeaderUtils.X_OCCI_LOCATION + "http://localhost:" + + OCCITestHelper.ENDPOINT_PORT + ComputeApplication.TARGET + + "/b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; @SuppressWarnings("unchecked") @Before @@ -53,16 +55,16 @@ public void setup() throws Exception { Mockito.any(Map.class))).thenReturn(instanceLocation); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( -// OCCITestHelper.USER_MOCK); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( -// new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); - + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + new Token("id", OCCITestHelper.USER_MOCK, new Date(), + new HashMap())); + Mockito.when(identityPlugin.getToken(OCCITestHelper.INVALID_TOKEN)).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); + HashMap tokenAttr = new HashMap(); -// tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); - + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn(userToken); requestHelper.initializeComponent(computePlugin, identityPlugin); From edf896c6239d9953862d9d4634c6cbae6ead5454 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 20 May 2014 15:51:22 -0300 Subject: [PATCH 143/185] Fixing TestManagerController tests --- .../manager/core/ManagerController.java | 2 +- .../manager/core/TestManagerController.java | 163 ++++++++---------- 2 files changed, 70 insertions(+), 95 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index d15f0751..4ce49720 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -494,7 +494,7 @@ public void run() { }, 0, schedulerPeriod); } - private void checkAndSubmitOpenRequests() { + protected void checkAndSubmitOpenRequests() { boolean allFulfilled = true; LOGGER.debug("Checking and submiting requests."); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 280f024a..2e0c726e 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -80,28 +80,29 @@ public void testGetFederationMember() throws InterruptedException { managerController = new ManagerController(properties); OpenStackIdentityPlugin openStackidentityPlugin = Mockito .mock(OpenStackIdentityPlugin.class); - Map attributesToken = new HashMap(); - attributesToken.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - attributesToken.put(OCCIHeaders.X_TOKEN_PASS, USER_PASS); - attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + Map tokenCredentials = new HashMap(); + tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, USER_PASS); + tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - long expirationTime = System.currentTimeMillis() + 500; + long tokenExpirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); // attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(expirationTime), attributesTokenReturn); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(tokenExpirationTime), attributesTokenReturn); Map attributesTokenReturn2 = new HashMap(); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); // attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token2 = new Token(ACCESS_TOKEN_ID_2, USER_NAME, new Date(expirationTime + LONG_TIME), + Token token2 = new Token(ACCESS_TOKEN_ID_2, USER_NAME, new Date(tokenExpirationTime + LONG_TIME), attributesTokenReturn2); - Mockito.when(openStackidentityPlugin.createToken(attributesToken)).thenReturn(token, token2); + Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, token2); + Mockito.when(openStackidentityPlugin.isValid(ACCESS_TOKEN_ID)).thenReturn(true, false); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token @@ -114,7 +115,7 @@ public void testGetFederationMember() throws InterruptedException { Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(expirationTime + GRACE_TIME); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(tokenExpirationTime + GRACE_TIME); token.setDateUtils(dateUtils); // Get new token @@ -124,76 +125,56 @@ public void testGetFederationMember() throws InterruptedException { @Test public void testcheckAndUpdateRequestToken() throws InterruptedException { - final String firstTokenId = "firstTokenId"; - final String secontTokenId = "secondTokenId"; - final int timeDefault = 100; + final int tokenUpdaterInterval = 100; final long now = System.currentTimeMillis(); - + long tokenExpirationTime = now + (4 * tokenUpdaterInterval); + Properties properties = new Properties(); - properties.put("token_update_period", Integer.toString(timeDefault)); + properties.put("token_update_period", Integer.toString(tokenUpdaterInterval)); managerController = new ManagerController(properties); DateUtils dateUtils = Mockito.mock(DateUtils.class); RequestRepository requestRepository = new RequestRepository(); - Token token = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), - new HashMap()); - Token token2 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), - new HashMap()); - Token token3 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), - new HashMap()); - Token token4 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(tokenExpirationTime), new HashMap()); - Token token5 = new Token(firstTokenId, USER_NAME, new Date(now + (4 * timeDefault)), - new HashMap()); - Request request1 = new Request("id1", token, USER_NAME, null, null); - request1.setState(RequestState.OPEN); - Request request2 = new Request("id2", token2, USER_NAME, null, null); - request2.setState(RequestState.OPEN); - Request request3 = new Request("id3", token3, USER_NAME, null, null); - request3.setState(RequestState.OPEN); - Request request4 = new Request("id4", token4, USER_NAME, null, null); - request4.setState(RequestState.CLOSED); - Request request5 = new Request("id5", token5, USER_NAME, null, null); - request5.setState(RequestState.FAILED); - requestRepository.addRequest(USER_NAME, request1); - requestRepository.addRequest(USER_NAME, request2); - requestRepository.addRequest(USER_NAME, request3); - requestRepository.addRequest(USER_NAME, request4); - requestRepository.addRequest(USER_NAME, request5); + + for (int i = 0; i < 5; i++) { + requestRepository.addRequest(USER_NAME, new Request("id" + i, token, USER_NAME, null, null)); + } managerController.setRequests(requestRepository); + //mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Token tokenUpdatedFirstTime = new Token(secontTokenId, USER_NAME, new Date(System.currentTimeMillis() - + timeDefault), new HashMap()); - Mockito.when(identityPlugin.createToken(Mockito.any(Token.class))).thenReturn( + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); + Token tokenUpdatedFirstTime = new Token(ACCESS_TOKEN_ID_2, USER_NAME, new Date(tokenExpirationTime + + tokenUpdaterInterval), new HashMap()); + Mockito.when(identityPlugin.createToken(token)).thenReturn( tokenUpdatedFirstTime); managerController.setIdentityPlugin(identityPlugin); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); managerController.setDateUtils(dateUtils); - managerController.checkAndUpdateRequestToken(timeDefault); + managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { - if (request.getState().equals(RequestState.OPEN)) { - Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); - } else if (request.getState().equals(RequestState.CLOSED) - || request.getState().equals(RequestState.FAILED)) { - Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + if (request.getState().in(RequestState.OPEN)) { + Assert.assertEquals(ACCESS_TOKEN_ID, request.getToken().getAccessId()); + } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { + Assert.assertEquals(ACCESS_TOKEN_ID, request.getToken().getAccessId()); } } - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now + (3 * timeDefault)); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(tokenExpirationTime - tokenUpdaterInterval); managerController.setDateUtils(dateUtils); - managerController.checkAndUpdateRequestToken(timeDefault); + managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { - if (request.getState().equals(RequestState.OPEN)) { - Assert.assertEquals(secontTokenId, request.getToken().getAccessId()); - } else if (request.getState().equals(RequestState.CLOSED) - || request.getState().equals(RequestState.FAILED)) { - Assert.assertEquals(firstTokenId, request.getToken().getAccessId()); + if (request.getState().in(RequestState.OPEN)) { + Assert.assertEquals(ACCESS_TOKEN_ID_2, request.getToken().getAccessId()); + } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { + Assert.assertEquals(ACCESS_TOKEN_ID, request.getToken().getAccessId()); } } } @@ -204,7 +185,7 @@ public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedExc properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", USER_NAME, new Date(), new HashMap()); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.DELETED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -221,9 +202,9 @@ public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedExc managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance("id")); + .thenReturn(new Instance(INSTANCE_ID)); Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); @@ -248,7 +229,7 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", USER_NAME, new Date(), new HashMap()); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.DELETED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -269,9 +250,9 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); @@ -285,7 +266,7 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", USER_NAME, new Date(), new HashMap()); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -299,7 +280,7 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); managerController.monitorInstances(); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); @@ -308,7 +289,7 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt } Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); managerController.monitorInstances(); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); @@ -320,14 +301,13 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt @SuppressWarnings("unchecked") @Test public void testMonitoringFulfilledRequestAndPesistentInstance() throws InterruptedException { - final int timeDefault = 100; - final int timeDefaultSchedulePeriod = 10; + final int timeDefault = 5 * 60 * 1000; //Big time to not interfere this test Properties properties = new Properties(); properties.put("instance_monitoring_period", Integer.toString(timeDefault)); - properties.put("scheduler_period", Integer.toString(timeDefaultSchedulePeriod)); + properties.put("scheduler_period", 100 * SCHEDULER_PERIOD); managerController = new ManagerController(properties); - Token token = new Token("id", USER_NAME, new Date(), new HashMap()); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()); Map map = new HashMap(); map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); Request request1 = new Request("id1", token, USER_NAME, null, map); @@ -340,40 +320,35 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); + Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), + Mockito.anyMap())).thenReturn(INSTANCE_ID); + + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + managerController.setIdentityPlugin(identityPlugin); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), - Mockito.anyMap())).thenReturn("ok"); - + List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, "")); - + managerController.monitorInstances(); - boolean wasOpen = false; - for (int i = 0; i < 50; i++) { - Thread.sleep(1); - for (Request request : requestsFromUser) { - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); - if (request.getState().equals(RequestState.OPEN)) { - wasOpen = true; - } - } + + for (Request request : requestsFromUser) { + requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + Assert.assertTrue(request.getState().in(RequestState.OPEN)); } - - Assert.assertTrue(wasOpen); - - Thread.sleep(timeDefaultSchedulePeriod * 100); + + managerController.checkAndSubmitOpenRequests(); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { + System.out.println("------> state: " + request.getState()); Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } } @@ -384,7 +359,7 @@ public void testMonitoringFulfilledRequestAndOnetimeInstance() throws Interrupte properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token("id", USER_NAME, new Date(), new HashMap()); + Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); Request request1 = new Request("id1", token, USER_NAME, null, null); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", token, USER_NAME, null, null); @@ -398,7 +373,7 @@ public void testMonitoringFulfilledRequestAndOnetimeInstance() throws Interrupte managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); + Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); managerController.monitorInstances(); List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); @@ -407,7 +382,7 @@ public void testMonitoringFulfilledRequestAndOnetimeInstance() throws Interrupte } Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance("id")); + .thenReturn(new Instance(INSTANCE_ID)); managerController.monitorInstances(); requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); From 322f8757b3fdf2c348114a0a69e2d6942ce689ec Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 20 May 2014 15:59:53 -0300 Subject: [PATCH 144/185] Fixing Tests. --- .../manager/core/ManagerController.java | 6 +++++- .../manager/core/TestManagerController.java | 1 - .../manager/occi/TestDeleteCompute.java | 15 ++++++++++----- .../manager/occi/TestDeleteRequest.java | 12 ++++++++---- .../fogbowcloud/manager/occi/TestGetCompute.java | 6 ++++-- .../fogbowcloud/manager/occi/TestPostCompute.java | 7 ------- .../fogbowcloud/manager/occi/TestPostRequest.java | 11 ++++++++--- 7 files changed, 35 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 4ce49720..03ff1eba 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -101,7 +101,11 @@ public ResourcesInfo getResourcesInfo() { } public String getUser(String accessId) { - return identityPlugin.getToken(accessId).getUser(); + Token token = identityPlugin.getToken(accessId); + if (token == null) { + return null; + } + return token.getUser(); } public List getRequestsFromUser(String authToken) { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 2e0c726e..3540027b 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -348,7 +348,6 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { - System.out.println("------> state: " + request.getState()); Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index dd75c881..13faa025 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -1,5 +1,6 @@ package org.fogbowcloud.manager.occi; +import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -38,15 +39,19 @@ public void setup() throws Exception { Mockito.doNothing().when(computePlugin) .removeInstance(OCCITestHelper.ACCESS_TOKEN, INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)) + .thenReturn(new Token("1", OCCITestHelper.USER_MOCK, new Date(), + new HashMap())); List requests = new LinkedList(); - Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), - OCCITestHelper.USER_MOCK, null, null); + Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, + new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_ID); requests.add(request1); - Request request2 = new Request("1", new Token("otherToken", "otherUser", - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), "otherUser", null, null); + Request request2 = new Request("2", new Token("otherToken", "otherUser", + OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), + "otherUser", null, null); request2.setInstanceId(OTHER_INSTANCE_ID); requests.add(request2); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index 823cec9e..9d6d0e0e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -2,6 +2,8 @@ import java.io.IOException; import java.net.URISyntaxException; +import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -20,6 +22,7 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.util.OCCITestHelper; @@ -43,10 +46,11 @@ public void setup() throws Exception { .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( -// new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); - + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + new Token("id", OCCITestHelper.USER_MOCK, new Date(), + new HashMap())); + Mockito.when(identityPlugin.getToken(OCCITestHelper.INVALID_TOKEN)).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 26ec782c..6d1211d4 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -1,6 +1,7 @@ package org.fogbowcloud.manager.occi; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -54,8 +55,9 @@ public void setup() throws Exception { Mockito.eq(INSTANCE_3_ID_WITHOUT_USER))).thenReturn(instance1); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn( -// OCCITestHelper.USER_MOCK); + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + new Token("id", OCCITestHelper.USER_MOCK, new Date(), + new HashMap())); List requests = new LinkedList(); Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java index fa86f552..3363872d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java @@ -6,11 +6,4 @@ import org.junit.Test; public class TestPostCompute { - - @Ignore - @Test - public void test() { - fail("Not yet implemented"); - } - } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java index af12e085..78b1d368 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestPostRequest.java @@ -2,6 +2,8 @@ import java.io.IOException; import java.net.URISyntaxException; +import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -18,6 +20,7 @@ import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; +import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.util.OCCITestHelper; @@ -41,9 +44,11 @@ public void setup() throws Exception { .thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.ACCESS_TOKEN)).thenReturn(OCCITestHelper.USER_MOCK); -// Mockito.when(identityPlugin.getUser(OCCITestHelper.INVALID_TOKEN)).thenThrow( -// new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn( + new Token("id", OCCITestHelper.USER_MOCK, new Date(), + new HashMap())); + Mockito.when(identityPlugin.getToken(OCCITestHelper.INVALID_TOKEN)).thenThrow( + new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); } From c4886641b104767f585fcc78a72e1617bb2b5348 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 21 May 2014 09:05:16 -0300 Subject: [PATCH 145/185] Fixing Test --- .../fogbowcloud/manager/xmpp/util/ManagerTestHelper.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 9c1e5cf3..2ad066bc 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -16,6 +16,8 @@ import org.dom4j.Attribute; import org.dom4j.Element; import org.fogbowcloud.manager.core.CertificateHandlerHelper; +import org.fogbowcloud.manager.core.DefaultMemberValidator; +import org.fogbowcloud.manager.core.FederationMemberValidator; import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; @@ -33,6 +35,7 @@ import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; +import org.mockito.Mock; import org.mockito.Mockito; import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; @@ -174,6 +177,8 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws ManagerController managerFacade = new ManagerController(properties); managerFacade.setComputePlugin(computePlugin); managerFacade.setIdentityPlugin(identityPlugin); + FederationMemberValidator validator = new DefaultMemberValidator(); + managerFacade.setValidator(validator); managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); @@ -204,10 +209,12 @@ public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Excepti properties.put("federation_user_password", "fogbow"); properties.put("xmpp_jid", "manager.test.com"); + FederationMemberValidator validator = new DefaultMemberValidator(); ManagerController managerFacade = new ManagerController(properties); managerFacade.setComputePlugin(computePlugin); managerFacade.setIdentityPlugin(identityPlugin); - + managerFacade.setValidator(validator); + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); From 7639fa6094452a8305e7b2064839cf477539dad4 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 21 May 2014 09:10:28 -0300 Subject: [PATCH 146/185] Turning MemberValidator configurable. Adding line to member.conf.example --- manager.conf.example | 2 ++ .../java/org/fogbowcloud/manager/Main.java | 30 +++++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index d03deda6..aa760271 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -20,6 +20,8 @@ federation_user_name=fogbow federation_user_password=fogbow federation_user_tenant_name=demo +member_validator=org.fogbowcloud.manager.core.DefaultMemberValidator + cert_path= scheduler_period=30000 diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index b25b723f..418ebbd9 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -3,6 +3,7 @@ import java.io.FileInputStream; import java.util.Properties; +import org.fogbowcloud.manager.core.FederationMemberValidator; import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; @@ -17,41 +18,44 @@ public static void main(String[] args) throws Exception { Properties properties = new Properties(); FileInputStream input = new FileInputStream(args[0]); properties.load(input); - + ComputePlugin computePlugin = (ComputePlugin) createInstance( "compute_class", properties); IdentityPlugin identityPlugin = (IdentityPlugin) createInstance( "identity_class", properties); + + FederationMemberValidator validator = (FederationMemberValidator) createInstance( + "member_validator", properties); ManagerController facade = new ManagerController(properties); facade.setComputePlugin(computePlugin); facade.setIdentityPlugin(identityPlugin); + facade.setValidator(validator); - ManagerXmppComponent xmpp = new ManagerXmppComponent(properties.getProperty("xmpp_jid"), - properties.getProperty("xmpp_password"), - properties.getProperty("xmpp_host"), - Integer.parseInt(properties.getProperty("xmpp_port")), - facade); + ManagerXmppComponent xmpp = new ManagerXmppComponent( + properties.getProperty("xmpp_jid"), + properties.getProperty("xmpp_password"), + properties.getProperty("xmpp_host"), + Integer.parseInt(properties.getProperty("xmpp_port")), facade); xmpp.setRendezvousAddress(properties.getProperty("rendezvous_jid")); xmpp.connect(); xmpp.process(false); xmpp.init(); facade.setPacketSender(xmpp); - + OCCIApplication application = new OCCIApplication(facade); - + Component http = new Component(); - http.getServers().add(Protocol.HTTP, Integer - .parseInt(properties.getProperty("http_port"))); + http.getServers().add(Protocol.HTTP, + Integer.parseInt(properties.getProperty("http_port"))); http.getDefaultHost().attach(application); http.start(); } - + private static Object createInstance(String propName, Properties properties) throws Exception { return Class.forName(properties.getProperty(propName)) .getConstructor(Properties.class).newInstance(properties); } - - + } From bf48740ca233ef2f687b6956ee6555174b858051 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 21 May 2014 10:21:21 -0300 Subject: [PATCH 147/185] Deleting TestPostComputer. Fixing RequestRepository : Returing all requests. Fixing tests. --- .../occi/request/RequestRepository.java | 27 +++---- .../occi/request/RequestServerResource.java | 3 - .../manager/occi/TestDeleteRequest.java | 79 +++++++++++++------ .../manager/occi/TestGetRequest.java | 4 +- .../manager/occi/TestOCCIApplication.java | 29 ++++--- .../manager/occi/TestPostCompute.java | 9 --- .../manager/occi/util/OCCITestHelper.java | 9 ++- 7 files changed, 95 insertions(+), 65 deletions(-) delete mode 100644 src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index aa6fc5f2..c3081e7d 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -68,23 +68,22 @@ public Request get(String user, String requestId) { public List getByUser(String user) { LOGGER.debug("Getting instances by user " + user); List userRequests = requests.get(user); - // return userRequests == null ? new LinkedList() : new - // LinkedList( - // userRequests); - return userRequests == null ? new LinkedList() - : normalizeRequestsByUser(userRequests); + return userRequests == null ? new LinkedList() : new LinkedList( + userRequests); +// return userRequests == null ? new LinkedList() +// : normalizeRequestsByUser(userRequests); } - private List normalizeRequestsByUser(List userRequests) { - List requests = new LinkedList(); - for (Request userRequest : userRequests) { - if (!userRequest.getState().equals(RequestState.DELETED)) { - requests.add(userRequest); - } - } - return requests; - } +// private List normalizeRequestsByUser(List userRequests) { +// List requests = new LinkedList(); +// for (Request userRequest : userRequests) { +// if (!userRequest.getState().equals(RequestState.DELETED)) { +// requests.add(userRequest); +// } +// } +// return requests; +// } public void removeByUser(String user) { List requestsByUser = requests.get(user); diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java index 7922a1c1..f7362f82 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java @@ -123,9 +123,6 @@ protected static String generateResponse(List requests, HttpRequest req response += HeaderUtils.X_OCCI_LOCATION + requestEndpoint + "/" + request.getId() + "\n"; } - if (response.equals("")) { - response = "Empty"; - } return response; } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java index 9d6d0e0e..58439d5e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteRequest.java @@ -7,14 +7,17 @@ import java.util.List; import java.util.Map; +import org.apache.commons.codec.Charsets; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; +import org.apache.http.ParseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.Category; @@ -25,6 +28,7 @@ import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.RequestAttribute; import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.junit.After; import org.junit.Assert; @@ -42,13 +46,15 @@ public void setup() throws Exception { this.requestHelper = new OCCITestHelper(); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(""); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(""); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn( - new Token("id", OCCITestHelper.USER_MOCK, new Date(), - new HashMap())); + Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)) + .thenReturn( + new Token("id", OCCITestHelper.USER_MOCK, new Date(), + new HashMap())); Mockito.when(identityPlugin.getToken(OCCITestHelper.INVALID_TOKEN)).thenThrow( new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)); this.requestHelper.initializeComponent(computePlugin, identityPlugin); @@ -73,7 +79,7 @@ public void testDeleteEmptyRequest() throws URISyntaxException, HttpException, I HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); // Delete HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST); delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); @@ -83,15 +89,15 @@ public void testDeleteEmptyRequest() throws URISyntaxException, HttpException, I // Get response = client.execute(get); Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); } @Test public void testDeleteSpecificRequest() throws URISyntaxException, HttpException, IOException { // Post HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); - Category category = new Category(RequestConstants.TERM, - RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); + Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, + OCCIHeaders.KIND_CLASS); post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); @@ -105,36 +111,38 @@ public void testDeleteSpecificRequest() throws URISyntaxException, HttpException HttpDelete delete = new HttpDelete(requestLocations.get(0)); delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(delete); + final int deletedRequestAmount = 1; Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Get HttpGet get = new HttpGet(OCCITestHelper.URI_FOGBOW_REQUEST); get.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); - response = client.execute(get); - Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); + Assert.assertEquals(deletedRequestAmount, deletedInstancesCounter(response)); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testDeleteManyRequestsIndividually() throws URISyntaxException, HttpException, IOException { + final int defaultAmount = 5; + // Post HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); - Category category = new Category(RequestConstants.TERM, - RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); + Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, + OCCIHeaders.KIND_CLASS); post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, - RequestAttribute.INSTANCE_COUNT.getValue() + " = 200"); + post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + + " = " + defaultAmount); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); List requestLocations = OCCITestHelper.getRequestLocations(response); - Assert.assertEquals(200, requestLocations.size()); + Assert.assertEquals(defaultAmount, requestLocations.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Delete all requests individually @@ -153,26 +161,29 @@ public void testDeleteManyRequestsIndividually() throws URISyntaxException, Http get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); - Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); + + Assert.assertEquals(defaultAmount, deletedInstancesCounter(response)); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testDeleteAllRequests() throws URISyntaxException, HttpException, IOException { + final int createdMount = 5; + // Post HttpPost post = new HttpPost(OCCITestHelper.URI_FOGBOW_REQUEST); - Category category = new Category(RequestConstants.TERM, - RequestConstants.SCHEME, OCCIHeaders.KIND_CLASS); + Category category = new Category(RequestConstants.TERM, RequestConstants.SCHEME, + OCCIHeaders.KIND_CLASS); post.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); post.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); post.addHeader(OCCIHeaders.CATEGORY, category.toHeader()); - post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, - RequestAttribute.INSTANCE_COUNT.getValue() + " = 200"); + post.addHeader(OCCIHeaders.X_OCCI_ATTRIBUTE, RequestAttribute.INSTANCE_COUNT.getValue() + + " = " + createdMount); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(post); List requestIDs = OCCITestHelper.getRequestLocations(response); - Assert.assertEquals(200, requestIDs.size()); + Assert.assertEquals(createdMount, requestIDs.size()); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); // Delete @@ -189,14 +200,13 @@ public void testDeleteAllRequests() throws URISyntaxException, HttpException, IO get.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); response = client.execute(get); - Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); + Assert.assertEquals(createdMount, deletedInstancesCounter(response)); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); } @Test public void testDeleteRequestNotFound() throws URISyntaxException, HttpException, IOException { - HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST + "/" - + "not_found_id"); + HttpDelete delete = new HttpDelete(OCCITestHelper.URI_FOGBOW_REQUEST + "/" + "not_found_id"); delete.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); delete.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); HttpClient client = new DefaultHttpClient(); @@ -216,6 +226,25 @@ public void testDeleteWithInvalidToken() throws URISyntaxException, HttpExceptio Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); } + private int deletedInstancesCounter(HttpResponse response) throws ParseException, IOException, + URISyntaxException, HttpException { + HttpClient client = new DefaultHttpClient(); + List requestLocations2 = OCCITestHelper.getRequestLocations(response); + int countDeletedInscantes = 0; + for (String requestLocation : requestLocations2) { + HttpGet getSpecific = new HttpGet(requestLocation); + getSpecific.addHeader(OCCIHeaders.CONTENT_TYPE, OCCITestHelper.CONTENT_TYPE_OCCI); + getSpecific.addHeader(OCCIHeaders.X_AUTH_TOKEN, OCCITestHelper.ACCESS_TOKEN); + response = client.execute(getSpecific); + String responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + if (responseStr.contains(RequestState.DELETED.getValue())) { + countDeletedInscantes++; + } + } + return countDeletedInscantes; + } + @After public void tearDown() throws Exception { this.requestHelper.stopComponent(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 720a4648..7a11630d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -79,7 +79,7 @@ public void testGetRequest() throws URISyntaxException, HttpException, IOExcepti HttpResponse response = client.execute(get); Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); } @Test @@ -91,7 +91,7 @@ public void testGetRequestPlainContent() throws URISyntaxException, HttpExceptio HttpResponse response = client.execute(get); Assert.assertEquals(0, OCCITestHelper.getRequestLocations(response).size()); - Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); + Assert.assertEquals(HttpStatus.SC_NO_CONTENT, response.getStatusLine().getStatusCode()); } @Test diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 0cddf6f8..cbd9d218 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -13,7 +13,6 @@ import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; @@ -57,14 +56,13 @@ public void setUp() { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); HashMap tokenAttr = new HashMap(); -// tokenAttr.put(OCCIHeaders.X_TOKEN_USER, OCCITestHelper.USER_MOCK); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); - + Mockito.when(identityPlugin.getToken(Mockito.anyString())).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - + managerFacade.setIdentityPlugin(identityPlugin); managerFacade.setComputePlugin(computePlugin); managerFacade.setSSHTunnel(sshTunnel); @@ -88,9 +86,10 @@ public void testGetRequestDetails() throws InterruptedException { @Test public void testGetRequestDetailsAfterPeriod() throws InterruptedException { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID); - + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(INSTANCE_ID); + managerFacade.setComputePlugin(computePlugin); occiApplication.createRequests(OCCITestHelper.ACCESS_TOKEN, new ArrayList(), xOCCIAtt); @@ -98,7 +97,7 @@ public void testGetRequestDetailsAfterPeriod() throws InterruptedException { Assert.assertEquals(1, requests.size()); String requestId = requests.get(0).getId(); Request requestDetails = occiApplication.getRequest(OCCITestHelper.ACCESS_TOKEN, requestId); - + Thread.sleep(SCHEDULER_PERIOD * 2); Assert.assertEquals(requestId, requestDetails.getId()); @@ -143,7 +142,7 @@ public void testRemoveAllRequest() { occiApplication.removeAllRequests(OCCITestHelper.ACCESS_TOKEN); requestsFromUser = occiApplication.getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); - Assert.assertEquals(0, requestsFromUser.size()); + Assert.assertEquals(numberOfInstances, counterDeletedRequests(requestsFromUser)); } @Test @@ -161,6 +160,16 @@ public void testRemoveSpecificRequest() { occiApplication.removeRequest(OCCITestHelper.ACCESS_TOKEN, requestsFromUser.get(1).getId()); requestsFromUser = occiApplication.getRequestsFromUser(OCCITestHelper.ACCESS_TOKEN); - Assert.assertEquals(numberOfInstances - 1, requestsFromUser.size()); + Assert.assertEquals(1, counterDeletedRequests(requestsFromUser)); + } + + private int counterDeletedRequests(List requestsFromUser) { + int count = 0; + for (Request request : requestsFromUser) { + if (request.getState().equals(RequestState.DELETED)) { + count++; + } + } + return count; } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java deleted file mode 100644 index 3363872d..00000000 --- a/src/test/java/org/fogbowcloud/manager/occi/TestPostCompute.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.fogbowcloud.manager.occi; - -import static org.junit.Assert.fail; - -import org.junit.Ignore; -import org.junit.Test; - -public class TestPostCompute { -} diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index 02b7bc88..e7f93064 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -99,8 +99,13 @@ public void stopComponent() throws Exception { public static List getRequestLocations(HttpResponse response) throws ParseException, IOException { - String responseStr = EntityUtils.toString(response.getEntity(), - String.valueOf(Charsets.UTF_8)); + String responseStr = ""; + try { + responseStr = EntityUtils.toString(response.getEntity(), + String.valueOf(Charsets.UTF_8)); + } catch (Exception e) { + return new ArrayList(); + } List requestIds = new ArrayList(); if (responseStr.contains(HeaderUtils.X_OCCI_LOCATION)) { From 5f8bbab3c5bae0a0d231b4d67458e70a854cd7c5 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 21 May 2014 11:02:53 -0300 Subject: [PATCH 148/185] Refatoring RequestRepository. --- .../manager/occi/request/RequestRepository.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java index c3081e7d..6c243fa7 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestRepository.java @@ -70,21 +70,8 @@ public List getByUser(String user) { List userRequests = requests.get(user); return userRequests == null ? new LinkedList() : new LinkedList( userRequests); -// return userRequests == null ? new LinkedList() -// : normalizeRequestsByUser(userRequests); - } -// private List normalizeRequestsByUser(List userRequests) { -// List requests = new LinkedList(); -// for (Request userRequest : userRequests) { -// if (!userRequest.getState().equals(RequestState.DELETED)) { -// requests.add(userRequest); -// } -// } -// return requests; -// } - public void removeByUser(String user) { List requestsByUser = requests.get(user); if (requestsByUser != null) { From 216b64f2c62a29a5371299d01bb20511a142be06 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 21 May 2014 12:13:20 -0300 Subject: [PATCH 149/185] Refactoring tests --- .../manager/core/model/FederationMember.java | 12 +- .../manager/xmpp/core/model/DateUtils.java | 15 + .../manager/core/TestManagerController.java | 814 +++++++----------- .../manager/occi/TestDeleteCompute.java | 5 +- .../manager/occi/TestGetCompute.java | 7 +- .../manager/occi/TestGetRequest.java | 3 +- .../manager/occi/TestOCCIApplication.java | 6 +- .../manager/occi/TestTokenServerResource.java | 3 +- .../occi/plugins/TestComputeOpenStack.java | 70 +- .../occi/plugins/TestIdentityOpenStack.java | 17 +- .../manager/occi/util/OCCITestHelper.java | 2 - .../manager/occi/util/PluginHelper.java | 15 +- .../xmpp/TestDeleteRemoteInstance.java | 25 +- .../manager/xmpp/TestGetRemoteInstance.java | 73 +- .../manager/xmpp/TestIAmAlive.java | 7 +- .../xmpp/TestRequestRemoteInstance.java | 3 +- .../manager/xmpp/TestWhoIsAlive.java | 7 +- .../manager/xmpp/util/ManagerTestHelper.java | 26 +- .../manager/xmpp/util/TestHelperData.java | 31 + 19 files changed, 486 insertions(+), 655 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java diff --git a/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java b/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java index 6090e6c5..74099e9b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java @@ -1,16 +1,11 @@ package org.fogbowcloud.manager.core.model; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class FederationMember { public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - + private long lastTime; private ResourcesInfo resourcesInfo; @@ -31,10 +26,7 @@ public long getLastTime() { } public String getFormattedTime() { - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - return dateFormatISO8601.format(new Date(lastTime)); + return DateUtils.getDateISO8601Format(lastTime); } /** diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java b/src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java index 385e53e8..4d583477 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java +++ b/src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java @@ -1,5 +1,12 @@ package org.fogbowcloud.manager.xmpp.core.model; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + +import org.fogbowcloud.manager.core.model.FederationMember; + public class DateUtils { public DateUtils() { @@ -8,4 +15,12 @@ public DateUtils() { public long currentTimeMillis() { return System.currentTimeMillis(); } + + public static String getDateISO8601Format(long dateMili) { + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + String expirationDate = dateFormatISO8601.format(new Date(dateMili)); + return expirationDate; + } } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 3540027b..c8e16a92 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -2,19 +2,13 @@ import java.io.IOException; import java.security.cert.CertificateException; -import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Collection; import java.util.Date; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; -import java.util.ListIterator; -import java.util.Locale; import java.util.Map; import java.util.Properties; -import java.util.TimeZone; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; @@ -36,9 +30,9 @@ import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; -import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -46,76 +40,92 @@ public class TestManagerController { - private static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; private static final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; - - private static final Long SCHEDULER_PERIOD = 500L; - public static final String USER_NAME = "user"; - public static final String USER_PASS = "password"; - public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; public static final String ACCESS_TOKEN_ID_2 = "2222CVXV23T4TG42VVCV"; - private static final Long GRACE_TIME = 30L; - private static final String TENANT_NAME = "tenantName"; - private static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; private Token userToken; private ManagerController managerController; private ManagerTestHelper managerTestHelper; - + private Map xOCCIAtt; + @Before - public void setUp() throws Exception { - managerController = new ManagerController(new Properties()); + public void setUp() throws Exception { managerTestHelper = new ManagerTestHelper(); + + // default instance count value is 1 + xOCCIAtt = new HashMap(); + xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), + String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); + HashMap tokenAttr = new HashMap(); -// tokenAttr.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - userToken = new Token(ACCESS_TOKEN_ID, USER_NAME, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); + userToken = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, + TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttr); + + Properties properties = new Properties(); + properties.put("federation_user_name", TestHelperData.USER_NAME); + properties.put("federation_user_password", TestHelperData.USER_PASS); + properties.put("federation_user_tenant_name", TestHelperData.TENANT_NAME); + properties.put("scheduler_period", TestHelperData.SCHEDULER_PERIOD.toString()); + managerController = new ManagerController(properties); + + // mocking compute + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + + // mocking identity + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(userToken); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); } @Test public void testGetFederationMember() throws InterruptedException { - Properties properties = new Properties(); - properties.put("federation_user_name", USER_NAME); - properties.put("federation_user_password", USER_PASS); - properties.put("federation_user_tenant_name", TENANT_NAME); - managerController = new ManagerController(properties); OpenStackIdentityPlugin openStackidentityPlugin = Mockito .mock(OpenStackIdentityPlugin.class); Map tokenCredentials = new HashMap(); - tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, USER_PASS); - tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, TestHelperData.USER_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, TestHelperData.USER_PASS); + tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TestHelperData.TENANT_NAME); long tokenExpirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); -// attributesTokenReturn.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(tokenExpirationTime), attributesTokenReturn); - - Map attributesTokenReturn2 = new HashMap(); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); -// attributesTokenReturn2.put(OCCIHeaders.X_TOKEN_USER, USER_NAME); + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TestHelperData.TENANT_NAME); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, new Date( + tokenExpirationTime), attributesTokenReturn); - Token token2 = new Token(ACCESS_TOKEN_ID_2, USER_NAME, new Date(tokenExpirationTime + LONG_TIME), - attributesTokenReturn2); + Token token2 = new Token(ACCESS_TOKEN_ID_2, TestHelperData.USER_NAME, new Date( + tokenExpirationTime + TestHelperData.LONG_TIME), attributesTokenReturn); - Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, token2); - Mockito.when(openStackidentityPlugin.isValid(ACCESS_TOKEN_ID)).thenReturn(true, false); + Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, + token2); + Mockito.when(openStackidentityPlugin.isValid(TestHelperData.ACCESS_TOKEN_ID)).thenReturn( + true, false); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token Token federationUserToken = managerController.getFederationUserToken(); String accessToken = federationUserToken.getAccessId(); - Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); + Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, accessToken); // Use member token accessToken = managerController.getFederationUserToken().getAccessId(); - Assert.assertEquals(ACCESS_TOKEN_ID, accessToken); + Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(tokenExpirationTime + GRACE_TIME); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn( + tokenExpirationTime + TestHelperData.GRACE_TIME); token.setDateUtils(dateUtils); // Get new token @@ -128,53 +138,58 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { final int tokenUpdaterInterval = 100; final long now = System.currentTimeMillis(); long tokenExpirationTime = now + (4 * tokenUpdaterInterval); - + Properties properties = new Properties(); properties.put("token_update_period", Integer.toString(tokenUpdaterInterval)); managerController = new ManagerController(properties); DateUtils dateUtils = Mockito.mock(DateUtils.class); RequestRepository requestRepository = new RequestRepository(); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(tokenExpirationTime), - new HashMap()); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, new Date( + tokenExpirationTime), new HashMap()); for (int i = 0; i < 5; i++) { - requestRepository.addRequest(USER_NAME, new Request("id" + i, token, USER_NAME, null, null)); + requestRepository.addRequest(TestHelperData.USER_NAME, new Request("id" + i, token, + TestHelperData.USER_NAME, null, null)); } managerController.setRequests(requestRepository); - //mocking identity + // mocking identity IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); - Token tokenUpdatedFirstTime = new Token(ACCESS_TOKEN_ID_2, USER_NAME, new Date(tokenExpirationTime - + tokenUpdaterInterval), new HashMap()); - Mockito.when(identityPlugin.createToken(token)).thenReturn( - tokenUpdatedFirstTime); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); + Token tokenUpdatedFirstTime = new Token(ACCESS_TOKEN_ID_2, TestHelperData.USER_NAME, + new Date(tokenExpirationTime + tokenUpdaterInterval), new HashMap()); + Mockito.when(identityPlugin.createToken(token)).thenReturn(tokenUpdatedFirstTime); managerController.setIdentityPlugin(identityPlugin); - + Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); managerController.setDateUtils(dateUtils); managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { - Assert.assertEquals(ACCESS_TOKEN_ID, request.getToken().getAccessId()); + Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, request.getToken() + .getAccessId()); } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { - Assert.assertEquals(ACCESS_TOKEN_ID, request.getToken().getAccessId()); + Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, request.getToken() + .getAccessId()); } } - Mockito.when(dateUtils.currentTimeMillis()).thenReturn(tokenExpirationTime - tokenUpdaterInterval); + Mockito.when(dateUtils.currentTimeMillis()).thenReturn( + tokenExpirationTime - tokenUpdaterInterval); managerController.setDateUtils(dateUtils); managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { Assert.assertEquals(ACCESS_TOKEN_ID_2, request.getToken().getAccessId()); } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { - Assert.assertEquals(ACCESS_TOKEN_ID, request.getToken().getAccessId()); + Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, request.getToken() + .getAccessId()); } } } @@ -182,29 +197,30 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { @Test public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); + properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); - Request request1 = new Request("id1", token, USER_NAME, null, null); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, + new Date(), new HashMap()); + Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); request1.setState(RequestState.DELETED); - Request request2 = new Request("id2", token, USER_NAME, null, null); + Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); request2.setState(RequestState.DELETED); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(USER_NAME, request1); - requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(TestHelperData.USER_NAME, request1); + requestRepository.addRequest(TestHelperData.USER_NAME, request2); managerController.setRequests(requestRepository); RequestRepository requestRepositoryCopy = new RequestRepository(); - requestRepositoryCopy.addRequest(USER_NAME, request1); - requestRepositoryCopy.addRequest(USER_NAME, request2); + requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request1); + requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request2); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(INSTANCE_ID)); + .thenReturn(new Instance(TestHelperData.INSTANCE_ID)); Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); @@ -216,7 +232,8 @@ private List getRequestsDeleted(RequestRepository requestRepository) { List requests = new ArrayList(); for (Request request : requestRepository.get(RequestState.DELETED)) { try { - requests.add(managerController.getRequest(ACCESS_TOKEN_ID, request.getId())); + requests.add(managerController.getRequest(TestHelperData.ACCESS_TOKEN_ID, + request.getId())); } catch (Exception e) { } } @@ -226,31 +243,32 @@ private List getRequestsDeleted(RequestRepository requestRepository) { @Test public void testMonitoringDeletedRequestAndNotFoundInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); + properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); - Request request1 = new Request("id1", token, USER_NAME, null, null); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, + new Date(), new HashMap()); + Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); request1.setState(RequestState.DELETED); - Request request2 = new Request("id2", token, USER_NAME, null, null); + Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); request2.setState(RequestState.DELETED); - Request request3 = new Request("id3", token, USER_NAME, null, null); + Request request3 = new Request("id3", token, TestHelperData.USER_NAME, null, null); request3.setState(RequestState.OPEN); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(USER_NAME, request1); - requestRepository.addRequest(USER_NAME, request2); - requestRepository.addRequest(USER_NAME, request3); + requestRepository.addRequest(TestHelperData.USER_NAME, request1); + requestRepository.addRequest(TestHelperData.USER_NAME, request2); + requestRepository.addRequest(TestHelperData.USER_NAME, request3); managerController.setRequests(requestRepository); RequestRepository requestRepositoryCopy = new RequestRepository(); - requestRepositoryCopy.addRequest(USER_NAME, request1); - requestRepositoryCopy.addRequest(USER_NAME, request2); - requestRepositoryCopy.addRequest(USER_NAME, request3); + requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request1); + requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request2); + requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request3); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); @@ -263,27 +281,29 @@ public void testMonitoringDeletedRequestAndNotFoundInstance() throws Interrupted @Test public void testMonitoringFulfilledRequestAndNotFoundInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); + properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); - Request request1 = new Request("id1", token, USER_NAME, null, null); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, + new Date(), new HashMap()); + Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", token, USER_NAME, null, null); + Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); request2.setState(RequestState.FULFILLED); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(USER_NAME, request1); - requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(TestHelperData.USER_NAME, request1); + requestRepository.addRequest(TestHelperData.USER_NAME, request2); managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); managerController.monitorInstances(); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } @@ -292,7 +312,7 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); } @@ -301,52 +321,54 @@ public void testMonitoringFulfilledRequestAndNotFoundInstance() throws Interrupt @SuppressWarnings("unchecked") @Test public void testMonitoringFulfilledRequestAndPesistentInstance() throws InterruptedException { - final int timeDefault = 5 * 60 * 1000; //Big time to not interfere this test + final int timeDefault = 5 * 60 * 1000; // Big time to not interfere this + // test Properties properties = new Properties(); properties.put("instance_monitoring_period", Integer.toString(timeDefault)); - properties.put("scheduler_period", 100 * SCHEDULER_PERIOD); + properties.put("scheduler_period", 100 * TestHelperData.SCHEDULER_PERIOD); managerController = new ManagerController(properties); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()); Map map = new HashMap(); map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - Request request1 = new Request("id1", token, USER_NAME, null, map); + Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, map); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", token, USER_NAME, null, map); - request2.setState(RequestState.FULFILLED); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(USER_NAME, request1); - requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(TestHelperData.USER_NAME, request1); managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); - Mockito.when(computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), - Mockito.anyMap())).thenReturn(INSTANCE_ID); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), + Mockito.anyMap())).thenReturn(TestHelperData.INSTANCE_ID); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - + managerController.setIdentityPlugin(identityPlugin); managerController.setComputePlugin(computePlugin); - - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + + List requestsFromUser = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - + managerController.monitorInstances(); - + for (Request request : requestsFromUser) { - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertTrue(request.getState().in(RequestState.OPEN)); } - + managerController.checkAndSubmitOpenRequests(); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } @@ -355,36 +377,38 @@ public void testMonitoringFulfilledRequestAndPesistentInstance() throws Interrup @Test public void testMonitoringFulfilledRequestAndOnetimeInstance() throws InterruptedException { Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(LONG_TIME)); + properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); managerController = new ManagerController(properties); - Token token = new Token(ACCESS_TOKEN_ID, USER_NAME, new Date(), new HashMap()); - Request request1 = new Request("id1", token, USER_NAME, null, null); + Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, + new Date(), new HashMap()); + Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", token, USER_NAME, null, null); + Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); request2.setState(RequestState.FULFILLED); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(USER_NAME, request1); - requestRepository.addRequest(USER_NAME, request2); + requestRepository.addRequest(TestHelperData.USER_NAME, request1); + requestRepository.addRequest(TestHelperData.USER_NAME, request2); managerController.setRequests(requestRepository); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); managerController.setIdentityPlugin(identityPlugin); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(token); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); managerController.monitorInstances(); - List requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(INSTANCE_ID)); + .thenReturn(new Instance(TestHelperData.INSTANCE_ID)); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } @@ -433,87 +457,46 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { @SuppressWarnings("unchecked") @Test public void testGetRequestsByUser() throws InterruptedException { + mockOKRequestCompute(); - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); - - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - - Thread.sleep(SCHEDULER_PERIOD * 2); + managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(USER_NAME, requests.get(0).getUser()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.USER_NAME, requests.get(0).getUser()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { + mockOKRequestCompute(); + + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); - - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); - - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - - Thread.sleep(SCHEDULER_PERIOD); +// Thread.sleep(TestHelperData.SCHEDULER_PERIOD); + managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + managerController + .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); @@ -525,13 +508,9 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio @Test public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); + properties.put("scheduler_period", TestHelperData.SCHEDULER_PERIOD.toString()); managerController = new ManagerController(properties); - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); @@ -539,14 +518,13 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(INSTANCE_ID) + .thenReturn(TestHelperData.INSTANCE_ID) .thenThrow( new OCCIException(ErrorType.QUOTA_EXCEEDED, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -554,23 +532,27 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - Thread.sleep(SCHEDULER_PERIOD); +// Thread.sleep(TestHelperData.SCHEDULER_PERIOD); + managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + managerController + .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -584,24 +566,20 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti @Test public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { Properties properties = new Properties(); - properties.put("scheduler_period", Long.toString(SCHEDULER_PERIOD)); + properties.put("scheduler_period", Long.toString(TestHelperData.SCHEDULER_PERIOD)); managerController = new ManagerController(properties); - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID, SECOND_INSTANCE_ID); + Mockito.any(Map.class))).thenReturn(TestHelperData.INSTANCE_ID, + SECOND_INSTANCE_ID); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(userToken); SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -609,23 +587,27 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr managerController.setComputePlugin(computePlugin); managerController.setSSHTunnel(sshTunnel); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - Thread.sleep(SCHEDULER_PERIOD); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD); +// managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + managerController + .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -635,9 +617,10 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getMemberId()); // getting second instance - Thread.sleep(SCHEDULER_PERIOD * 2); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD * 2); +// managerController.checkAndSubmitOpenRequests(); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); @@ -647,48 +630,21 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - - long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + TestHelperData.SCHEDULER_PERIOD; - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - String.valueOf(getDateISO8601Format(expirationRequestTime))); - - // mocking compute - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); - - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + String.valueOf(DateUtils.getDateISO8601Format(expirationRequestTime))); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -697,9 +653,9 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -709,63 +665,42 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { + long expirationRequestTime = System.currentTimeMillis() + TestHelperData.SCHEDULER_PERIOD + + TestHelperData.GRACE_TIME; - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - - long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD + GRACE_TIME; - - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - getDateISO8601Format(expirationRequestTime)); - - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + DateUtils.getDateISO8601Format(expirationRequestTime)); - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + mockOKRequestCompute(); - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD); - Thread.sleep(SCHEDULER_PERIOD); - - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD); // removing instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + managerController + .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); - Thread.sleep(SCHEDULER_PERIOD); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -775,47 +710,28 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") - @Test - public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - - long expirationRequestTime = System.currentTimeMillis() + SCHEDULER_PERIOD; - - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); - xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - getDateISO8601Format(expirationRequestTime)); - - // mocking compute + private void mockOKRequestCompute() { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.any(Map.class))).thenReturn(TestHelperData.INSTANCE_ID); + managerController.setComputePlugin(computePlugin); + } - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + @Test + public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { + long expirationRequestTime = System.currentTimeMillis() + TestHelperData.SCHEDULER_PERIOD; - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); + xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), + DateUtils.getDateISO8601Format(expirationRequestTime)); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -824,9 +740,9 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -837,49 +753,26 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { } - @SuppressWarnings("unchecked") @Test public void testOneTimeRequestValidFromInFuture() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - long now = System.currentTimeMillis(); - long startRequestTime = now + (SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + LONG_TIME; + long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + TestHelperData.LONG_TIME; - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.ONE_TIME.getValue())); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - getDateISO8601Format(expirationRequestTime)); - - // mocking compute - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); + DateUtils.getDateISO8601Format(expirationRequestTime)); - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + mockOKRequestCompute(); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -888,9 +781,9 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); // request is not in validity period yet Assert.assertEquals(1, requests.size()); @@ -900,61 +793,38 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // request is in validity period - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testPersistentRequestValidFromInFuture() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - long now = System.currentTimeMillis(); - long startRequestTime = now + (SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + LONG_TIME; + long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + TestHelperData.LONG_TIME; - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - getDateISO8601Format(expirationRequestTime)); + DateUtils.getDateISO8601Format(expirationRequestTime)); - // mocking compute - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); - - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + mockOKRequestCompute(); // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -963,9 +833,9 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); // request is not in validity period yet Assert.assertEquals(1, requests.size()); @@ -975,65 +845,42 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // request is in validity period - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - long now = System.currentTimeMillis(); - long startRequestTime = now + (SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (SCHEDULER_PERIOD * 3); + long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 3); - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - getDateISO8601Format(expirationRequestTime)); - - // mocking compute - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); - - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + DateUtils.getDateISO8601Format(expirationRequestTime)); + mockOKRequestCompute(); + // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); // request is not in validity period yet Assert.assertEquals(1, requests.size()); @@ -1043,25 +890,26 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // request is in validity period - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); // remove instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + managerController + .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // request is not in validity period anymore - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -1071,52 +919,29 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - long now = System.currentTimeMillis(); - long startRequestTime = now + (SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (SCHEDULER_PERIOD * 3); + long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 3); - // default instance count value is 1 - Map xOCCIAtt = new HashMap(); - xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), - String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), - getDateISO8601Format(expirationRequestTime)); - - // mocking compute - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(INSTANCE_ID); - - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); -// Mockito.when(identityPlugin.getUser(ACCESS_TOKEN_ID)).thenReturn(USER_NAME); - Mockito.when(identityPlugin.getToken(ACCESS_TOKEN_ID)).thenReturn(userToken); - - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); + DateUtils.getDateISO8601Format(expirationRequestTime)); + mockOKRequestCompute(); + // creating request - managerController.createRequests(ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + xOCCIAtt); - List requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); // request is not in validity period yet Assert.assertEquals(1, requests.size()); @@ -1126,27 +951,28 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // request is in validity period - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // remove instance - managerController.removeInstance(ACCESS_TOKEN_ID, INSTANCE_ID); + managerController + .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); - Thread.sleep(SCHEDULER_PERIOD + GRACE_TIME); + Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); // request is not in validity period anymore - requests = managerController.getRequestsFromUser(ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -1156,14 +982,6 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getMemberId()); } - public static String getDateISO8601Format(long dateMili) { - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - String expirationDate = dateFormatISO8601.format(new Date(dateMili)); - return expirationDate; - } - @Test public void testSubmitRequestForRemoteMemberValidation() { ResourcesInfo resources = Mockito.mock(ResourcesInfo.class); @@ -1175,31 +993,27 @@ public void testSubmitRequestForRemoteMemberValidation() { list.add(member); managerController.setMembers(list); - RestrictCAsMemberValidator validatorMock = Mockito - .mock(RestrictCAsMemberValidator.class); + RestrictCAsMemberValidator validatorMock = Mockito.mock(RestrictCAsMemberValidator.class); Mockito.doReturn(true).when(validatorMock).canDonateTo(member); managerController.setValidator(validatorMock); - + Token token = Mockito.mock(Token.class); Mockito.doReturn(null).when(token).getAccessId(); - + IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn( - token); + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(token); managerController.setIdentityPlugin(identityPlugin); - + ComputePlugin plugin = Mockito.mock(OpenStackComputePlugin.class); - Mockito.doReturn("answer") - .when(plugin) - .requestInstance(null, null, null); - + Mockito.doReturn("answer").when(plugin).requestInstance(null, null, null); + managerController.setComputePlugin(plugin); - Assert.assertEquals("answer", managerController - .createInstanceForRemoteMember("abc", null, null)); + Assert.assertEquals("answer", + managerController.createInstanceForRemoteMember("abc", null, null)); Mockito.doReturn(false).when(validatorMock).canDonateTo(member); managerController.setValidator(validatorMock); - Assert.assertEquals(null, managerController - .createInstanceForRemoteMember("abc", null, null)); + Assert.assertEquals(null, + managerController.createInstanceForRemoteMember("abc", null, null)); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 13faa025..057a9c84 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -17,6 +17,7 @@ import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -45,12 +46,12 @@ public void setup() throws Exception { List requests = new LinkedList(); Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, - OCCITestHelper.USER_MOCK, OCCITestHelper.TOKEN_FUTURE_EXPIRATION, + OCCITestHelper.USER_MOCK, TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_ID); requests.add(request1); Request request2 = new Request("2", new Token("otherToken", "otherUser", - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), "otherUser", null, null); request2.setInstanceId(OTHER_INSTANCE_ID); requests.add(request2); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 6d1211d4..90f66272 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -21,6 +21,7 @@ import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -61,17 +62,17 @@ public void setup() throws Exception { List requests = new LinkedList(); Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request1.setInstanceId(INSTANCE_1_ID); requests.add(request1); Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), OCCITestHelper.USER_MOCK, null, null); request2.setInstanceId(INSTANCE_2_ID); requests.add(request2); Request request3 = new Request("3", new Token("token", "user", - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), "user", + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), "user", null, null); request3.setInstanceId(INSTANCE_3_ID_WITHOUT_USER); requests.add(request3); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index 7a11630d..f714768a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -31,6 +31,7 @@ import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.ComputeApplication; import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -63,7 +64,7 @@ public void setup() throws Exception { HashMap tokenAttr = new HashMap(); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); + TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index cbd9d218..46af3619 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -20,6 +20,7 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -51,13 +52,13 @@ public void setUp() { Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( - new OCCIException(ErrorType.BAD_REQUEST, + new OCCIException(ErrorType.QUOTA_EXCEEDED, ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); HashMap tokenAttr = new HashMap(); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); + TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(Mockito.anyString())).thenReturn(userToken); @@ -77,6 +78,7 @@ public void testGetRequestDetails() throws InterruptedException { String requestId = requests.get(0).getId(); Request requestDetails = occiApplication.getRequest(OCCITestHelper.ACCESS_TOKEN, requestId); + Thread.sleep(100); Assert.assertEquals(requestId, requestDetails.getId()); Assert.assertNull(requestDetails.getInstanceId()); Assert.assertEquals(RequestState.OPEN, requestDetails.getState()); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java index 661999d7..68460ac0 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -16,6 +16,7 @@ import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.OCCITestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -57,7 +58,7 @@ public void testGetTokenWrongContentType() throws Exception { @SuppressWarnings("unchecked") @Test public void testGetToken() throws Exception { - Token token = new Token(ACCESS_TOKEN_ID, "user", OCCITestHelper.TOKEN_FUTURE_EXPIRATION, + Token token = new Token(ACCESS_TOKEN_ID, "user", TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()); Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(token); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 6522a6c3..067fef3d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -72,11 +72,11 @@ public void testRequestAValidInstance() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); Instance instance = computeOpenStack - .getInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); + .getInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID); Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails( instance.toOCCIMassageFormatDetails(), ComputeApplication.CORE_ATTRIBUTE_OCCI))); @@ -109,7 +109,7 @@ public void testRequestWithoutOSCateory() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.SMALL_TERM, RequestConstants.TEMPLATE_RESOURCE_SCHEME, RequestConstants.MIXIN_CLASS)); - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap()); } @@ -120,7 +120,7 @@ public void testRequestWithoutSizeCateory() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); } @@ -135,7 +135,7 @@ public void testNotSupportedOCCICoreAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.CORE_ATTRIBUTE_OCCI, "3"); - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt); + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, xOCCIAtt); } @Test(expected = OCCIException.class) @@ -149,7 +149,7 @@ public void testNotSupportedOCCIMemAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.MEMORY_ATTRIBUTE_OCCI, "5"); - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt); + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, xOCCIAtt); } @Test(expected = OCCIException.class) @@ -163,7 +163,7 @@ public void testNotSupportedOCCIArchAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.ARCHITECTURE_ATTRIBUTE_OCCI, "x86"); - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt); + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, xOCCIAtt); } @Test(expected = OCCIException.class) @@ -177,7 +177,7 @@ public void testNotSupportedOCCISpeedAtt() { Map xOCCIAtt = new HashMap(); xOCCIAtt.put(ComputeApplication.SPEED_ATTRIBUTE_OCCI, "2"); - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt); + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, xOCCIAtt); } @Test @@ -192,9 +192,9 @@ public void testSupportedOCCIAtt() { xOCCIAtt.put(ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI, "server-test"); Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, xOCCIAtt)); - String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID).toOCCIMassageFormatDetails(); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); @@ -213,9 +213,9 @@ public void testMoreSupportedOCCIAtts() { xOCCIAtt.put("occi.compute.state", "inactive"); Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, xOCCIAtt)); + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, xOCCIAtt)); - String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID).toOCCIMassageFormatDetails(); Assert.assertEquals("server-test", getAttValueFromDetails(instanceDetails, ComputeApplication.HOSTNAME_ATTRIBUTE_OCCI)); @@ -226,7 +226,7 @@ public void testMoreSupportedOCCIAtts() { @Test public void testGetAllInstanceIds() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); // requesting one default instance @@ -234,12 +234,12 @@ public void testGetAllInstanceIds() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); // check getting all instance ids instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(1, instanceLocations.size()); Assert.assertEquals(URL + ComputeApplication.TARGET + "/" + FIRST_INSTANCE_ID, instanceLocations.get(0)); @@ -248,7 +248,7 @@ public void testGetAllInstanceIds() { @Test public void testGetAllManyInstanceIds() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); // requesting default instance @@ -258,13 +258,13 @@ public void testGetAllManyInstanceIds() { for (String instanceId : expectedInstanceIds) { Assert.assertEquals(instanceId, computeOpenStack - .requestInstance(PluginHelper.AUTH_TOKEN, categories, + .requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); } // check getting all instance ids instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); for (String expectedId : expectedInstanceIds) { Assert.assertTrue(instanceLocations.contains(URL + ComputeApplication.TARGET + "/" @@ -285,7 +285,7 @@ private List getInstanceLocations(List intances) { @Test public void testGetInstanceDetails() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); // requesting one default instance @@ -293,14 +293,14 @@ public void testGetInstanceDetails() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.AUTH_TOKEN, categories, + computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); // check instance details instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(1, instanceLocations.size()); - String instanceDetails = computeOpenStack.getInstance(PluginHelper.AUTH_TOKEN, + String instanceDetails = computeOpenStack.getInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID).toOCCIMassageFormatDetails(); Assert.assertEquals(FIRST_INSTANCE_ID, getAttValueFromDetails(instanceDetails, ComputeApplication.ID_CORE_ATTRIBUTE_OCCI)); @@ -317,19 +317,19 @@ public void testGetInstanceDetails() { @Test public void testDeleteAllInstancesEmpty() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); - computeOpenStack.removeInstances(PluginHelper.AUTH_TOKEN); + computeOpenStack.removeInstances(PluginHelper.ACCESS_ID); instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); } @Test public void testDeleteAllManyInstances() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); // requesting default instances @@ -338,26 +338,26 @@ public void testDeleteAllManyInstances() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { Assert.assertEquals(instanceId, computeOpenStack - .requestInstance(PluginHelper.AUTH_TOKEN, categories, + .requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); } // check number of instances instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); // removing all instances - computeOpenStack.removeInstances(PluginHelper.AUTH_TOKEN); + computeOpenStack.removeInstances(PluginHelper.ACCESS_ID); instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); } @Test public void testDeleteOneInstance() { List instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(0, instanceLocations.size()); // requesting default instances @@ -366,19 +366,19 @@ public void testDeleteOneInstance() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { Assert.assertEquals(instanceId, computeOpenStack - .requestInstance(PluginHelper.AUTH_TOKEN, categories, + .requestInstance(PluginHelper.ACCESS_ID, categories, new HashMap())); } // check number of instances instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(expectedInstanceIds.size(), instanceLocations.size()); // removing one instances - computeOpenStack.removeInstance(PluginHelper.AUTH_TOKEN, FIRST_INSTANCE_ID); + computeOpenStack.removeInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID); instanceLocations = getInstanceLocations(computeOpenStack - .getInstances(PluginHelper.AUTH_TOKEN)); + .getInstances(PluginHelper.ACCESS_ID)); Assert.assertEquals(expectedInstanceIds.size() - 1, instanceLocations.size()); } } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 00b1358a..6c1fd1f1 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -10,6 +10,7 @@ import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.PluginHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -39,7 +40,7 @@ public void tearDown() throws Exception { @Test public void testValidToken() { Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, - this.identityOpenStack.getToken(PluginHelper.AUTH_TOKEN).getUser()); + this.identityOpenStack.getToken(PluginHelper.ACCESS_ID).getUser()); } @Test(expected = ResourceException.class) @@ -50,7 +51,7 @@ public void testInvalidToken() { @Test public void testGetNameUserFromToken() { Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, - this.identityOpenStack.getToken(PluginHelper.AUTH_TOKEN).getUser()); + this.identityOpenStack.getToken(PluginHelper.ACCESS_ID).getUser()); } @Test(expected = ResourceException.class) @@ -68,9 +69,9 @@ public void testGetToken() { String authToken = token.getAccessId(); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); Date expirationDate = token.getExpirationDate(); - Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); + Assert.assertEquals(TestHelperData.TOKEN_FUTURE_EXPIRATION, expirationDate); } @Test @@ -83,17 +84,17 @@ public void testUpgradeToken() { String authToken = token.getAccessId(); String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); Date expirationDate = token.getExpirationDate(); - Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); + Assert.assertEquals(TestHelperData.TOKEN_FUTURE_EXPIRATION, expirationDate); Token token2 = this.identityOpenStack.createToken(token); authToken = token2.getAccessId(); tenantID = token2.get(OCCIHeaders.X_TOKEN_TENANT_ID); expirationDate = token2.getExpirationDate(); - Assert.assertEquals(PluginHelper.AUTH_TOKEN, authToken); + Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(PluginHelper.EXPIRATION_DATE, expirationDate); + Assert.assertEquals(TestHelperData.TOKEN_FUTURE_EXPIRATION, expirationDate); } @Test(expected = OCCIException.class) diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java index e7f93064..aa896623 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/OCCITestHelper.java @@ -38,8 +38,6 @@ public class OCCITestHelper { public static final String URI_FOGBOW_QUERY = "http://localhost:8182/-/"; public static final String USER_MOCK = "user_mock"; public static final int ENDPOINT_PORT = 8182; - public static final long LONG_TIME = 24 * 60 * 60 * 1000; //one day - public static final Date TOKEN_FUTURE_EXPIRATION = new Date(System.currentTimeMillis() + LONG_TIME); private Component component; private RequestRepository requests; diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 677bce9b..0aa22972 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -8,6 +8,7 @@ import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.mockito.Mockito; import org.restlet.Component; import org.restlet.data.Protocol; @@ -16,12 +17,12 @@ public class PluginHelper { private Component component; - public static final String AUTH_TOKEN = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; + public static final String ACCESS_ID = "HgfugGJHgJgHJGjGJgJg-857GHGYHjhHjH"; public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; public static final String TENANT_NAME = "admin"; - public static final Date EXPIRATION_DATE = new Date(System.currentTimeMillis() - + OCCITestHelper.LONG_TIME); +// public static final Date EXPIRATION_DATE = new Date(System.currentTimeMillis() +// + TestHelperData.LONG_TIME); public static final String USERNAME_FOGBOW = "admin"; public static final String PASSWORD_FOGBOW = "reverse"; @@ -39,13 +40,13 @@ public void initializeKeystoneComponent() throws Exception { tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); // tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - Token token = new Token(AUTH_TOKEN, USERNAME_FOGBOW, EXPIRATION_DATE, tokenAttributes); + Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttributes); // TODO Refactor! We really need all these args to KeytoneApplication? KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, - PASSWORD_FOGBOW, TENANT_NAME, AUTH_TOKEN, token); + PASSWORD_FOGBOW, TENANT_NAME, ACCESS_ID, token); - keystoneApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); + keystoneApplication.putTokenAndUser(ACCESS_ID, USERNAME_FOGBOW); this.component.getDefaultHost().attach(keystoneApplication); this.component.start(); @@ -63,7 +64,7 @@ public void initializeComputeComponent(List expectedInstanceIds) throws expectedInstanceIds.get(1), expectedInstanceIds.get(2), expectedInstanceIds.get(3), expectedInstanceIds.get(4)); computeApplication.setIdGenerator(idGenerator); - computeApplication.putTokenAndUser(AUTH_TOKEN, USERNAME_FOGBOW); + computeApplication.putTokenAndUser(ACCESS_ID, USERNAME_FOGBOW); this.component.getDefaultHost().attach(computeApplication); this.component.start(); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java index a20fe3ab..f8796948 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -9,6 +9,7 @@ import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jivesoftware.smack.XMPPException; import org.junit.After; import org.junit.Before; @@ -17,13 +18,7 @@ public class TestDeleteRemoteInstance { - private static final String TOKEN = "token"; private static final String WRONG_TOKEN = "wrong"; - - public static final String MANAGER_COMPONENT_URL = "manager.test.com"; - - public static final String USER_DEFAULT = "user"; - public static final String INSTANCE_DEFAULT = "instance"; public static final String INSTANCE_OTHER_USER = "otherUser"; private ManagerTestHelper managerTestHelper; @@ -41,9 +36,9 @@ public void tearDown() throws Exception { @Test public void testDeleteRemoteInstance() throws Exception { Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); - request.setInstanceId(INSTANCE_DEFAULT); - request.setMemberId(MANAGER_COMPONENT_URL); + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), TestHelperData.USER_NAME, null, null); + request.setInstanceId(TestHelperData.INSTANCE_ID); + request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); @@ -52,9 +47,9 @@ public void testDeleteRemoteInstance() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); - request.setInstanceId(INSTANCE_DEFAULT); - request.setMemberId(MANAGER_COMPONENT_URL); + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), TestHelperData.USER_NAME, null, null); + request.setInstanceId(TestHelperData.INSTANCE_ID); + request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -68,15 +63,15 @@ public void testDeleteRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstanceUnauthorized() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), TestHelperData.USER_NAME, null, null); request.setInstanceId(INSTANCE_OTHER_USER); - request.setMemberId(MANAGER_COMPONENT_URL); + request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) - .removeInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_OTHER_USER)); + .removeInstance(Mockito.eq(TestHelperData.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 7f60e37d..77eef4ee 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -16,6 +16,7 @@ import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jivesoftware.smack.XMPPException; import org.junit.After; import org.junit.Assert; @@ -25,16 +26,9 @@ public class TestGetRemoteInstance { - private static final String TOKEN = "token"; private static final String WRONG_TOKEN = "wrong"; + private static final String INSTANCE_OTHER_USER = "otherUser"; - public static final String MANAGER_COMPONENT_URL = "manager.test.com"; - public static final String MANAGER_COMPONENT_PASS = "password"; - - public static final String USER_DEFAULT = "user"; - public static final String INSTANCE_DEFAULT = "instance"; - public static final String INSTANCE_OTHER_USER = "otherUser"; - private ManagerTestHelper managerTestHelper; @Before @@ -64,45 +58,47 @@ private Instance createInstance() { Link link = new Link("linkname", attributes); - return new Instance(INSTANCE_DEFAULT, resources, attributes, link); + return new Instance(TestHelperData.INSTANCE_ID, resources, attributes, link); } @Test public void testGetRemoteInstance() throws Exception { managerTestHelper.initializeXMPPManagerComponent(false); Instance instance = createInstance(); - - Mockito.when(managerTestHelper.getComputePlugin() - .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_DEFAULT))) - .thenReturn(instance); - - Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); - request.setInstanceId(INSTANCE_DEFAULT); - request.setMemberId(MANAGER_COMPONENT_URL); - + + Mockito.when( + managerTestHelper.getComputePlugin().getInstance( + Mockito.eq(TestHelperData.ACCESS_TOKEN_ID), + Mockito.eq(TestHelperData.INSTANCE_ID))).thenReturn(instance); + + Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), + TestHelperData.USER_NAME, null, null); + request.setInstanceId(TestHelperData.INSTANCE_ID); + request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + Instance remoteInstance = null; try { - remoteInstance = ManagerPacketHelper.getRemoteInstance(request, - managerTestHelper.createPacketSender()); + remoteInstance = ManagerPacketHelper.getRemoteInstance(request, + managerTestHelper.createPacketSender()); } catch (Exception e) { e.printStackTrace(); } Assert.assertEquals(instance.getId(), remoteInstance.getId()); Assert.assertEquals(instance.getAttributes(), remoteInstance.getAttributes()); - Assert.assertEquals(instance.getResources().get(0).toHeader(), - remoteInstance.getResources().get(0).toHeader()); - Assert.assertEquals(instance.getLink().getName(), - remoteInstance.getLink().getName()); + Assert.assertEquals(instance.getResources().get(0).toHeader(), remoteInstance + .getResources().get(0).toHeader()); + Assert.assertEquals(instance.getLink().getName(), remoteInstance.getLink().getName()); } - + @Test public void testGetRemoteInstaceNotFound() throws Exception { - Request request = new Request("anyvalue", new Token( WRONG_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); - request.setInstanceId(INSTANCE_DEFAULT); - request.setMemberId(MANAGER_COMPONENT_URL); + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), + TestHelperData.USER_NAME, null, null); + request.setInstanceId(TestHelperData.INSTANCE_ID); + request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -114,20 +110,21 @@ public void testGetRemoteInstaceNotFound() throws Exception { managerTestHelper.createPacketSender())); } - @Test(expected=OCCIException.class) + @Test(expected = OCCIException.class) public void testGetRemoteInstanceUnauthorized() throws Exception { - Request request = new Request("anyvalue", new Token( WRONG_TOKEN, OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, null, null); + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), + TestHelperData.USER_NAME, null, null); request.setInstanceId(INSTANCE_OTHER_USER); - request.setMemberId(MANAGER_COMPONENT_URL); + request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) - .getInstance(Mockito.eq(TOKEN), Mockito.eq(INSTANCE_OTHER_USER)); + .getInstance(Mockito.eq(TestHelperData.ACCESS_TOKEN_ID), + Mockito.eq(INSTANCE_OTHER_USER)); - ManagerPacketHelper.getRemoteInstance(request, - managerTestHelper.createPacketSender()); - } + ManagerPacketHelper.getRemoteInstance(request, managerTestHelper.createPacketSender()); + } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 3cf76c66..90677603 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -12,6 +12,7 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; @@ -62,7 +63,7 @@ public boolean accept(Packet packet) { return false; } return packet.getFrom().toBareJID() - .equals(ManagerTestHelper.MANAGER_COMPONENT_URL); + .equals(TestHelperData.MANAGER_COMPONENT_URL); } }, callback); @@ -142,7 +143,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - ManagerTestHelper.IAMALIVE_NAMESPACE); + TestHelperData.IAMALIVE_NAMESPACE); } }, callbackIAmAlive); @@ -154,7 +155,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - ManagerTestHelper.WHOISALIVE_NAMESPACE); + TestHelperData.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index 0e8f236b..70ec10e9 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -13,6 +13,7 @@ import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jivesoftware.smack.XMPPException; import org.junit.After; import org.junit.Assert; @@ -64,7 +65,7 @@ private Request createRequest() { attributes.put("key1", "value1"); attributes.put("key2", "value2"); Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - OCCITestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, categories, attributes); + TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, categories, attributes); request.setInstanceId(INSTANCE_DEFAULT); return request; } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java index 6a76f2c2..78c968ec 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java @@ -12,6 +12,7 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; @@ -79,7 +80,7 @@ public boolean accept(Packet packet) { return false; } return packet.getFrom().toBareJID() - .equals(ManagerTestHelper.MANAGER_COMPONENT_URL); + .equals(TestHelperData.MANAGER_COMPONENT_URL); } }, callback); managerXmppComponent.whoIsalive(); @@ -87,7 +88,7 @@ public boolean accept(Packet packet) { Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); Element element = packet.getElement().element("query"); Assert.assertEquals(element.getNamespaceURI(), - ManagerTestHelper.WHOISALIVE_NAMESPACE); + TestHelperData.WHOISALIVE_NAMESPACE); Assert.assertEquals(1, managerXmppComponent.getManagerFacade() .getMembers().size()); @@ -140,7 +141,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - ManagerTestHelper.WHOISALIVE_NAMESPACE); + TestHelperData.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java index 2ad066bc..bb5f40db 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java @@ -5,7 +5,6 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; @@ -26,7 +25,6 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; -import org.fogbowcloud.manager.occi.util.OCCITestHelper; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; import org.jamppa.client.plugin.xep0077.XEP0077; @@ -35,31 +33,12 @@ import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.filter.PacketIDFilter; -import org.mockito.Mock; import org.mockito.Mockito; import org.xmpp.component.ComponentException; import org.xmpp.packet.IQ; import org.xmpp.packet.Packet; -public class ManagerTestHelper { - - private static final int SERVER_CLIENT_PORT = 5222; - private static final int SERVER_COMPONENT_PORT = 5347; - private static final String SERVER_HOST = "localhost"; - private static final String CLIENT_ADRESS = "client@test.com"; - private static final String CLIENT_PASS = "password"; - private static final String SMACK_ENDING = "/Smack"; - - public static final String MANAGER_COMPONENT_URL = "manager.test.com"; - public static final String MANAGER_COMPONENT_PASS = "password"; - - public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; - public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; - - public static final int TEST_DEFAULT_TIMEOUT = 10000; - public static final int TIMEOUT_GRACE = 500; - - public final static String CONFIG_PATH = "src/test/resources/manager.conf.test"; +public class ManagerTestHelper extends TestHelperData { private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; @@ -69,8 +48,7 @@ public class ManagerTestHelper { public ManagerTestHelper() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); - this.tokenDefault = new Token("token", "user", new Date(System.currentTimeMillis() - + OCCITestHelper.LONG_TIME), tokenAttributes); + this.tokenDefault = new Token(ACCESS_TOKEN_ID, USER_NAME, TOKEN_FUTURE_EXPIRATION, tokenAttributes); } public ResourcesInfo getResources() throws CertificateException, IOException { diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java b/src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java new file mode 100644 index 00000000..cec5b02b --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java @@ -0,0 +1,31 @@ +package org.fogbowcloud.manager.xmpp.util; + +import java.util.Date; + +public class TestHelperData { + + protected static final int SERVER_CLIENT_PORT = 5222; + protected static final int SERVER_COMPONENT_PORT = 5347; + protected static final String SERVER_HOST = "localhost"; + protected static final String CLIENT_ADRESS = "client@test.com"; + protected static final String CLIENT_PASS = "password"; + protected static final String SMACK_ENDING = "/Smack"; + public static final String MANAGER_COMPONENT_URL = "manager.test.com"; + public static final String MANAGER_COMPONENT_PASS = "password"; + public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; + public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; + public static final int TEST_DEFAULT_TIMEOUT = 10000; + public static final int TIMEOUT_GRACE = 500; + public static final String CONFIG_PATH = "src/test/resources/manager.conf.test"; + + public static final Long SCHEDULER_PERIOD = 500L; + public static final String USER_NAME = "user"; + public static final String USER_PASS = "password"; + public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; + public static final Long GRACE_TIME = 30L; + public static final String TENANT_NAME = "tenantName"; + public static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; + public static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + public static final Date TOKEN_FUTURE_EXPIRATION = new Date(System.currentTimeMillis() + LONG_TIME); + +} \ No newline at end of file From 325fe8d9c4a9dfbe78340d5a2e6faf120f1a424f Mon Sep 17 00:00:00 2001 From: fgan1 Date: Wed, 21 May 2014 12:52:22 -0300 Subject: [PATCH 150/185] Refatoring TestInstance. --- .../manager/occi/core/TestInstance.java | 115 ++++++++++-------- 1 file changed, 64 insertions(+), 51 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java index c97c3f13..0c3bb548 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/TestInstance.java @@ -1,11 +1,42 @@ package org.fogbowcloud.manager.occi.core; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.fogbowcloud.manager.occi.instance.Instance; +import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; public class TestInstance { + private List resources = new ArrayList(); + private Map attributes = new HashMap(); + private Link link; + + @Before + public void setUp() { + Category category = new Category("compute", "http://compute", "kind"); + Resource resource = new Resource(category, new ArrayList(), + new ArrayList(), "location", "title", "rel"); + List actionsAndSupportedAttributes = new ArrayList(); + actionsAndSupportedAttributes.add("value1"); + actionsAndSupportedAttributes.add("value2"); + Resource resource2 = new Resource(category, new ArrayList(), + new ArrayList(), "location", "title", "rel"); + resources.add(resource); + resources.add(resource2); + + attributes.put("org.openstack.compute.console.vnc", "N/A"); + attributes.put("occi.compute.architecture", "x86"); + attributes.put("occi.compute.speed", "0.0"); + + link = new Link("", attributes); + } + @Test public void testParseIdOneValue() { String textResponse = "X-OCCI-Location: http://localhost:8787/compute/c1490"; @@ -16,70 +47,52 @@ public void testParseIdOneValue() { @Test public void testParseDetails() { - String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infras" - + "tructure#\"; class=\"kind\"; " - + "title=\"Compute Resource\"; rel=\"http://schemas.ogf.org/occi/core#resource\"; " - + "location=\"http://localhost:8787/compute/\"; " - + "attributes=\"occi.compute.architecture occi.compute.state{immutable} " - + "occi.compute.speed occi.compute.memory occi.compute.cores occi.compute.hostname\"; " - + "actions=\"http://schemas.ogf.org/occi/infrastructure/compute/action#start http://sc" - + "hemas.ogf.org/occi/infrastructure/compute/action#stop " - + "http://schemas.ogf.org/occi/infrastructure/compute/action#restart " - + "http://schemas.ogf.org/occi/infrastructure/compute/action#suspend\"\n" - + "Link: ; rel=\"http://schemas.ogf.org/occi/infrastructure#network\"; " - + "self=\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"; " - + "category=\"http://schemas.ogf.org/occi/infrastructure#networkinterface " - + "http://schemas.ogf.org/occi/infrastructure/networkinterface#ipnetworkinterface\"; " - + "occi.networkinterface.gateway=\"10.0.0.1\"; " - + "occi.networkinterface.mac=\"fa:16:3e:5b:9d:4d\";" - + " occi.networkinterface.interface=\"et" - + "h0\"; occi.networkinterface.state=\"active\";" - + " occi.networkinterface.allocation=\"stat" - + "ic\"; occi.networkinterface.address=\"0.0.0.0\";" - + " occi.core.source=\"/compute/c14902" - + "07-6be7-4303-a41c-f8a4b1b9c25d\"; occi.core.target=\"/network/admin\";" - + " occi.core.id=" - + "\"/network/interface/d7fe049b-71a3-4a91-b74b-bd191a79d423\"\n" - + "X-OCCI-Attribute: org.openstack.compute.console.vnc=\"N/A\"\n" - + "X-OCCI-Attribute: occi.compute.architecture=\"x86\"\n" - + "X-OCCI-Attribute: occi.compute.state=\"inactive\"\n" - + "X-OCCI-Attribute: occi.compute.speed=\"0.0\"\n" - + "X-OCCI-Attribute: org.openstack.compute.state=\"errorz\"\n" - + "X-OCCI-Attribute: occi.compute.memory=\"0.125\"\n" - + "X-OCCI-Attribute: occi.compute.cores=\"1\"\n" - + "X-OCCI-Attribute: occi.compute.hostname=\"server-c1490207-6be7-4303-a41c-f" - + "8a4b1b9c25d\"\n" - + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; + String textResponse = getFormatedResources(); + textResponse += "\n"; + textResponse += link.toOCCIMessageFormatLink() + "\n"; + textResponse += getFormatedAttributes(); Instance instance = Instance.parseInstance("id", textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); } - + @Test public void testParseDetailsOnlyAttributes() { - String textResponse = "" - + "X-OCCI-Attribute: org.openstack.compute.console.vnc=\"N/A\"\n" - + "X-OCCI-Attribute: occi.core.id=\"c1490207-6be7-4303-a41c-f8a4b1b9c25d\""; + String textResponse = getFormatedAttributes(); Instance instance = Instance.parseInstance("id", textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); - } - + } + @Test public void testParseDetailsOnlyCategory() { - String textResponse = "Category: compute; scheme=\"http://schemas.ogf.org/occi/infras" - + "tructure#\"; class=\"kind\"; " - + "title=\"Compute Resource\"; rel=\"http://schemas.ogf.org/occi/core#resource\"; " - + "location=\"http://localhost:8787/compute/\"; " - + "attributes=\"occi.compute.architecture occi.compute.state{immutable} " - + "occi.compute.speed occi.compute.memory occi.compute.cores" - + " occi.compute.hostname\"; " - + "actions=\"http://schemas.ogf.org/occi/infrastructure/compute/action#start" - + " http://schemas.ogf.org/occi/infrastructure/compute/action#stop " - + "http://schemas.ogf.org/occi/infrastructure/compute/action#restart " - + "http://schemas.ogf.org/occi/infrastructure/compute/action#suspend\""; + String textResponse = getFormatedResources(); Instance instance = Instance.parseInstance("id", textResponse); Assert.assertEquals(textResponse, instance.toOCCIMassageFormatDetails()); } + + @Test + public void addAttributes() { + Instance instance = new Instance(""); + instance.addAttribute("key1", "value1"); + instance.addAttribute("key2", "value2"); + Assert.assertEquals(2, instance.getAttributes().size()); + } + + private String getFormatedResources() { + String textResponse = ""; + for (Resource resource : resources) { + textResponse += "Category: " + resource.toHeader() + "\n"; + } + return textResponse = textResponse.trim(); + } + + private String getFormatedAttributes() { + String textResponse = ""; + for (String key : attributes.keySet()) { + textResponse += "X-OCCI-Attribute: " + key + "=\"" + attributes.get(key) + "\"\n"; + } + return textResponse = textResponse.trim(); + } } From 9596589cc24e55ffe3c1ddf9c88a326deb8a8647 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 21 May 2014 17:18:19 -0300 Subject: [PATCH 151/185] Refactoring tests, request, DefaultDataTest --- .../manager/core/ManagerController.java | 74 +- .../{xmpp => }/core/model/DateUtils.java | 4 +- .../manager/core/model/FederationMember.java | 1 - .../fogbowcloud/manager/occi/core/Token.java | 2 +- .../manager/occi/request/Request.java | 16 +- .../core/TestCertificateOperations.java | 2 +- .../TestDefaultFederationMemberValidator.java | 2 +- .../manager/core/TestManagerController.java | 634 ++++++++---------- .../util/DefaultDataTest.java} | 21 +- .../util/ManagerTestHelper.java | 4 +- .../manager/occi/TestDeleteCompute.java | 9 +- .../manager/occi/TestGetCompute.java | 19 +- .../manager/occi/TestGetRequest.java | 4 +- .../manager/occi/TestOCCIApplication.java | 4 +- .../manager/occi/TestTokenServerResource.java | 4 +- .../occi/plugins/TestIdentityOpenStack.java | 8 +- .../manager/occi/util/PluginHelper.java | 4 +- .../xmpp/TestDeleteRemoteInstance.java | 24 +- .../manager/xmpp/TestFederationMember.java | 2 +- .../manager/xmpp/TestGetRemoteInstance.java | 31 +- .../manager/xmpp/TestIAmAlive.java | 10 +- .../xmpp/TestRequestRemoteInstance.java | 7 +- .../manager/xmpp/TestWhoIsAlive.java | 10 +- 23 files changed, 390 insertions(+), 506 deletions(-) rename src/main/java/org/fogbowcloud/manager/{xmpp => }/core/model/DateUtils.java (84%) rename src/test/java/org/fogbowcloud/manager/{xmpp/util/TestHelperData.java => core/util/DefaultDataTest.java} (83%) rename src/test/java/org/fogbowcloud/manager/{xmpp => core}/util/ManagerTestHelper.java (99%) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 03ff1eba..ed3de9ff 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -11,6 +11,7 @@ import org.apache.http.HttpStatus; import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.model.DateUtils; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -30,7 +31,6 @@ import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; import org.fogbowcloud.manager.xmpp.ManagerPacketHelper; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; import org.jamppa.component.PacketSender; public class ManagerController { @@ -108,42 +108,41 @@ public String getUser(String accessId) { return token.getUser(); } - public List getRequestsFromUser(String authToken) { - String user = getUser(authToken); + public List getRequestsFromUser(String accessId) { + String user = getUser(accessId); return requests.getByUser(user); } - public void removeAllRequests(String authToken) { - String user = getUser(authToken); + public void removeAllRequests(String accessId) { + String user = getUser(accessId); LOGGER.debug("Removing all requests of user: " + user); requests.removeByUser(user); } - public void removeRequest(String authToken, String requestId) { + public void removeRequest(String accessId, String requestId) { LOGGER.debug("Removing requestId: " + requestId); - checkRequestId(authToken, requestId); + checkRequestId(accessId, requestId); requests.remove(requestId); } - private void checkRequestId(String authToken, String requestId) { - String user = getUser(authToken); + private void checkRequestId(String accessId, String requestId) { + String user = getUser(accessId); if (requests.get(user, requestId) == null) { LOGGER.debug("User " + user + " does not have requesId " + requestId); throw new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND); } } - public List getInstances(String authToken) { - LOGGER.debug("Getting instances of token " + authToken); + public List getInstances(String accessId) { + LOGGER.debug("Getting instances of token " + accessId); List instances = new ArrayList(); - for (Request request : requests.getByUser(getUser(authToken))) { + for (Request request : requests.getByUser(getUser(accessId))) { String instanceId = request.getInstanceId(); LOGGER.debug("InstanceId " + instanceId); if (instanceId == null) { continue; } try { - instances.add(getInstance(request)); } catch (Exception e) { LOGGER.warn("Exception thown while getting instance " + instanceId + ".", e); @@ -152,8 +151,8 @@ public List getInstances(String authToken) { return instances; } - public Instance getInstance(String authToken, String instanceId) { - Request request = getRequestForInstance(authToken, instanceId); + public Instance getInstance(String accessId, String instanceId) { + Request request = getRequestForInstance(accessId, instanceId); return getInstance(request); } @@ -180,27 +179,27 @@ private Instance getRemoteInstance(Request request) { return ManagerPacketHelper.getRemoteInstance(request, packetSender); } - public void removeInstances(String authToken) { - String user = getUser(authToken); + public void removeInstances(String accessId) { + String user = getUser(accessId); LOGGER.debug("Removing instances of user: " + user); for (Request request : requests.getByUser(user)) { String instanceId = request.getInstanceId(); if (instanceId == null) { continue; } - removeInstance(authToken, instanceId, request); + removeInstance(accessId, instanceId, request); } } - public void removeInstance(String authToken, String instanceId) { - Request request = getRequestForInstance(authToken, instanceId); - removeInstance(authToken, instanceId, request); + public void removeInstance(String accessId, String instanceId) { + Request request = getRequestForInstance(accessId, instanceId); + removeInstance(accessId, instanceId, request); } - private void removeInstance(String authToken, String instanceId, Request request) { + private void removeInstance(String accessId, String instanceId, Request request) { sshTunnel.release(request); if (isLocal(request)) { - this.computePlugin.removeInstance(authToken, instanceId); + this.computePlugin.removeInstance(accessId, instanceId); } else { removeRemoteInstance(request); } @@ -236,7 +235,7 @@ public Request getRequestForInstance(String accessId, String instanceId) { List userRequests = requests.getAll(); for (Request request : userRequests) { if (instanceId.equals(request.getInstanceId())) { - if (!request.getUser().equals(user)) { + if (!request.getToken().getUser().equals(user)) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); } return request; @@ -270,13 +269,12 @@ public String createInstanceForRemoteMember(String memberId, List cate FederationMember member = getFederationMember(memberId); if (!validator.canDonateTo(member)) { return null; - } - + } LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); - String token = getFederationUserToken().getAccessId(); + String federationTokenAccessId = getFederationUserToken().getAccessId(); try { - return computePlugin.requestInstance(token, categories, xOCCIAtt); + return computePlugin.requestInstance(federationTokenAccessId, categories, xOCCIAtt); } catch (OCCIException e) { if (e.getStatus().getCode() == HttpStatus.SC_BAD_REQUEST) { return null; @@ -299,16 +297,15 @@ protected Token getFederationUserToken() { federationUserCredentials.put(OCCIHeaders.X_TOKEN_PASS, password); federationUserCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - Token token = identityPlugin.createToken(federationUserCredentials); - this.federationUserToken = token; + this.federationUserToken = identityPlugin.createToken(federationUserCredentials); return federationUserToken; } public Instance getInstanceForRemoteMember(String instanceId) { LOGGER.info("Getting instance " + instanceId + " for remote member."); - String token = getFederationUserToken().getAccessId(); + String federationTokenAccessId = getFederationUserToken().getAccessId(); try { - return computePlugin.getInstance(token, instanceId); + return computePlugin.getInstance(federationTokenAccessId, instanceId); } catch (OCCIException e) { LOGGER.warn("Exception while getting instance " + instanceId + " for remote member.", e); if (e.getStatus().getCode() == HttpStatus.SC_NOT_FOUND) { @@ -320,15 +317,14 @@ public Instance getInstanceForRemoteMember(String instanceId) { public void removeInstanceForRemoteMember(String instanceId) { LOGGER.info("Removing instance " + instanceId + " for remote member."); - String token = getFederationUserToken().getAccessId(); - computePlugin.removeInstance(token, instanceId); + String federationTokenAccessId = getFederationUserToken().getAccessId(); + computePlugin.removeInstance(federationTokenAccessId, instanceId); } - public List createRequests(String authToken, List categories, + public List createRequests(String accessId, List categories, Map xOCCIAtt) { - String user = getUser(authToken); - Token userToken = identityPlugin.getToken(authToken); + Token userToken = identityPlugin.getToken(accessId); LOGGER.debug("User Token: " + userToken); Integer instanceCount = Integer.valueOf(xOCCIAtt.get(RequestAttribute.INSTANCE_COUNT @@ -338,7 +334,7 @@ public List createRequests(String authToken, List categories, List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, userToken, user, categories, xOCCIAtt); + Request request = new Request(requestId, userToken, categories, xOCCIAtt); try { sshTunnel.create(properties, request); } catch (Exception e) { @@ -347,7 +343,7 @@ public List createRequests(String authToken, List categories, } LOGGER.info("Created request: " + request); currentRequests.add(request); - requests.addRequest(user, request); + requests.addRequest(userToken.getUser(), request); } if (!requestSchedulerTimer.isScheduled()) { scheduleRequests(); diff --git a/src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java b/src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java similarity index 84% rename from src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java rename to src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java index 4d583477..ce85cb88 100644 --- a/src/main/java/org/fogbowcloud/manager/xmpp/core/model/DateUtils.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java @@ -1,12 +1,10 @@ -package org.fogbowcloud.manager.xmpp.core.model; +package org.fogbowcloud.manager.core.model; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; -import org.fogbowcloud.manager.core.model.FederationMember; - public class DateUtils { public DateUtils() { diff --git a/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java b/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java index 74099e9b..da39a14c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/FederationMember.java @@ -1,6 +1,5 @@ package org.fogbowcloud.manager.core.model; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class FederationMember { diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index 09b9c223..df338537 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -3,7 +3,7 @@ import java.util.Date; import java.util.Map; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; +import org.fogbowcloud.manager.core.model.DateUtils; public class Token { diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index ba09b333..2b253fe7 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -8,10 +8,10 @@ import java.util.Map; import java.util.TimeZone; +import org.fogbowcloud.manager.core.model.DateUtils; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.Token; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; public class Request { @@ -22,13 +22,11 @@ public class Request { private RequestState state; private List categories; private Map xOCCIAtt; - private String user; - public Request(String id, Token token, String user, List categories, + public Request(String id, Token token, List categories, Map xOCCIAtt) { this.id = id; this.token = token; - this.user = user; this.categories = categories; this.xOCCIAtt = xOCCIAtt; setState(RequestState.OPEN); @@ -45,10 +43,6 @@ public void addCategory(Category category) { categories.add(category); } - public String getUser() { - return user; - } - public String getInstanceId() { return instanceId; } @@ -108,9 +102,9 @@ public void setMemberId(String memberId) { } public String toString() { - return "id: " + id + ", token: " + token + ", user: " + user + ", instanceId: " - + instanceId + ", memberId: " + memberId + ", state: " + state + ", categories: " - + categories + ", xOCCIAtt: " + xOCCIAtt; + return "id: " + id + ", token: " + token + ", instanceId: " + instanceId + ", memberId: " + + memberId + ", state: " + state + ", categories: " + categories + ", xOCCIAtt: " + + xOCCIAtt; } public boolean isIntoValidPeriod() { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java index 20aec005..3562d06d 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestCertificateOperations.java @@ -4,7 +4,7 @@ import java.security.cert.Certificate; import java.security.cert.CertificateException; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Test; diff --git a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java index 79fc6e7f..7c2406dc 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestDefaultFederationMemberValidator.java @@ -17,7 +17,7 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index c8e16a92..fa3abe8f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -10,6 +10,7 @@ import java.util.Map; import java.util.Properties; +import org.fogbowcloud.manager.core.model.DateUtils; import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; @@ -17,6 +18,8 @@ import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; +import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -30,9 +33,6 @@ import org.fogbowcloud.manager.occi.request.RequestRepository; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.request.RequestType; -import org.fogbowcloud.manager.xmpp.core.model.DateUtils; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -47,29 +47,32 @@ public class TestManagerController { private ManagerController managerController; private ManagerTestHelper managerTestHelper; private Map xOCCIAtt; - + private IdentityPlugin identityPlugin; + private ComputePlugin computePlugin; + @Before - public void setUp() throws Exception { + public void setUp() throws Exception { managerTestHelper = new ManagerTestHelper(); - + // default instance count value is 1 xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - + HashMap tokenAttr = new HashMap(); - userToken = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, - TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttr); - + userToken = new Token(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.USER_NAME, + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttr); + Properties properties = new Properties(); - properties.put("federation_user_name", TestHelperData.USER_NAME); - properties.put("federation_user_password", TestHelperData.USER_PASS); - properties.put("federation_user_tenant_name", TestHelperData.TENANT_NAME); - properties.put("scheduler_period", TestHelperData.SCHEDULER_PERIOD.toString()); + properties.put("federation_user_name", DefaultDataTest.USER_NAME); + properties.put("federation_user_password", DefaultDataTest.USER_PASS); + properties.put("federation_user_tenant_name", DefaultDataTest.TENANT_NAME); + properties.put("scheduler_period", DefaultDataTest.SCHEDULER_PERIOD.toString()); + properties.put("instance_monitoring_period", Long.toString(DefaultDataTest.LONG_TIME)); managerController = new ManagerController(properties); // mocking compute - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( @@ -77,8 +80,8 @@ public void setUp() throws Exception { ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(userToken); + identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getToken(DefaultDataTest.ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -93,39 +96,39 @@ public void testGetFederationMember() throws InterruptedException { OpenStackIdentityPlugin openStackidentityPlugin = Mockito .mock(OpenStackIdentityPlugin.class); Map tokenCredentials = new HashMap(); - tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, TestHelperData.USER_NAME); - tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, TestHelperData.USER_PASS); - tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TestHelperData.TENANT_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, DefaultDataTest.USER_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, DefaultDataTest.USER_PASS); + tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTest.TENANT_NAME); long tokenExpirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TestHelperData.TENANT_NAME); - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, new Date( + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTest.TENANT_NAME); + Token token = new Token(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.USER_NAME, new Date( tokenExpirationTime), attributesTokenReturn); - Token token2 = new Token(ACCESS_TOKEN_ID_2, TestHelperData.USER_NAME, new Date( - tokenExpirationTime + TestHelperData.LONG_TIME), attributesTokenReturn); + Token token2 = new Token(ACCESS_TOKEN_ID_2, DefaultDataTest.USER_NAME, new Date( + tokenExpirationTime + DefaultDataTest.LONG_TIME), attributesTokenReturn); Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, token2); - Mockito.when(openStackidentityPlugin.isValid(TestHelperData.ACCESS_TOKEN_ID)).thenReturn( + Mockito.when(openStackidentityPlugin.isValid(DefaultDataTest.ACCESS_TOKEN_ID)).thenReturn( true, false); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token Token federationUserToken = managerController.getFederationUserToken(); String accessToken = federationUserToken.getAccessId(); - Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, accessToken); + Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, accessToken); // Use member token accessToken = managerController.getFederationUserToken().getAccessId(); - Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, accessToken); + Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); Mockito.when(dateUtils.currentTimeMillis()).thenReturn( - tokenExpirationTime + TestHelperData.GRACE_TIME); + tokenExpirationTime + DefaultDataTest.GRACE_TIME); token.setDateUtils(dateUtils); // Get new token @@ -135,280 +138,219 @@ public void testGetFederationMember() throws InterruptedException { @Test public void testcheckAndUpdateRequestToken() throws InterruptedException { - final int tokenUpdaterInterval = 100; final long now = System.currentTimeMillis(); + final int tokenUpdaterInterval = 100; long tokenExpirationTime = now + (4 * tokenUpdaterInterval); - Properties properties = new Properties(); - properties.put("token_update_period", Integer.toString(tokenUpdaterInterval)); - managerController = new ManagerController(properties); - DateUtils dateUtils = Mockito.mock(DateUtils.class); - - RequestRepository requestRepository = new RequestRepository(); - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, new Date( + Token token = new Token(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.USER_NAME, new Date( tokenExpirationTime), new HashMap()); - + RequestRepository requestRepository = new RequestRepository(); for (int i = 0; i < 5; i++) { - requestRepository.addRequest(TestHelperData.USER_NAME, new Request("id" + i, token, - TestHelperData.USER_NAME, null, null)); + requestRepository.addRequest(DefaultDataTest.USER_NAME, new Request("id" + i, token, + null, null)); } managerController.setRequests(requestRepository); - // mocking identity - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); - Token tokenUpdatedFirstTime = new Token(ACCESS_TOKEN_ID_2, TestHelperData.USER_NAME, - new Date(tokenExpirationTime + tokenUpdaterInterval), new HashMap()); - Mockito.when(identityPlugin.createToken(token)).thenReturn(tokenUpdatedFirstTime); - managerController.setIdentityPlugin(identityPlugin); + // adding behaviour on identity mock + Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTest.USER_NAME, new Date( + tokenExpirationTime + tokenUpdaterInterval), new HashMap()); + Mockito.when(identityPlugin.createToken(token)).thenReturn(secondToken); + // mocking date + DateUtils dateUtils = Mockito.mock(DateUtils.class); Mockito.when(dateUtils.currentTimeMillis()).thenReturn(now); managerController.setDateUtils(dateUtils); managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); + List requestsFromUser = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { - Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, request.getToken() + Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, request.getToken() .getAccessId()); } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { - Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, request.getToken() + Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, request.getToken() .getAccessId()); } } + // updating date Mockito.when(dateUtils.currentTimeMillis()).thenReturn( tokenExpirationTime - tokenUpdaterInterval); - managerController.setDateUtils(dateUtils); managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { Assert.assertEquals(ACCESS_TOKEN_ID_2, request.getToken().getAccessId()); } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { - Assert.assertEquals(TestHelperData.ACCESS_TOKEN_ID, request.getToken() + Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, request.getToken() .getAccessId()); } } } @Test - public void testMonitoringDeletedRequestAndFoundInstance() throws InterruptedException { - Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); - managerController = new ManagerController(properties); - - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, - new Date(), new HashMap()); - Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); + public void testMonitorDeletedRequestWithInstance() throws InterruptedException { + Request request1 = new Request("id1", userToken, null, null); + request1.setInstanceId(DefaultDataTest.INSTANCE_ID); request1.setState(RequestState.DELETED); - Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); + Request request2 = new Request("id2", userToken, null, null); + request2.setInstanceId(DefaultDataTest.INSTANCE_ID); request2.setState(RequestState.DELETED); + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(TestHelperData.USER_NAME, request1); - requestRepository.addRequest(TestHelperData.USER_NAME, request2); + requestRepository.addRequest(userToken.getUser(), request1); + requestRepository.addRequest(userToken.getUser(), request2); managerController.setRequests(requestRepository); - RequestRepository requestRepositoryCopy = new RequestRepository(); - requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request1); - requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request2); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - managerController.setIdentityPlugin(identityPlugin); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); + // updating compute mock Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(TestHelperData.INSTANCE_ID)); + .thenReturn(new Instance(DefaultDataTest.INSTANCE_ID)); - Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); + List requestsFromUser = managerController.getRequestsFromUser(userToken + .getAccessId()); + Assert.assertEquals(2, requestsFromUser.size()); + Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(0).getState()); + Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(1).getState()); managerController.monitorInstances(); - Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); - } - private List getRequestsDeleted(RequestRepository requestRepository) { - List requests = new ArrayList(); - for (Request request : requestRepository.get(RequestState.DELETED)) { - try { - requests.add(managerController.getRequest(TestHelperData.ACCESS_TOKEN_ID, - request.getId())); - } catch (Exception e) { - } - } - return requests; + requestsFromUser = managerController.getRequestsFromUser(userToken.getAccessId()); + Assert.assertEquals(2, requestsFromUser.size()); + Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(0).getState()); + Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(1).getState()); } @Test - public void testMonitoringDeletedRequestAndNotFoundInstance() throws InterruptedException { - Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); - managerController = new ManagerController(properties); - - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, - new Date(), new HashMap()); - Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); + public void testMonitorDeletedRequestWithoutInstance() throws InterruptedException { + Request request1 = new Request("id1", userToken, null, null); request1.setState(RequestState.DELETED); - Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); + Request request2 = new Request("id2", userToken, null, null); request2.setState(RequestState.DELETED); - Request request3 = new Request("id3", token, TestHelperData.USER_NAME, null, null); + Request request3 = new Request("id3", userToken, null, null); request3.setState(RequestState.OPEN); + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(TestHelperData.USER_NAME, request1); - requestRepository.addRequest(TestHelperData.USER_NAME, request2); - requestRepository.addRequest(TestHelperData.USER_NAME, request3); + requestRepository.addRequest(userToken.getUser(), request1); + requestRepository.addRequest(userToken.getUser(), request2); + requestRepository.addRequest(userToken.getUser(), request3); managerController.setRequests(requestRepository); - RequestRepository requestRepositoryCopy = new RequestRepository(); - requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request1); - requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request2); - requestRepositoryCopy.addRequest(TestHelperData.USER_NAME, request3); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - managerController.setIdentityPlugin(identityPlugin); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); + //updating compute mock Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - Assert.assertEquals(2, getRequestsDeleted(requestRepositoryCopy).size()); + Assert.assertEquals(3, managerController.getRequestsFromUser(userToken.getAccessId()).size()); + Assert.assertEquals(RequestState.DELETED, + managerController.getRequest(userToken.getAccessId(), "id1").getState()); + Assert.assertEquals(RequestState.DELETED, + managerController.getRequest(userToken.getAccessId(), "id2").getState()); + Assert.assertEquals(RequestState.OPEN, + managerController.getRequest(userToken.getAccessId(), "id3").getState()); managerController.monitorInstances(); - Assert.assertEquals(0, getRequestsDeleted(requestRepositoryCopy).size()); + + Assert.assertEquals(1, managerController.getRequestsFromUser(userToken.getAccessId()).size()); + Assert.assertEquals(RequestState.OPEN, + managerController.getRequestsFromUser(userToken.getAccessId()).get(0).getState()); } @Test - public void testMonitoringFulfilledRequestAndNotFoundInstance() throws InterruptedException { - Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); - managerController = new ManagerController(properties); - - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, - new Date(), new HashMap()); - Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); + public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedException { + Request request1 = new Request("id1", userToken, null, null); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); + Request request2 = new Request("id2", userToken, null, null); request2.setState(RequestState.FULFILLED); + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(TestHelperData.USER_NAME, request1); - requestRepository.addRequest(TestHelperData.USER_NAME, request2); + requestRepository.addRequest(userToken.getUser(), request1); + requestRepository.addRequest(userToken.getUser(), request2); managerController.setRequests(requestRepository); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - managerController.setIdentityPlugin(identityPlugin); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); - - managerController.monitorInstances(); - List requestsFromUser = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + //updating compute mock + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + + List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - + managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); } } - @SuppressWarnings("unchecked") @Test - public void testMonitoringFulfilledRequestAndPesistentInstance() throws InterruptedException { - final int timeDefault = 5 * 60 * 1000; // Big time to not interfere this - // test - Properties properties = new Properties(); - properties.put("instance_monitoring_period", Integer.toString(timeDefault)); - properties.put("scheduler_period", 100 * TestHelperData.SCHEDULER_PERIOD); - - managerController = new ManagerController(properties); - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()); - Map map = new HashMap(); - map.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, map); + public void testMonitorFulfilledAndPersistentRequest() throws InterruptedException { + Map attributes = new HashMap(); + attributes.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); + Request request1 = new Request("id1", userToken, null, attributes); request1.setState(RequestState.FULFILLED); + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(TestHelperData.USER_NAME, request1); + requestRepository.addRequest(userToken.getUser(), request1); managerController.setRequests(requestRepository); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.anyList(), - Mockito.anyMap())).thenReturn(TestHelperData.INSTANCE_ID); - + mockRequestInstance(); + + //updating compute mock Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - - List requestsFromUser = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); - for (Request request : requestsFromUser) { - Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); - } + List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(1, requestsFromUser.size()); + Assert.assertEquals(RequestState.FULFILLED, requestsFromUser.get(0).getState()); managerController.monitorInstances(); - for (Request request : requestsFromUser) { - requestsFromUser = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); - Assert.assertTrue(request.getState().in(RequestState.OPEN)); - } + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(1, requestsFromUser.size()); + Assert.assertEquals(RequestState.OPEN, requestsFromUser.get(0).getState()); managerController.checkAndSubmitOpenRequests(); - requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); - for (Request request : requestsFromUser) { - Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); - } + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(1, requestsFromUser.size()); + Assert.assertEquals(RequestState.FULFILLED, requestsFromUser.get(0).getState()); } @Test - public void testMonitoringFulfilledRequestAndOnetimeInstance() throws InterruptedException { - Properties properties = new Properties(); - properties.put("instance_monitoring_period", Long.toString(TestHelperData.LONG_TIME)); - managerController = new ManagerController(properties); - - Token token = new Token(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.USER_NAME, - new Date(), new HashMap()); - Request request1 = new Request("id1", token, TestHelperData.USER_NAME, null, null); + public void testMonitorFulfilledRequestWithInstance() throws InterruptedException { + Request request1 = new Request("id1", userToken, null, null); + request1.setInstanceId(DefaultDataTest.INSTANCE_ID); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", token, TestHelperData.USER_NAME, null, null); + Request request2 = new Request("id2", userToken, null, null); + request2.setInstanceId(SECOND_INSTANCE_ID); request2.setState(RequestState.FULFILLED); + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(TestHelperData.USER_NAME, request1); - requestRepository.addRequest(TestHelperData.USER_NAME, request2); + requestRepository.addRequest(userToken.getUser(), request1); + requestRepository.addRequest(userToken.getUser(), request2); managerController.setRequests(requestRepository); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - managerController.setIdentityPlugin(identityPlugin); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - managerController.setComputePlugin(computePlugin); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(token); - - managerController.monitorInstances(); - List requestsFromUser = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + //updating compute mock + Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) + .thenReturn(new Instance(DefaultDataTest.INSTANCE_ID)); + + managerController.monitorInstances(); + List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { - Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); + Assert.assertEquals(RequestState.FULFILLED, request.getState()); } - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(TestHelperData.INSTANCE_ID)); - managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } @@ -454,49 +396,44 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { Assert.assertEquals(10, managerController.getMembers().size()); } - @SuppressWarnings("unchecked") @Test public void testGetRequestsByUser() throws InterruptedException { - mockOKRequestCompute(); + mockRequestInstance(); - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(TestHelperData.USER_NAME, requests.get(0).getUser()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.USER_NAME, requests.get(0).getToken().getUser()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } @Test public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { - mockOKRequestCompute(); - - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + mockRequestInstance(); + + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); -// Thread.sleep(TestHelperData.SCHEDULER_PERIOD); managerController.checkAndSubmitOpenRequests(); - List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController - .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); + managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); @@ -504,55 +441,31 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio Assert.assertNull(requests.get(0).getMemberId()); } - @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", TestHelperData.SCHEDULER_PERIOD.toString()); - managerController = new ManagerController(properties); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))) - .thenReturn(TestHelperData.INSTANCE_ID) - .thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + mockRequestInstance(); - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(userToken); - - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); - - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); -// Thread.sleep(TestHelperData.SCHEDULER_PERIOD); managerController.checkAndSubmitOpenRequests(); - List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController - .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); + managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -565,49 +478,36 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { - Properties properties = new Properties(); - properties.put("scheduler_period", Long.toString(TestHelperData.SCHEDULER_PERIOD)); - managerController = new ManagerController(properties); - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + //mocking compute for 2 instances + computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(TestHelperData.INSTANCE_ID, + Mockito.any(Map.class))).thenReturn(DefaultDataTest.INSTANCE_ID, SECOND_INSTANCE_ID); - - IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(TestHelperData.ACCESS_TOKEN_ID)).thenReturn(userToken); - - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); - - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD); -// managerController.checkAndSubmitOpenRequests(); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController - .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); + managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -617,10 +517,9 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getMemberId()); // getting second instance - Thread.sleep(TestHelperData.SCHEDULER_PERIOD * 2); -// managerController.checkAndSubmitOpenRequests(); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD * 2); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); @@ -632,7 +531,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr @Test public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + TestHelperData.SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + DefaultDataTest.SCHEDULER_PERIOD; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); @@ -640,11 +539,11 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException String.valueOf(DateUtils.getDateISO8601Format(expirationRequestTime))); // creating request - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -653,9 +552,9 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -667,40 +566,38 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException @Test public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + TestHelperData.SCHEDULER_PERIOD - + TestHelperData.GRACE_TIME; + long expirationRequestTime = System.currentTimeMillis() + DefaultDataTest.SCHEDULER_PERIOD + + DefaultDataTest.GRACE_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); - mockOKRequestCompute(); + mockRequestInstance(); - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD); - List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD); // removing instance - managerController - .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); + managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -710,28 +607,27 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep Assert.assertNull(requests.get(0).getMemberId()); } - private void mockOKRequestCompute() { - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + private void mockRequestInstance() { + computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(TestHelperData.INSTANCE_ID); + Mockito.any(Map.class))).thenReturn(DefaultDataTest.INSTANCE_ID); managerController.setComputePlugin(computePlugin); } @Test public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + TestHelperData.SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + DefaultDataTest.SCHEDULER_PERIOD; - xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestConstants.DEFAULT_TYPE); + xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); // creating request - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -740,9 +636,9 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -750,29 +646,29 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - } @Test - public void testOneTimeRequestValidFromInFuture() throws InterruptedException { + public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + TestHelperData.LONG_TIME; + long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + DefaultDataTest.LONG_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.ONE_TIME.getValue())); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); - mockOKRequestCompute(); + mockRequestInstance(); // creating request - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -781,11 +677,11 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); - // request is not in validity period yet + // request is not in valid period yet Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -793,38 +689,38 @@ public void testOneTimeRequestValidFromInFuture() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - // request is in validity period - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + // request is in valid period + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } @Test - public void testPersistentRequestValidFromInFuture() throws InterruptedException { + public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + TestHelperData.LONG_TIME; + long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + DefaultDataTest.LONG_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); - mockOKRequestCompute(); + mockRequestInstance(); // creating request - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -833,11 +729,11 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); - // request is not in validity period yet + // request is not in valid period yet Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -845,44 +741,45 @@ public void testPersistentRequestValidFromInFuture() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - // request is in validity period - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + // request is in valid period + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } @Test public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 3); + long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 3); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); - mockOKRequestCompute(); - + mockRequestInstance(); + // creating request - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); - // request is not in validity period yet + // request is not in valid period yet Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -890,26 +787,25 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - // request is in validity period - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + // request is in valid period + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); // remove instance - managerController - .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); + managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - // request is not in validity period anymore - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + // request is not in valid period anymore + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -922,28 +818,29 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti @Test public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (TestHelperData.SCHEDULER_PERIOD * 3); + long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 3); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); + xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), + DateUtils.getDateISO8601Format(startRequestTime)); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); - mockOKRequestCompute(); - + mockRequestInstance(); + // creating request - managerController.createRequests(TestHelperData.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); - // request is not in validity period yet + // request is not in valid period yet Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -951,28 +848,27 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - // request is in validity period - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + // request is in valid period + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(TestHelperData.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); // remove instance - managerController - .removeInstance(TestHelperData.ACCESS_TOKEN_ID, TestHelperData.INSTANCE_ID); + managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); - Thread.sleep(TestHelperData.SCHEDULER_PERIOD + TestHelperData.GRACE_TIME); + Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); - // request is not in validity period anymore - requests = managerController.getRequestsFromUser(TestHelperData.ACCESS_TOKEN_ID); + // request is not in valid period anymore + requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTest.java similarity index 83% rename from src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java rename to src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTest.java index cec5b02b..4c01f915 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/TestHelperData.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTest.java @@ -1,9 +1,10 @@ -package org.fogbowcloud.manager.xmpp.util; +package org.fogbowcloud.manager.core.util; import java.util.Date; -public class TestHelperData { +public class DefaultDataTest { + //xmpp data protected static final int SERVER_CLIENT_PORT = 5222; protected static final int SERVER_COMPONENT_PORT = 5347; protected static final String SERVER_HOST = "localhost"; @@ -14,18 +15,22 @@ public class TestHelperData { public static final String MANAGER_COMPONENT_PASS = "password"; public static final String WHOISALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/whoisalive"; public static final String IAMALIVE_NAMESPACE = "http://fogbowcloud.org/rendezvous/iamalive"; - public static final int TEST_DEFAULT_TIMEOUT = 10000; - public static final int TIMEOUT_GRACE = 500; + + //manager controller data public static final String CONFIG_PATH = "src/test/resources/manager.conf.test"; + //time data + public static final int TEST_DEFAULT_TIMEOUT = 10000; + public static final int TIMEOUT_GRACE = 500; public static final Long SCHEDULER_PERIOD = 500L; + public static final Long GRACE_TIME = 30L; + public static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; //one day + public static final Date TOKEN_FUTURE_EXPIRATION = new Date(System.currentTimeMillis() + LONG_TIME); + + //test default values public static final String USER_NAME = "user"; public static final String USER_PASS = "password"; public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; - public static final Long GRACE_TIME = 30L; public static final String TENANT_NAME = "tenantName"; - public static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; public static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; - public static final Date TOKEN_FUTURE_EXPIRATION = new Date(System.currentTimeMillis() + LONG_TIME); - } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java similarity index 99% rename from src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java rename to src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index bb5f40db..25024c5c 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -1,4 +1,4 @@ -package org.fogbowcloud.manager.xmpp.util; +package org.fogbowcloud.manager.core.util; import java.io.FileInputStream; import java.io.IOException; @@ -38,7 +38,7 @@ import org.xmpp.packet.IQ; import org.xmpp.packet.Packet; -public class ManagerTestHelper extends TestHelperData { +public class ManagerTestHelper extends DefaultDataTest { private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 057a9c84..2d378e99 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -13,11 +13,11 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -46,13 +46,12 @@ public void setup() throws Exception { List requests = new LinkedList(); Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, - OCCITestHelper.USER_MOCK, TestHelperData.TOKEN_FUTURE_EXPIRATION, - new HashMap()), OCCITestHelper.USER_MOCK, null, null); + OCCITestHelper.USER_MOCK, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + new HashMap()), null, null); request1.setInstanceId(INSTANCE_ID); requests.add(request1); Request request2 = new Request("2", new Token("otherToken", "otherUser", - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), - "otherUser", null, null); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request2.setInstanceId(OTHER_INSTANCE_ID); requests.add(request2); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index 90f66272..c6dd33ea 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -14,6 +14,7 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Resource; import org.fogbowcloud.manager.occi.core.Token; @@ -21,7 +22,6 @@ import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -61,19 +61,18 @@ public void setup() throws Exception { new HashMap())); List requests = new LinkedList(); - Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), - OCCITestHelper.USER_MOCK, null, null); + Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.USER_MOCK, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + new HashMap()), null, null); request1.setInstanceId(INSTANCE_1_ID); requests.add(request1); - Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), - OCCITestHelper.USER_MOCK, null, null); + Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, + OCCITestHelper.USER_MOCK, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + new HashMap()), null, null); request2.setInstanceId(INSTANCE_2_ID); requests.add(request2); - Request request3 = new Request("3", new Token("token", "user", - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), "user", - null, null); + Request request3 = new Request("3", new Token("token", "user", + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request3.setInstanceId(INSTANCE_3_ID_WITHOUT_USER); requests.add(request3); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index f714768a..ff7b201e 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -19,6 +19,7 @@ import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; @@ -31,7 +32,6 @@ import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.ComputeApplication; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -64,7 +64,7 @@ public void setup() throws Exception { HashMap tokenAttr = new HashMap(); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttr); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 46af3619..205e6f24 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -10,6 +10,7 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -20,7 +21,6 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.fogbowcloud.manager.occi.request.RequestState; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -58,7 +58,7 @@ public void setUp() { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); HashMap tokenAttr = new HashMap(); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttr); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(Mockito.anyString())).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java index 68460ac0..cef734c9 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -11,12 +11,12 @@ import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -58,7 +58,7 @@ public void testGetTokenWrongContentType() throws Exception { @SuppressWarnings("unchecked") @Test public void testGetToken() throws Exception { - Token token = new Token(ACCESS_TOKEN_ID, "user", TestHelperData.TOKEN_FUTURE_EXPIRATION, + Token token = new Token(ACCESS_TOKEN_ID, "user", DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()); Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(token); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 6c1fd1f1..4c61852a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -6,11 +6,11 @@ import java.util.Properties; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.PluginHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -71,7 +71,7 @@ public void testGetToken() { Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(TestHelperData.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(DefaultDataTest.TOKEN_FUTURE_EXPIRATION, expirationDate); } @Test @@ -86,7 +86,7 @@ public void testUpgradeToken() { Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(TestHelperData.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(DefaultDataTest.TOKEN_FUTURE_EXPIRATION, expirationDate); Token token2 = this.identityOpenStack.createToken(token); authToken = token2.getAccessId(); @@ -94,7 +94,7 @@ public void testUpgradeToken() { expirationDate = token2.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(TestHelperData.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(DefaultDataTest.TOKEN_FUTURE_EXPIRATION, expirationDate); } @Test(expected = OCCIException.class) diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 0aa22972..db32669d 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -5,10 +5,10 @@ import java.util.List; import java.util.Map; +import org.fogbowcloud.manager.core.util.DefaultDataTest; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.mockito.Mockito; import org.restlet.Component; import org.restlet.data.Protocol; @@ -40,7 +40,7 @@ public void initializeKeystoneComponent() throws Exception { tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); // tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, TestHelperData.TOKEN_FUTURE_EXPIRATION, tokenAttributes); + Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttributes); // TODO Refactor! We really need all these args to KeytoneApplication? KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java index f8796948..c867e5ed 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -2,14 +2,14 @@ import java.util.HashMap; +import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jivesoftware.smack.XMPPException; import org.junit.After; import org.junit.Before; @@ -36,9 +36,9 @@ public void tearDown() throws Exception { @Test public void testDeleteRemoteInstance() throws Exception { Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), TestHelperData.USER_NAME, null, null); - request.setInstanceId(TestHelperData.INSTANCE_ID); - request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTest.INSTANCE_ID); + request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); @@ -47,9 +47,9 @@ public void testDeleteRemoteInstance() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), TestHelperData.USER_NAME, null, null); - request.setInstanceId(TestHelperData.INSTANCE_ID); - request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTest.INSTANCE_ID); + request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -62,16 +62,16 @@ public void testDeleteRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstanceUnauthorized() throws Exception { - Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), TestHelperData.USER_NAME, null, null); + Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request.setInstanceId(INSTANCE_OTHER_USER); - request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) - .removeInstance(Mockito.eq(TestHelperData.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); + .removeInstance(Mockito.eq(DefaultDataTest.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java index 8733c446..0898de75 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestFederationMember.java @@ -10,7 +10,7 @@ import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.model.Flavor; import org.fogbowcloud.manager.core.model.ResourcesInfo; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.junit.Assert; import org.junit.Before; import org.junit.Test; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 77eef4ee..910eb1b4 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -5,6 +5,8 @@ import java.util.List; import java.util.Map; +import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -15,8 +17,6 @@ import org.fogbowcloud.manager.occi.instance.Instance.Link; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jivesoftware.smack.XMPPException; import org.junit.After; import org.junit.Assert; @@ -58,7 +58,7 @@ private Instance createInstance() { Link link = new Link("linkname", attributes); - return new Instance(TestHelperData.INSTANCE_ID, resources, attributes, link); + return new Instance(DefaultDataTest.INSTANCE_ID, resources, attributes, link); } @Test @@ -68,14 +68,13 @@ public void testGetRemoteInstance() throws Exception { Mockito.when( managerTestHelper.getComputePlugin().getInstance( - Mockito.eq(TestHelperData.ACCESS_TOKEN_ID), - Mockito.eq(TestHelperData.INSTANCE_ID))).thenReturn(instance); + Mockito.eq(DefaultDataTest.ACCESS_TOKEN_ID), + Mockito.eq(DefaultDataTest.INSTANCE_ID))).thenReturn(instance); Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), - TestHelperData.USER_NAME, null, null); - request.setInstanceId(TestHelperData.INSTANCE_ID); - request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTest.INSTANCE_ID); + request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); Instance remoteInstance = null; try { @@ -95,10 +94,9 @@ public void testGetRemoteInstance() throws Exception { @Test public void testGetRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), - TestHelperData.USER_NAME, null, null); - request.setInstanceId(TestHelperData.INSTANCE_ID); - request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTest.INSTANCE_ID); + request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -113,16 +111,15 @@ public void testGetRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testGetRemoteInstanceUnauthorized() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), - TestHelperData.USER_NAME, null, null); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request.setInstanceId(INSTANCE_OTHER_USER); - request.setMemberId(TestHelperData.MANAGER_COMPONENT_URL); + request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) - .getInstance(Mockito.eq(TestHelperData.ACCESS_TOKEN_ID), + .getInstance(Mockito.eq(DefaultDataTest.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); ManagerPacketHelper.getRemoteInstance(request, managerTestHelper.createPacketSender()); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 90677603..3193af62 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -11,8 +11,8 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; +import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; @@ -63,7 +63,7 @@ public boolean accept(Packet packet) { return false; } return packet.getFrom().toBareJID() - .equals(TestHelperData.MANAGER_COMPONENT_URL); + .equals(DefaultDataTest.MANAGER_COMPONENT_URL); } }, callback); @@ -143,7 +143,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - TestHelperData.IAMALIVE_NAMESPACE); + DefaultDataTest.IAMALIVE_NAMESPACE); } }, callbackIAmAlive); @@ -155,7 +155,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - TestHelperData.WHOISALIVE_NAMESPACE); + DefaultDataTest.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index 70ec10e9..58cb27a3 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -5,6 +5,8 @@ import java.util.List; import java.util.Map; +import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -12,8 +14,6 @@ import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; import org.fogbowcloud.manager.occi.util.OCCITestHelper; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; import org.jivesoftware.smack.XMPPException; import org.junit.After; import org.junit.Assert; @@ -65,7 +65,8 @@ private Request createRequest() { attributes.put("key1", "value1"); attributes.put("key2", "value2"); Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - TestHelperData.TOKEN_FUTURE_EXPIRATION, new HashMap()), USER_DEFAULT, categories, attributes); + DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), categories, + attributes); request.setInstanceId(INSTANCE_DEFAULT); return request; } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java index 78c968ec..f1d8b816 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java @@ -11,8 +11,8 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.xmpp.util.ManagerTestHelper; -import org.fogbowcloud.manager.xmpp.util.TestHelperData; +import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.XMPPException; @@ -80,7 +80,7 @@ public boolean accept(Packet packet) { return false; } return packet.getFrom().toBareJID() - .equals(TestHelperData.MANAGER_COMPONENT_URL); + .equals(DefaultDataTest.MANAGER_COMPONENT_URL); } }, callback); managerXmppComponent.whoIsalive(); @@ -88,7 +88,7 @@ public boolean accept(Packet packet) { Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); Element element = packet.getElement().element("query"); Assert.assertEquals(element.getNamespaceURI(), - TestHelperData.WHOISALIVE_NAMESPACE); + DefaultDataTest.WHOISALIVE_NAMESPACE); Assert.assertEquals(1, managerXmppComponent.getManagerFacade() .getMembers().size()); @@ -141,7 +141,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - TestHelperData.WHOISALIVE_NAMESPACE); + DefaultDataTest.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); From f809abbac5c85607207df19822b7a513099e82cd Mon Sep 17 00:00:00 2001 From: fgan1 Date: Thu, 22 May 2014 10:25:57 -0300 Subject: [PATCH 152/185] Renaming DefaultDataTest to DefaultDataTestHelper. --- bin/fogbow-inject-tunnel | 1 - .../manager/core/TestManagerController.java | 254 +++++++++--------- ...taTest.java => DefaultDataTestHelper.java} | 2 +- .../manager/core/util/ManagerTestHelper.java | 2 +- .../manager/occi/TestDeleteCompute.java | 6 +- .../manager/occi/TestGetCompute.java | 8 +- .../manager/occi/TestGetRequest.java | 4 +- .../manager/occi/TestOCCIApplication.java | 4 +- .../manager/occi/TestTokenServerResource.java | 4 +- .../occi/plugins/TestIdentityOpenStack.java | 8 +- .../manager/occi/util/PluginHelper.java | 4 +- .../xmpp/TestDeleteRemoteInstance.java | 20 +- .../manager/xmpp/TestGetRemoteInstance.java | 26 +- .../manager/xmpp/TestIAmAlive.java | 8 +- .../xmpp/TestRequestRemoteInstance.java | 4 +- .../manager/xmpp/TestWhoIsAlive.java | 8 +- 16 files changed, 181 insertions(+), 182 deletions(-) rename src/test/java/org/fogbowcloud/manager/core/util/{DefaultDataTest.java => DefaultDataTestHelper.java} (97%) diff --git a/bin/fogbow-inject-tunnel b/bin/fogbow-inject-tunnel index f398b3fb..c10f53bb 100644 --- a/bin/fogbow-inject-tunnel +++ b/bin/fogbow-inject-tunnel @@ -1,3 +1,2 @@ #!/bin/sh /usr/bin/ssh -y -N -f -R 0.0.0.0:#REMOTE_PORT#:localhost:22 #REMOTE_USER#@#REMOTE_HOST# - diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index fa3abe8f..fe7ff2e0 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -18,7 +18,7 @@ import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; @@ -60,15 +60,15 @@ public void setUp() throws Exception { String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); HashMap tokenAttr = new HashMap(); - userToken = new Token(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.USER_NAME, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttr); + userToken = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); Properties properties = new Properties(); - properties.put("federation_user_name", DefaultDataTest.USER_NAME); - properties.put("federation_user_password", DefaultDataTest.USER_PASS); - properties.put("federation_user_tenant_name", DefaultDataTest.TENANT_NAME); - properties.put("scheduler_period", DefaultDataTest.SCHEDULER_PERIOD.toString()); - properties.put("instance_monitoring_period", Long.toString(DefaultDataTest.LONG_TIME)); + properties.put("federation_user_name", DefaultDataTestHelper.USER_NAME); + properties.put("federation_user_password", DefaultDataTestHelper.USER_PASS); + properties.put("federation_user_tenant_name", DefaultDataTestHelper.TENANT_NAME); + properties.put("scheduler_period", DefaultDataTestHelper.SCHEDULER_PERIOD.toString()); + properties.put("instance_monitoring_period", Long.toString(DefaultDataTestHelper.LONG_TIME)); managerController = new ManagerController(properties); // mocking compute @@ -81,7 +81,7 @@ public void setUp() throws Exception { // mocking identity identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(DefaultDataTest.ACCESS_TOKEN_ID)).thenReturn(userToken); + Mockito.when(identityPlugin.getToken(DefaultDataTestHelper.ACCESS_TOKEN_ID)).thenReturn(userToken); // mocking sshTunnel SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); @@ -96,39 +96,39 @@ public void testGetFederationMember() throws InterruptedException { OpenStackIdentityPlugin openStackidentityPlugin = Mockito .mock(OpenStackIdentityPlugin.class); Map tokenCredentials = new HashMap(); - tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, DefaultDataTest.USER_NAME); - tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, DefaultDataTest.USER_PASS); - tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTest.TENANT_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, DefaultDataTestHelper.USER_NAME); + tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, DefaultDataTestHelper.USER_PASS); + tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTestHelper.TENANT_NAME); long tokenExpirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTest.TENANT_NAME); - Token token = new Token(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.USER_NAME, new Date( + attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTestHelper.TENANT_NAME); + Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime), attributesTokenReturn); - Token token2 = new Token(ACCESS_TOKEN_ID_2, DefaultDataTest.USER_NAME, new Date( - tokenExpirationTime + DefaultDataTest.LONG_TIME), attributesTokenReturn); + Token token2 = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( + tokenExpirationTime + DefaultDataTestHelper.LONG_TIME), attributesTokenReturn); Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, token2); - Mockito.when(openStackidentityPlugin.isValid(DefaultDataTest.ACCESS_TOKEN_ID)).thenReturn( + Mockito.when(openStackidentityPlugin.isValid(DefaultDataTestHelper.ACCESS_TOKEN_ID)).thenReturn( true, false); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token Token federationUserToken = managerController.getFederationUserToken(); String accessToken = federationUserToken.getAccessId(); - Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, accessToken); + Assert.assertEquals(DefaultDataTestHelper.ACCESS_TOKEN_ID, accessToken); // Use member token accessToken = managerController.getFederationUserToken().getAccessId(); - Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, accessToken); + Assert.assertEquals(DefaultDataTestHelper.ACCESS_TOKEN_ID, accessToken); DateUtils dateUtils = Mockito.mock(DateUtils.class); Mockito.when(dateUtils.currentTimeMillis()).thenReturn( - tokenExpirationTime + DefaultDataTest.GRACE_TIME); + tokenExpirationTime + DefaultDataTestHelper.GRACE_TIME); token.setDateUtils(dateUtils); // Get new token @@ -142,17 +142,17 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { final int tokenUpdaterInterval = 100; long tokenExpirationTime = now + (4 * tokenUpdaterInterval); - Token token = new Token(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.USER_NAME, new Date( + Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime), new HashMap()); RequestRepository requestRepository = new RequestRepository(); for (int i = 0; i < 5; i++) { - requestRepository.addRequest(DefaultDataTest.USER_NAME, new Request("id" + i, token, + requestRepository.addRequest(DefaultDataTestHelper.USER_NAME, new Request("id" + i, token, null, null)); } managerController.setRequests(requestRepository); // adding behaviour on identity mock - Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTest.USER_NAME, new Date( + Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + tokenUpdaterInterval), new HashMap()); Mockito.when(identityPlugin.createToken(token)).thenReturn(secondToken); @@ -164,13 +164,13 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); List requestsFromUser = managerController - .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { - Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, request.getToken() + Assert.assertEquals(DefaultDataTestHelper.ACCESS_TOKEN_ID, request.getToken() .getAccessId()); } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { - Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, request.getToken() + Assert.assertEquals(DefaultDataTestHelper.ACCESS_TOKEN_ID, request.getToken() .getAccessId()); } } @@ -181,12 +181,12 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { Assert.assertEquals(ACCESS_TOKEN_ID_2, request.getToken().getAccessId()); } else if (request.getState().in(RequestState.CLOSED, RequestState.FAILED)) { - Assert.assertEquals(DefaultDataTest.ACCESS_TOKEN_ID, request.getToken() + Assert.assertEquals(DefaultDataTestHelper.ACCESS_TOKEN_ID, request.getToken() .getAccessId()); } } @@ -195,10 +195,10 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { @Test public void testMonitorDeletedRequestWithInstance() throws InterruptedException { Request request1 = new Request("id1", userToken, null, null); - request1.setInstanceId(DefaultDataTest.INSTANCE_ID); + request1.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request1.setState(RequestState.DELETED); Request request2 = new Request("id2", userToken, null, null); - request2.setInstanceId(DefaultDataTest.INSTANCE_ID); + request2.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request2.setState(RequestState.DELETED); RequestRepository requestRepository = new RequestRepository(); @@ -208,7 +208,7 @@ public void testMonitorDeletedRequestWithInstance() throws InterruptedException // updating compute mock Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(DefaultDataTest.INSTANCE_ID)); + .thenReturn(new Instance(DefaultDataTestHelper.INSTANCE_ID)); List requestsFromUser = managerController.getRequestsFromUser(userToken .getAccessId()); @@ -274,7 +274,7 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); @@ -282,7 +282,7 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); @@ -306,19 +306,19 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.FULFILLED, requestsFromUser.get(0).getState()); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.OPEN, requestsFromUser.get(0).getState()); managerController.checkAndSubmitOpenRequests(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.FULFILLED, requestsFromUser.get(0).getState()); } @@ -326,7 +326,7 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti @Test public void testMonitorFulfilledRequestWithInstance() throws InterruptedException { Request request1 = new Request("id1", userToken, null, null); - request1.setInstanceId(DefaultDataTest.INSTANCE_ID); + request1.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", userToken, null, null); request2.setInstanceId(SECOND_INSTANCE_ID); @@ -339,17 +339,17 @@ public void testMonitorFulfilledRequestWithInstance() throws InterruptedExceptio //updating compute mock Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(DefaultDataTest.INSTANCE_ID)); + .thenReturn(new Instance(DefaultDataTestHelper.INSTANCE_ID)); managerController.monitorInstances(); - List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertEquals(RequestState.FULFILLED, request.getState()); } managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); @@ -400,16 +400,16 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { public void testGetRequestsByUser() throws InterruptedException { mockRequestInstance(); - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(DefaultDataTest.USER_NAME, requests.get(0).getToken().getUser()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.USER_NAME, requests.get(0).getToken().getUser()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); } @@ -418,22 +418,22 @@ public void testGetRequestsByUser() throws InterruptedException { public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { mockRequestInstance(); - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestState.CLOSED, requests.get(0).getState()); @@ -448,24 +448,24 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti mockRequestInstance(); - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -485,29 +485,29 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(DefaultDataTest.INSTANCE_ID, + Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID, SECOND_INSTANCE_ID); managerController.setComputePlugin(computePlugin); - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); List requests = managerController - .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -517,9 +517,9 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getMemberId()); // getting second instance - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD * 2); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 2); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); @@ -531,7 +531,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr @Test public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + DefaultDataTest.SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); @@ -539,11 +539,11 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException String.valueOf(DateUtils.getDateISO8601Format(expirationRequestTime))); // creating request - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -552,9 +552,9 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -566,8 +566,8 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException @Test public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + DefaultDataTest.SCHEDULER_PERIOD - + DefaultDataTest.GRACE_TIME; + long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD + + DefaultDataTestHelper.GRACE_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); @@ -576,28 +576,28 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep mockRequestInstance(); - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); - List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); // removing instance - managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -611,23 +611,23 @@ private void mockRequestInstance() { computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(DefaultDataTest.INSTANCE_ID); + Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID); managerController.setComputePlugin(computePlugin); } @Test public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + DefaultDataTest.SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); // creating request - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -636,9 +636,9 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -651,8 +651,8 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { @Test public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + DefaultDataTest.LONG_TIME; + long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + DefaultDataTestHelper.LONG_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.ONE_TIME.getValue())); @@ -664,11 +664,11 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -677,9 +677,9 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); // request is not in valid period yet Assert.assertEquals(1, requests.size()); @@ -689,24 +689,24 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // request is in valid period - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } @Test public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + DefaultDataTest.LONG_TIME; + long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + DefaultDataTestHelper.LONG_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), @@ -717,10 +717,10 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -729,9 +729,9 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); // request is not in valid period yet Assert.assertEquals(1, requests.size()); @@ -741,24 +741,24 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // request is in valid period - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); } @Test public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 3); + long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), @@ -769,15 +769,15 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); // request is not in valid period yet Assert.assertEquals(1, requests.size()); @@ -787,25 +787,25 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // request is in valid period - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); // remove instance - managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // request is not in valid period anymore - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -818,8 +818,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti @Test public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (DefaultDataTest.SCHEDULER_PERIOD * 3); + long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); + long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), @@ -830,15 +830,15 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTest.ACCESS_TOKEN_ID, new ArrayList(), + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); List requests = managerController - .getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); // request is not in valid period yet Assert.assertEquals(1, requests.size()); @@ -848,27 +848,27 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // request is in valid period - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); - Assert.assertEquals(DefaultDataTest.INSTANCE_ID, requests.get(0).getInstanceId()); + Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // remove instance - managerController.removeInstance(DefaultDataTest.ACCESS_TOKEN_ID, DefaultDataTest.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - Thread.sleep(DefaultDataTest.SCHEDULER_PERIOD + DefaultDataTest.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // request is not in valid period anymore - requests = managerController.getRequestsFromUser(DefaultDataTest.ACCESS_TOKEN_ID); + requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), diff --git a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTest.java b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java similarity index 97% rename from src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTest.java rename to src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java index 4c01f915..ff11356b 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTest.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java @@ -2,7 +2,7 @@ import java.util.Date; -public class DefaultDataTest { +public class DefaultDataTestHelper { //xmpp data protected static final int SERVER_CLIENT_PORT = 5222; diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index 25024c5c..90c9fd57 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -38,7 +38,7 @@ import org.xmpp.packet.IQ; import org.xmpp.packet.Packet; -public class ManagerTestHelper extends DefaultDataTest { +public class ManagerTestHelper extends DefaultDataTestHelper { private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java index 2d378e99..25956ccb 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestDeleteCompute.java @@ -13,7 +13,7 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.request.Request; @@ -46,12 +46,12 @@ public void setup() throws Exception { List requests = new LinkedList(); Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, - OCCITestHelper.USER_MOCK, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + OCCITestHelper.USER_MOCK, DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request1.setInstanceId(INSTANCE_ID); requests.add(request1); Request request2 = new Request("2", new Token("otherToken", "otherUser", - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request2.setInstanceId(OTHER_INSTANCE_ID); requests.add(request2); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java index c6dd33ea..907fd2cc 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetCompute.java @@ -14,7 +14,7 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Resource; import org.fogbowcloud.manager.occi.core.Token; @@ -62,17 +62,17 @@ public void setup() throws Exception { List requests = new LinkedList(); Request request1 = new Request("1", new Token(OCCITestHelper.ACCESS_TOKEN, - OCCITestHelper.USER_MOCK, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + OCCITestHelper.USER_MOCK, DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request1.setInstanceId(INSTANCE_1_ID); requests.add(request1); Request request2 = new Request("2", new Token(OCCITestHelper.ACCESS_TOKEN, - OCCITestHelper.USER_MOCK, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + OCCITestHelper.USER_MOCK, DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request2.setInstanceId(INSTANCE_2_ID); requests.add(request2); Request request3 = new Request("3", new Token("token", "user", - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request3.setInstanceId(INSTANCE_3_ID_WITHOUT_USER); requests.add(request3); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java index ff7b201e..25f9c4ba 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestGetRequest.java @@ -19,7 +19,7 @@ import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.HeaderUtils; @@ -64,7 +64,7 @@ public void setup() throws Exception { HashMap tokenAttr = new HashMap(); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttr); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(OCCITestHelper.ACCESS_TOKEN)).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java index 205e6f24..41693d00 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestOCCIApplication.java @@ -10,7 +10,7 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.ssh.SSHTunnel; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -58,7 +58,7 @@ public void setUp() { IdentityPlugin identityPlugin = Mockito.mock(IdentityPlugin.class); HashMap tokenAttr = new HashMap(); Token userToken = new Token(OCCITestHelper.ACCESS_TOKEN, OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttr); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); Mockito.when(identityPlugin.getToken(Mockito.anyString())).thenReturn(userToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java index cef734c9..e37e30b8 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java +++ b/src/test/java/org/fogbowcloud/manager/occi/TestTokenServerResource.java @@ -11,7 +11,7 @@ import org.apache.http.util.EntityUtils; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; @@ -58,7 +58,7 @@ public void testGetTokenWrongContentType() throws Exception { @SuppressWarnings("unchecked") @Test public void testGetToken() throws Exception { - Token token = new Token(ACCESS_TOKEN_ID, "user", DefaultDataTest.TOKEN_FUTURE_EXPIRATION, + Token token = new Token(ACCESS_TOKEN_ID, "user", DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()); Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(token); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 4c61852a..9c02b053 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -6,7 +6,7 @@ import java.util.Properties; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; @@ -71,7 +71,7 @@ public void testGetToken() { Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(DefaultDataTest.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, expirationDate); } @Test @@ -86,7 +86,7 @@ public void testUpgradeToken() { Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(DefaultDataTest.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, expirationDate); Token token2 = this.identityOpenStack.createToken(token); authToken = token2.getAccessId(); @@ -94,7 +94,7 @@ public void testUpgradeToken() { expirationDate = token2.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(DefaultDataTest.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, expirationDate); } @Test(expected = OCCIException.class) diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index db32669d..95b84e2a 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Map; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; @@ -40,7 +40,7 @@ public void initializeKeystoneComponent() throws Exception { tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); // tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); - Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, DefaultDataTest.TOKEN_FUTURE_EXPIRATION, tokenAttributes); + Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttributes); // TODO Refactor! We really need all these args to KeytoneApplication? KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java index c867e5ed..3472f8b7 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestDeleteRemoteInstance.java @@ -2,7 +2,7 @@ import java.util.HashMap; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; @@ -36,9 +36,9 @@ public void tearDown() throws Exception { @Test public void testDeleteRemoteInstance() throws Exception { Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); - request.setInstanceId(DefaultDataTest.INSTANCE_ID); - request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); + request.setMemberId(DefaultDataTestHelper.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); @@ -47,9 +47,9 @@ public void testDeleteRemoteInstance() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); - request.setInstanceId(DefaultDataTest.INSTANCE_ID); - request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); + request.setMemberId(DefaultDataTestHelper.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -63,15 +63,15 @@ public void testDeleteRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testDeleteRemoteInstanceUnauthorized() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request.setInstanceId(INSTANCE_OTHER_USER); - request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); + request.setMemberId(DefaultDataTestHelper.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) - .removeInstance(Mockito.eq(DefaultDataTest.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); + .removeInstance(Mockito.eq(DefaultDataTestHelper.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); ManagerPacketHelper.deleteRemoteInstace(request, managerTestHelper.createPacketSender()); } diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java index 910eb1b4..8e85e725 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestGetRemoteInstance.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Map; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; @@ -58,7 +58,7 @@ private Instance createInstance() { Link link = new Link("linkname", attributes); - return new Instance(DefaultDataTest.INSTANCE_ID, resources, attributes, link); + return new Instance(DefaultDataTestHelper.INSTANCE_ID, resources, attributes, link); } @Test @@ -68,13 +68,13 @@ public void testGetRemoteInstance() throws Exception { Mockito.when( managerTestHelper.getComputePlugin().getInstance( - Mockito.eq(DefaultDataTest.ACCESS_TOKEN_ID), - Mockito.eq(DefaultDataTest.INSTANCE_ID))).thenReturn(instance); + Mockito.eq(DefaultDataTestHelper.ACCESS_TOKEN_ID), + Mockito.eq(DefaultDataTestHelper.INSTANCE_ID))).thenReturn(instance); Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); - request.setInstanceId(DefaultDataTest.INSTANCE_ID); - request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); + request.setMemberId(DefaultDataTestHelper.MANAGER_COMPONENT_URL); Instance remoteInstance = null; try { @@ -94,9 +94,9 @@ public void testGetRemoteInstance() throws Exception { @Test public void testGetRemoteInstaceNotFound() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); - request.setInstanceId(DefaultDataTest.INSTANCE_ID); - request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + request.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); + request.setMemberId(DefaultDataTestHelper.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); @@ -111,15 +111,15 @@ public void testGetRemoteInstaceNotFound() throws Exception { @Test(expected = OCCIException.class) public void testGetRemoteInstanceUnauthorized() throws Exception { Request request = new Request("anyvalue", new Token(WRONG_TOKEN, OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), null, null); request.setInstanceId(INSTANCE_OTHER_USER); - request.setMemberId(DefaultDataTest.MANAGER_COMPONENT_URL); + request.setMemberId(DefaultDataTestHelper.MANAGER_COMPONENT_URL); managerTestHelper.initializeXMPPManagerComponent(false); Mockito.doThrow(new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED)) .when(this.managerTestHelper.getComputePlugin()) - .getInstance(Mockito.eq(DefaultDataTest.ACCESS_TOKEN_ID), + .getInstance(Mockito.eq(DefaultDataTestHelper.ACCESS_TOKEN_ID), Mockito.eq(INSTANCE_OTHER_USER)); ManagerPacketHelper.getRemoteInstance(request, managerTestHelper.createPacketSender()); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 3193af62..0e9b395f 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -11,7 +11,7 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; @@ -63,7 +63,7 @@ public boolean accept(Packet packet) { return false; } return packet.getFrom().toBareJID() - .equals(DefaultDataTest.MANAGER_COMPONENT_URL); + .equals(DefaultDataTestHelper.MANAGER_COMPONENT_URL); } }, callback); @@ -143,7 +143,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - DefaultDataTest.IAMALIVE_NAMESPACE); + DefaultDataTestHelper.IAMALIVE_NAMESPACE); } }, callbackIAmAlive); @@ -155,7 +155,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - DefaultDataTest.WHOISALIVE_NAMESPACE); + DefaultDataTestHelper.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java index 58cb27a3..fc94ff42 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestRequestRemoteInstance.java @@ -5,7 +5,7 @@ import java.util.List; import java.util.Map; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; @@ -65,7 +65,7 @@ private Request createRequest() { attributes.put("key1", "value1"); attributes.put("key2", "value2"); Request request = new Request("anyvalue", new Token("anyvalue", OCCITestHelper.USER_MOCK, - DefaultDataTest.TOKEN_FUTURE_EXPIRATION, new HashMap()), categories, + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, new HashMap()), categories, attributes); request.setInstanceId(INSTANCE_DEFAULT); return request; diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java index f1d8b816..1d9ae573 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestWhoIsAlive.java @@ -11,7 +11,7 @@ import org.dom4j.Element; import org.fogbowcloud.manager.core.model.FederationMember; -import org.fogbowcloud.manager.core.util.DefaultDataTest; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.jamppa.client.XMPPClient; import org.jivesoftware.smack.PacketListener; @@ -80,7 +80,7 @@ public boolean accept(Packet packet) { return false; } return packet.getFrom().toBareJID() - .equals(DefaultDataTest.MANAGER_COMPONENT_URL); + .equals(DefaultDataTestHelper.MANAGER_COMPONENT_URL); } }, callback); managerXmppComponent.whoIsalive(); @@ -88,7 +88,7 @@ public boolean accept(Packet packet) { Packet packet = blockingQueue.poll(5, TimeUnit.SECONDS); Element element = packet.getElement().element("query"); Assert.assertEquals(element.getNamespaceURI(), - DefaultDataTest.WHOISALIVE_NAMESPACE); + DefaultDataTestHelper.WHOISALIVE_NAMESPACE); Assert.assertEquals(1, managerXmppComponent.getManagerFacade() .getMembers().size()); @@ -141,7 +141,7 @@ public boolean accept(Packet packet) { return false; } return element.getNamespaceURI().equals( - DefaultDataTest.WHOISALIVE_NAMESPACE); + DefaultDataTestHelper.WHOISALIVE_NAMESPACE); } }, callbackWhoIsAlive); From 04b3c6b3bc991e3c90327d75246675c881467e82 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 22 May 2014 17:25:09 -0300 Subject: [PATCH 153/185] Refactoring tests and classes --- .../org/fogbowcloud/manager/cli/Main.java | 7 +- .../manager/core/ManagerController.java | 8 +- .../manager/core/model/DateUtils.java | 13 +- .../openstack/OpenStackComputePlugin.java | 2 +- .../openstack/OpenStackIdentityPlugin.java | 195 +++++++++--------- .../manager/occi/TokenServerResource.java | 14 +- .../manager/occi/core/OCCIHeaders.java | 13 +- .../manager/occi/request/Request.java | 54 ++--- .../manager/core/TestManagerController.java | 11 +- .../core/util/DefaultDataTestHelper.java | 2 - .../manager/core/util/ManagerTestHelper.java | 8 +- .../occi/plugins/TestIdentityOpenStack.java | 31 ++- .../occi/util/KeystoneApplication.java | 44 ++-- .../manager/occi/util/PluginHelper.java | 10 +- 14 files changed, 195 insertions(+), 217 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index efcbf4b1..f7efceca 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -17,6 +17,7 @@ import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import com.beust.jcommander.JCommander; @@ -122,9 +123,9 @@ public static void main(String[] args) throws Exception { } Set
headers = new HashSet
(); - headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_USER, token.username)); - headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_PASS, token.password)); - headers.add(new BasicHeader(OCCIHeaders.X_TOKEN_TENANT_NAME, token.tenantName)); + headers.add(new BasicHeader(OpenStackIdentityPlugin.USER_KEY, token.username)); + headers.add(new BasicHeader(OpenStackIdentityPlugin.PASSWORD_KEY, token.password)); + headers.add(new BasicHeader(OpenStackIdentityPlugin.TENANT_NAME_KEY, token.tenantName)); doRequest("get", url + "/token", null, headers); } else if (parsedCommand.equals("query")) { diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index ed3de9ff..78f16289 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -16,12 +16,12 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.ssh.DefaultSSHTunnel; import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; @@ -293,9 +293,9 @@ protected Token getFederationUserToken() { String username = properties.getProperty("federation_user_name"); String password = properties.getProperty("federation_user_password"); String tenantName = properties.getProperty("federation_user_tenant_name"); - federationUserCredentials.put(OCCIHeaders.X_TOKEN_USER, username); - federationUserCredentials.put(OCCIHeaders.X_TOKEN_PASS, password); - federationUserCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); + federationUserCredentials.put(OpenStackIdentityPlugin.USER_KEY, username); + federationUserCredentials.put(OpenStackIdentityPlugin.PASSWORD_KEY, password); + federationUserCredentials.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); this.federationUserToken = identityPlugin.createToken(federationUserCredentials); return federationUserToken; diff --git a/src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java b/src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java index ce85cb88..be98d187 100644 --- a/src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java +++ b/src/main/java/org/fogbowcloud/manager/core/model/DateUtils.java @@ -6,7 +6,7 @@ import java.util.TimeZone; public class DateUtils { - + public DateUtils() { } @@ -14,6 +14,17 @@ public long currentTimeMillis() { return System.currentTimeMillis(); } + public static Date getDateFromISO8601Format(String expirationDateStr) { + SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( + FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); + dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); + try { + return dateFormatISO8601.parse(expirationDateStr); + } catch (Exception e) { + return null; + } + } + public static String getDateISO8601Format(long dateMili) { SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index 8967431f..adcf8952 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -174,7 +174,7 @@ public void removeInstance(String authToken, String instanceId) { public ResourcesInfo getResourcesInfo(Token token) { String responseStr = doRequest( "get", - computeV2APIEndpoint + token.getAttributes().get(OCCIHeaders.X_TOKEN_TENANT_ID) + computeV2APIEndpoint + token.getAttributes().get(OpenStackIdentityPlugin.TENANT_ID_KEY) + "/limits", token.getAccessId()).getResponseString(); String maxCpu = getAttFromJson(MAX_TOTAL_CORES_ATT, responseStr); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 06b4dd21..616ac0ce 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -1,12 +1,9 @@ package org.fogbowcloud.manager.core.plugins.openstack; -import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; -import java.util.Locale; import java.util.Map; import java.util.Properties; -import java.util.TimeZone; import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; @@ -19,17 +16,25 @@ import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -import org.fogbowcloud.manager.core.model.FederationMember; +import org.fogbowcloud.manager.core.model.DateUtils; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; +import org.json.JSONException; import org.json.JSONObject; public class OpenStackIdentityPlugin implements IdentityPlugin { + // keys for attributes map + public static final String USER_KEY = "X-Token-User"; + public static final String PASSWORD_KEY = "X-Token-Password"; + public static final String TENANT_ID_KEY = "X-Token-TenantId"; + public static final String TENANT_NAME_KEY = "X-Token-TenantName"; + + // keystone json data public static final String TENANT_NAME_KEYSTONE = "tenantName"; public static final String USERNAME_KEYSTONE = "username"; public static final String PASSWORD_KEYSTONE = "password"; @@ -42,11 +47,10 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String EXPIRES_KEYSTONE = "expires"; public static final String USER_KEYSTONE = "user"; public static final String NAME_KEYSTONE = "name"; - private static final Logger LOGGER = Logger.getLogger(OpenStackIdentityPlugin.class); - private static final int LAST_SUCCESSFUL_STATUS = 204; + private static final int LAST_SUCCESSFUL_STATUS = 204; + private final Logger LOGGER = Logger.getLogger(OpenStackIdentityPlugin.class); private static String V2_ENDPOINT_PATH = "/v2.0/tokens"; - private String v2Endpoint; public OpenStackIdentityPlugin(Properties properties) { @@ -54,50 +58,45 @@ public OpenStackIdentityPlugin(Properties properties) { this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; } - public String getResponseJson(String tokenId) { - HttpResponse response; - String responseStr = null; + @Override + public Token createToken(Map credentials) { + JSONObject json; try { - HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.v2Endpoint + "/" + tokenId); - httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, tokenId); - response = httpCLient.execute(httpGet); - - responseStr = EntityUtils - .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); - } catch (Exception e) { + json = mountJson(credentials); + } catch (JSONException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - checkStatusResponse(response); - return responseStr; + String responseStr = doPostRequest(v2Endpoint, json); + return getTokenFromJson(responseStr); } - @Override - public Token createToken(Map tokenAttributes) { + private JSONObject mountJson(Map credentials) throws JSONException { + JSONObject passwordCredentials = new JSONObject(); + passwordCredentials.put(USERNAME_KEYSTONE, + credentials.get(OpenStackIdentityPlugin.USER_KEY)); + passwordCredentials.put(PASSWORD_KEYSTONE, + credentials.get(OpenStackIdentityPlugin.PASSWORD_KEY)); + JSONObject auth = new JSONObject(); + auth.put(TENANT_NAME_KEYSTONE, credentials.get(TENANT_NAME_KEY)); + auth.put(PASSWORD_CREDENTIALS_KEYSTONE, passwordCredentials); + JSONObject root = new JSONObject(); + root.put(AUTH_KEYSTONE, auth); + return root; + } + + private String doPostRequest(String endpoint, JSONObject json) { HttpResponse response; String responseStr = null; try { - HttpClient httpClient = new DefaultHttpClient(); - HttpPost httpPost = new HttpPost(this.v2Endpoint); - - httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); - httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); - - JSONObject passwordCredentials = new JSONObject(); - passwordCredentials.put(USERNAME_KEYSTONE, - tokenAttributes.get(OCCIHeaders.X_TOKEN_USER)); - passwordCredentials.put(PASSWORD_KEYSTONE, - tokenAttributes.get(OCCIHeaders.X_TOKEN_PASS)); - JSONObject auth = new JSONObject(); - auth.put(TENANT_NAME_KEYSTONE, tokenAttributes.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); - auth.put(PASSWORD_CREDENTIALS_KEYSTONE, passwordCredentials); - JSONObject root = new JSONObject(); - root.put(AUTH_KEYSTONE, auth); - httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); - response = httpClient.execute(httpPost); + HttpPost request = new HttpPost(endpoint); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); + request.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_CONTENT_TYPE); + request.setEntity(new StringEntity(json.toString(), HTTP.UTF_8)); + HttpClient client = new DefaultHttpClient(); + response = client.execute(request); responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); } catch (Exception e) { LOGGER.error(e); @@ -105,40 +104,34 @@ public Token createToken(Map tokenAttributes) { } checkStatusResponse(response); - return getTokenFromJson(responseStr); + return responseStr; } @Override public Token createToken(Token token) { - HttpResponse response; - String responseStr = null; + JSONObject json; try { - HttpClient httpClient = new DefaultHttpClient(); - HttpPost httpPost = new HttpPost(this.v2Endpoint); - - httpPost.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); - httpPost.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_ACCEPT); - - JSONObject idToken = new JSONObject(); - idToken.put(ID_KEYSTONE, token.getAccessId()); - JSONObject auth = new JSONObject(); - auth.put(TENANT_NAME_KEYSTONE, token.get(OCCIHeaders.X_TOKEN_TENANT_NAME)); - auth.put(TOKEN_KEYSTONE, idToken); - JSONObject root = new JSONObject(); - root.put(AUTH_KEYSTONE, auth); - httpPost.setEntity(new StringEntity(root.toString(), HTTP.UTF_8)); - response = httpClient.execute(httpPost); - - responseStr = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); - } catch (Exception e) { + json = mountJson(token); + } catch (JSONException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - checkStatusResponse(response); + String responseStr = doPostRequest(v2Endpoint, json); return getTokenFromJson(responseStr); } + private JSONObject mountJson(Token token) throws JSONException { + JSONObject idToken = new JSONObject(); + idToken.put(ID_KEYSTONE, token.getAccessId()); + JSONObject auth = new JSONObject(); + auth.put(TENANT_NAME_KEYSTONE, token.get(TENANT_NAME_KEY)); + auth.put(TOKEN_KEYSTONE, idToken); + JSONObject root = new JSONObject(); + root.put(AUTH_KEYSTONE, auth); + return root; + } + private void checkStatusResponse(HttpResponse response) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new OCCIException(ErrorType.UNAUTHORIZED, ResponseConstants.UNAUTHORIZED); @@ -151,7 +144,6 @@ private void checkStatusResponse(HttpResponse response) { private Token getTokenFromJson(String responseStr) { try { - Map attributes = new HashMap(); JSONObject root = new JSONObject(responseStr); JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( TOKEN_KEYSTONE); @@ -159,71 +151,78 @@ private Token getTokenFromJson(String responseStr) { String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); String tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( NAME_KEYSTONE); - String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); - + String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); String user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) .getString(NAME_KEYSTONE); - attributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, tenantId); - attributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tenantName); - - return new Token(token, user, getDate(expirationDateToken), attributes); + Map tokenAtt = new HashMap(); + tokenAtt.put(TENANT_ID_KEY, tenantId); + tokenAtt.put(TENANT_NAME_KEY, tenantName); + return new Token(token, user, DateUtils.getDateFromISO8601Format(expirationDateToken), + tokenAtt); } catch (Exception e) { - e.printStackTrace(); LOGGER.error("Exception while getting token from json.", e); return null; } } - private Date getDate(String expirationDateStr) { - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - try { - return dateFormatISO8601.parse(expirationDateStr); - } catch (Exception e) { - LOGGER.error("Exception while getting date from String.", e); - return null; - } - } - @Override public Token getToken(String accessId) { String responseJson = getResponseJson(accessId); - long expirationTimeMillis = 0; + Date expirationTime = null; String user = null; + Map tokenAttributes = new HashMap(); try { - //TODO Refactor! This code is repeated at many classes - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - JSONObject root = new JSONObject(responseJson); - user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) .getString(NAME_KEYSTONE); - - String expirationTime = root.getJSONObject(ACCESS_KEYSTONE) + String expirationTimeStr = root.getJSONObject(ACCESS_KEYSTONE) .getJSONObject(TOKEN_KEYSTONE).getString(EXPIRES_KEYSTONE); - expirationTimeMillis = dateFormatISO8601.parse(expirationTime).getTime(); + String tenantName = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) + .getJSONObject(TENANT_KEYSTONE).getString(NAME_KEYSTONE); + String tenantId = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) + .getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); + + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, tenantId); + expirationTime = DateUtils.getDateFromISO8601Format(expirationTimeStr); } catch (Exception e) { LOGGER.error(e); } + return new Token(accessId, user, expirationTime, tokenAttributes); + } - Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, user); + /* + * The json response format can be seen in the following link: + * http://developer.openstack.org/api-ref-identity-v2.html + */ + public String getResponseJson(String accessId) { + HttpResponse response; + String responseStr = null; + try { + HttpClient httpCLient = new DefaultHttpClient(); + HttpGet httpGet = new HttpGet(this.v2Endpoint + "/" + accessId); + httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, accessId); + response = httpCLient.execute(httpGet); + + responseStr = EntityUtils + .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); + } catch (Exception e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } + checkStatusResponse(response); - return new Token(accessId, user, new Date(expirationTimeMillis), tokenAttributes); + return responseStr; } @Override public boolean isValid(String accessId) { - try{ + try { getToken(accessId); return true; - } catch (OCCIException e){ + } catch (OCCIException e) { return false; } } - } diff --git a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java index 5b654e27..b80d85a9 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/TokenServerResource.java @@ -3,8 +3,8 @@ import java.util.HashMap; import java.util.Map; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.HeaderUtils; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.restlet.engine.adapter.HttpRequest; import org.restlet.resource.Get; @@ -18,14 +18,14 @@ public String fetch() { HttpRequest req = (HttpRequest) getRequest(); HeaderUtils.checkOCCIContentType(req.getHeaders()); - String username = req.getHeaders().getValues(OCCIHeaders.X_TOKEN_USER); - String password = req.getHeaders().getValues(OCCIHeaders.X_TOKEN_PASS); - String tanantName = req.getHeaders().getValues(OCCIHeaders.X_TOKEN_TENANT_NAME); + String username = req.getHeaders().getValues(OpenStackIdentityPlugin.USER_KEY); + String password = req.getHeaders().getValues(OpenStackIdentityPlugin.PASSWORD_KEY); + String tanantName = req.getHeaders().getValues(OpenStackIdentityPlugin.TENANT_NAME_KEY); Map attributesToken = new HashMap(); - attributesToken.put(OCCIHeaders.X_TOKEN_USER, username); - attributesToken.put(OCCIHeaders.X_TOKEN_PASS, password); - attributesToken.put(OCCIHeaders.X_TOKEN_TENANT_NAME, tanantName); + attributesToken.put(OpenStackIdentityPlugin.USER_KEY, username); + attributesToken.put(OpenStackIdentityPlugin.PASSWORD_KEY, password); + attributesToken.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, tanantName); return generateResponse(application.getToken(attributesToken)); } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java index 28c477e4..782aab1c 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/OCCIHeaders.java @@ -6,21 +6,16 @@ public class OCCIHeaders { public static final String CONTENT_TYPE = "Content-Type"; public static final String X_AUTH_TOKEN = "X-Auth-Token"; public static final String X_SUBJECT_TOKEN = "X-Subject-Token"; - public static final String X_TOKEN_USER = "X-Token-User"; - public static final String X_TOKEN_PASS = "X-Token-Pass"; - public static final String X_TOKEN_TENANT_NAME = "X-Token-Tenant-Name"; - public static final String X_TOKEN_TENANT_ID = "X-Token-Tenant-Id"; - - // occi constants - public static final String CATEGORY = "Category"; public static final String X_OCCI_ATTRIBUTE = "X-OCCI-Attribute"; + public static final String ACCEPT = "Accept"; + public static final String CATEGORY = "Category"; + + // occi constants public static final String KIND_CLASS = "kind"; public static final String MIXIN_CLASS = "mixin"; public static final String ACTION_CLASS = "action"; public static final String SCHEME_CATEGORY = "scheme"; public static final String CLASS_CATEGORY = "class"; public static final String OCCI_CONTENT_TYPE = "text/occi"; - public static final String ACCEPT = "Accept"; public static final String JSON_CONTENT_TYPE = "application/json"; - public static final String JSON_ACCEPT = "application/json"; } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 2b253fe7..4c9023ad 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -1,15 +1,12 @@ package org.fogbowcloud.manager.occi.request; -import java.text.SimpleDateFormat; +import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import java.util.Locale; import java.util.Map; -import java.util.TimeZone; import org.fogbowcloud.manager.core.model.DateUtils; -import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.Token; @@ -23,8 +20,7 @@ public class Request { private List categories; private Map xOCCIAtt; - public Request(String id, Token token, List categories, - Map xOCCIAtt) { + public Request(String id, Token token, List categories, Map xOCCIAtt) { this.id = id; this.token = token; this.categories = categories; @@ -81,12 +77,12 @@ public String toHttpMessageFormat() { return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; } - public Token getToken() { + public Token getToken() { return this.token; } - + public void setToken(Token token) { - this.token = token; + this.token = token; } public Map getxOCCIAtt() { @@ -108,40 +104,28 @@ public String toString() { } public boolean isIntoValidPeriod() { - String startDateStr = xOCCIAtt.get(RequestAttribute.VALID_FROM.getValue()); - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - long startDateMillis; - try { - if (startDateStr != null){ - startDateMillis = dateFormatISO8601.parse(startDateStr).getTime(); - } else { - startDateMillis = new DateUtils().currentTimeMillis(); + String startDateStr = xOCCIAtt.get(RequestAttribute.VALID_FROM.getValue()); + Date startDate = DateUtils.getDateFromISO8601Format(startDateStr); + if (startDate == null) { + if (startDateStr != null) { + return false; } - } catch (Exception e) { - return false; + startDate = new Date(); } long now = new DateUtils().currentTimeMillis(); - return startDateMillis <= now && !isExpired(); + return startDate.getTime() <= now && !isExpired(); } - public boolean isExpired() { - String expirationDateSrt = xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()); - if (expirationDateSrt == null){ + public boolean isExpired() { + String expirationDateStr = xOCCIAtt.get(RequestAttribute.VALID_UNTIL.getValue()); + Date expirationDate = DateUtils.getDateFromISO8601Format(expirationDateStr); + if (expirationDateStr == null) { return false; - } - //TODO Refactor! This code is repeated at many places - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - long expirationDateMillis; - try { - expirationDateMillis = dateFormatISO8601.parse(expirationDateSrt).getTime(); - } catch (Exception e) { + } else if (expirationDate == null) { return true; } + long now = new DateUtils().currentTimeMillis(); - return expirationDateMillis < now; + return expirationDate.getTime() < now; } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index fe7ff2e0..29c71b24 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -23,7 +23,6 @@ import org.fogbowcloud.manager.occi.core.Category; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.instance.Instance; @@ -96,15 +95,15 @@ public void testGetFederationMember() throws InterruptedException { OpenStackIdentityPlugin openStackidentityPlugin = Mockito .mock(OpenStackIdentityPlugin.class); Map tokenCredentials = new HashMap(); - tokenCredentials.put(OCCIHeaders.X_TOKEN_USER, DefaultDataTestHelper.USER_NAME); - tokenCredentials.put(OCCIHeaders.X_TOKEN_PASS, DefaultDataTestHelper.USER_PASS); - tokenCredentials.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTestHelper.TENANT_NAME); + tokenCredentials.put(OpenStackIdentityPlugin.USER_KEY, DefaultDataTestHelper.USER_NAME); + tokenCredentials.put(OpenStackIdentityPlugin.PASSWORD_KEY, DefaultDataTestHelper.USER_PASS); + tokenCredentials.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, DefaultDataTestHelper.TENANT_NAME); long tokenExpirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_ID, "987654321"); - attributesTokenReturn.put(OCCIHeaders.X_TOKEN_TENANT_NAME, DefaultDataTestHelper.TENANT_NAME); + attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_ID_KEY, "987654321"); + attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, DefaultDataTestHelper.TENANT_NAME); Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime), attributesTokenReturn); diff --git a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java index ff11356b..ff093df3 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java @@ -20,8 +20,6 @@ public class DefaultDataTestHelper { public static final String CONFIG_PATH = "src/test/resources/manager.conf.test"; //time data - public static final int TEST_DEFAULT_TIMEOUT = 10000; - public static final int TIMEOUT_GRACE = 500; public static final Long SCHEDULER_PERIOD = 500L; public static final Long GRACE_TIME = 30L; public static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; //one day diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index 90c9fd57..610eaa33 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -23,7 +23,7 @@ import org.fogbowcloud.manager.core.model.ResourcesInfo; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; @@ -47,7 +47,7 @@ public class ManagerTestHelper extends DefaultDataTestHelper { public ManagerTestHelper() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, "tenantId_r4fci3qhbcy3b"); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, "tenantId_r4fci3qhbcy3b"); this.tokenDefault = new Token(ACCESS_TOKEN_ID, USER_NAME, TOKEN_FUTURE_EXPIRATION, tokenAttributes); } @@ -226,7 +226,7 @@ public List getItemsFromIQ(Packet response) throws Certificate ArrayList aliveItems = new ArrayList(); while (itemIterator.hasNext()) { - Element itemEl = (Element) itemIterator.next(); + Element itemEl = itemIterator.next(); Attribute id = itemEl.attribute("id"); Element statusEl = itemEl.element("status"); X509Certificate cert = CertificateHandlerHelper.parseCertificate(itemEl.element("cert") @@ -238,7 +238,7 @@ public List getItemsFromIQ(Packet response) throws Certificate List flavoursList = new LinkedList(); Iterator flavourIterator = itemEl.elementIterator("flavor"); while (flavourIterator.hasNext()) { - Element flavour = (Element) itemIterator.next(); + Element flavour = itemIterator.next(); String name = flavour.element("name").getText(); String cpu = flavour.element("cpu").getText(); String mem = flavour.element("mem").getText(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 9c02b053..9d7701d2 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -8,7 +8,6 @@ import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.occi.core.OCCIException; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.PluginHelper; import org.junit.After; @@ -62,12 +61,12 @@ public void testGetNameUserFromTokenInvalid() { @Test public void testGetToken() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANT_NAME); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); - String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); + String tenantID = token.get(OpenStackIdentityPlugin.TENANT_ID_KEY); Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); @@ -77,12 +76,12 @@ public void testGetToken() { @Test public void testUpgradeToken() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, PluginHelper.TENANT_NAME); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); - String tenantID = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); + String tenantID = token.get(OpenStackIdentityPlugin.TENANT_ID_KEY); Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); @@ -90,7 +89,7 @@ public void testUpgradeToken() { Token token2 = this.identityOpenStack.createToken(token); authToken = token2.getAccessId(); - tenantID = token2.get(OCCIHeaders.X_TOKEN_TENANT_ID); + tenantID = token2.get(OpenStackIdentityPlugin.TENANT_ID_KEY); expirationDate = token2.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); @@ -100,18 +99,18 @@ public void testUpgradeToken() { @Test(expected = OCCIException.class) public void testGetTokenWrongUsername() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, "wrong"); - tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, PluginHelper.PASSWORD_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, "wrong"); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, ""); this.identityOpenStack.createToken(tokenAttributes); } @Test(expected = OCCIException.class) public void testGetTokenWrongPassword() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, PluginHelper.USERNAME_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_PASS, "worng"); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, ""); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, "worng"); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, ""); this.identityOpenStack.createToken(tokenAttributes); } } \ No newline at end of file diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 50f0d5cd..43ddb718 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -31,25 +31,18 @@ public class KeystoneApplication extends Application { public static String TARGET_TOKEN_POST = "/v2.0/tokens"; public static String TARGET_TOKEN_GET = "/v2.0/tokens/{tokenId}"; - private Map tokenToUser; + private Map accessIdToUser; - private String usernameAdmin; - private String passwordAdmin; - private String tenantName; - private String validToken; + private String userPassword; private Token defaultToken; public KeystoneApplication() { - this.tokenToUser = new HashMap(); + this.accessIdToUser = new HashMap(); } - public KeystoneApplication(String usernameAdmin, String passwordAdmin, String tenantName, - String validToken, Token defaultToken) { - this.tokenToUser = new HashMap(); - this.tenantName = tenantName; - this.validToken = validToken; - this.usernameAdmin = usernameAdmin; - this.passwordAdmin = passwordAdmin; + public KeystoneApplication(Token defaultToken, String userPassword) { + this.accessIdToUser = new HashMap(); + this.userPassword = userPassword; this.defaultToken = defaultToken; } @@ -61,30 +54,31 @@ public Restlet createInboundRoot() { return router; } - public String getUserFromToken(String token) { - return this.tokenToUser.get(token); + public String getUserFromToken(String accessId) { + return this.accessIdToUser.get(accessId); } public void putTokenAndUser(String authToken, String user) { - this.tokenToUser.put(authToken, user); + this.accessIdToUser.put(authToken, user); } - public void checkUserByToken(String token) { - String user = this.tokenToUser.get(token); + public void checkUserByAccessId(String accessId) { + String user = accessIdToUser.get(accessId); if (user == null || user.equals("")) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } - public void authenticationCheckToken(String idToken, String tenantName) { - if (!this.validToken.equals(idToken) || !this.tenantName.equals(tenantName)) { + public void authenticationCheckToken(String accessId, String tenantName) { + if (!defaultToken.getAccessId().equals(accessId) + || !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } public void checkAuthenticationCredentials(String username, String password, String tenantName) { - if (!this.usernameAdmin.equals(username) || !this.passwordAdmin.equals(password) - || !this.tenantName.equals(tenantName)) { + if (!defaultToken.getUser().equals(username) || !this.userPassword.equals(password) + || !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } @@ -100,7 +94,7 @@ public String fetch() { KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); String token = req.getHeaders().getValues(OCCIHeaders.X_AUTH_TOKEN); - keyStoneApplication.checkUserByToken(token); + keyStoneApplication.checkUserByAccessId(token); String user = keyStoneApplication.getUserFromToken(token); return mountJSONResponseUserPerToken(token, user); } @@ -136,8 +130,8 @@ public Representation post(Representation entity) { private String mountJSONResponseAuthenticateToken(Token token) { try { String tokenAccessId = token.getAccessId(); - String tenantId = token.get(OCCIHeaders.X_TOKEN_TENANT_ID); - String tenantName = token.get(OCCIHeaders.X_TOKEN_TENANT_NAME); + String tenantId = token.get(OpenStackIdentityPlugin.TENANT_ID_KEY); + String tenantName = token.get(OpenStackIdentityPlugin.TENANT_NAME_KEY); SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index 95b84e2a..c6cee093 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -5,8 +5,8 @@ import java.util.List; import java.util.Map; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; -import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.occi.util.ComputeApplication.InstanceIdGenerator; import org.mockito.Mockito; @@ -37,14 +37,12 @@ public void initializeKeystoneComponent() throws Exception { this.component.getServers().add(Protocol.HTTP, PORT_ENDPOINT); Map tokenAttributes = new HashMap(); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_ID, TENANT_ID); -// tokenAttributes.put(OCCIHeaders.X_TOKEN_USER, USERNAME_FOGBOW); - tokenAttributes.put(OCCIHeaders.X_TOKEN_TENANT_NAME, TENANT_NAME); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, TENANT_ID); + tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, TENANT_NAME); Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttributes); // TODO Refactor! We really need all these args to KeytoneApplication? - KeystoneApplication keystoneApplication = new KeystoneApplication(USERNAME_FOGBOW, - PASSWORD_FOGBOW, TENANT_NAME, ACCESS_ID, token); + KeystoneApplication keystoneApplication = new KeystoneApplication(token, PASSWORD_FOGBOW); keystoneApplication.putTokenAndUser(ACCESS_ID, USERNAME_FOGBOW); From 0f0148b18f7f89c15c11e35c8e3a8afb571a0862 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 23 May 2014 11:29:27 -0300 Subject: [PATCH 154/185] Implementing TestCli. --- .../org/fogbowcloud/manager/cli/Main.java | 19 +- .../org/fogbowcloud/manager/cli/TestCli.java | 253 ++++++++++++++++++ 2 files changed, 265 insertions(+), 7 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/cli/TestCli.java diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index f7efceca..70f5fc4b 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -26,10 +26,12 @@ public class Main { - private static String DEFAULT_URL = "http://localhost:8182"; - private static int DEFAULT_INTANCE_COUNT = 1; - private static String DEFAULT_FLAVOR = "fogbow-small"; - private static String DEFAULT_IMAGE = "fogbow-linux-x86"; + protected static String DEFAULT_URL = "http://localhost:8182"; + protected static int DEFAULT_INTANCE_COUNT = 1; + protected static String DEFAULT_FLAVOR = "fogbow-small"; + protected static String DEFAULT_IMAGE = "fogbow-linux-x86"; + + private static HttpClient client = new DefaultHttpClient(); public static void main(String[] args) throws Exception { JCommander jc = new JCommander(); @@ -157,8 +159,7 @@ private static void doRequest(String method, String endpoint, String authToken, for (Header header : additionalHeaders) { request.addHeader(header); } - - HttpClient client = new DefaultHttpClient(); + HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { @@ -167,7 +168,11 @@ private static void doRequest(String method, String endpoint, String authToken, System.out.println(response.getStatusLine().toString()); } } - + + protected static void setClient(HttpClient client) { + Main.client = client; + } + private static class Command { @Parameter(names = "--url", description = "fogbow manager url") String url = System.getenv("FOGBOW_URL") == null ? Main.DEFAULT_URL : System.getenv("FOGBOW_URL"); diff --git a/src/test/java/org/fogbowcloud/manager/cli/TestCli.java b/src/test/java/org/fogbowcloud/manager/cli/TestCli.java new file mode 100644 index 00000000..1b07e86b --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/cli/TestCli.java @@ -0,0 +1,253 @@ +package org.fogbowcloud.manager.cli; + +import org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.HttpResponseFactory; +import org.apache.http.HttpStatus; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.impl.DefaultHttpResponseFactory; +import org.apache.http.message.BasicStatusLine; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; +import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; +import org.fogbowcloud.manager.occi.core.OCCIHeaders; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatcher; +import org.mockito.Mockito; + +import com.beust.jcommander.ParameterException; + +public class TestCli { + + private Main cli; + private HttpClient client; + private HttpUriRequestMatcher matcher; + + @SuppressWarnings("static-access") + @Before + public void setUp() throws Exception { + cli = new Main(); + client = Mockito.mock(HttpClient.class); + HttpResponseFactory factory = new DefaultHttpResponseFactory(); + HttpResponse response = factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, + HttpStatus.SC_NO_CONTENT, "Return Irrelevant"), null); + Mockito.when(client.execute(Mockito.any(HttpUriRequest.class))).thenReturn(response); + cli.setClient(client); + } + + @SuppressWarnings("static-access") + @Test + public void commandGetToken() throws Exception { + final String user = "admin"; + final String password = "reverse"; + final String tenantName = "admin"; + + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/token"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader(OpenStackIdentityPlugin.USER_KEY, user); + request.addHeader(OpenStackIdentityPlugin.PASSWORD_KEY, password); + request.addHeader(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); + matcher = new HttpUriRequestMatcher(request); + + String command = "token --get --url " + Main.DEFAULT_URL + " --username " + user + + " --tenantName " + tenantName + " --password " + password; + + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test + public void commandWithoutUrl() throws Exception { + final String user = "admin"; + final String password = "reverse"; + final String tenantName = "admin"; + + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/token"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader(OpenStackIdentityPlugin.USER_KEY, user); + request.addHeader(OpenStackIdentityPlugin.PASSWORD_KEY, password); + request.addHeader(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); + matcher = new HttpUriRequestMatcher(request); + + String command = "token --get --username " + user + " --tenantName " + tenantName + + " --password " + password; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test(expected = ParameterException.class) + public void commandWrongSyntax() throws Exception { + String command = "--get --url http://localhost:8182 --username admin" + + " --tenantName admin --password reverse"; + cli.main(createArgs(command)); + } + + @SuppressWarnings("static-access") + @Test + public void commandPostRequest() throws Exception { + final String intanceCount = "2"; + final String image = "image"; + final String flavor = "flavor"; + + HttpUriRequest request = new HttpPost(Main.DEFAULT_URL + "/request"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader("Category", + "fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\""); + request.addHeader("X-OCCI-Attribute", "org.fogbowcloud.request.instance-count=" + + intanceCount); + request.addHeader("X-OCCI-Attribute", "org.fogbowcloud.request.type=one-time"); + request.addHeader("Category", flavor + + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); + request.addHeader("Category", image + + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + matcher = new HttpUriRequestMatcher(request); + + String command = "request --create --n " + intanceCount + " --url " + Main.DEFAULT_URL + + " " + "--image " + image + " --flavor " + flavor + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test + public void commandPostRequestDefaultValues() throws Exception { + HttpUriRequest request = new HttpPost(Main.DEFAULT_URL + "/request"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader("Category", + "fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\""); + request.addHeader("X-OCCI-Attribute", "org.fogbowcloud.request.instance-count=" + + Main.DEFAULT_INTANCE_COUNT); + request.addHeader("X-OCCI-Attribute", "org.fogbowcloud.request.type=one-time"); + request.addHeader("Category", Main.DEFAULT_FLAVOR + + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\""); + request.addHeader("Category", Main.DEFAULT_IMAGE + + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + matcher = new HttpUriRequestMatcher(request); + + String command = "request --create --url " + Main.DEFAULT_URL + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test + public void commandGetQuery() throws Exception { + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/-/"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + matcher = new HttpUriRequestMatcher(request); + + String command = "query --get"; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test + public void commandGetInstance() throws Exception { + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/compute/"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + matcher = new HttpUriRequestMatcher(request); + + String command = "instance --get --url " + Main.DEFAULT_URL + " " + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test + public void commandGetSpecificInstance() throws Exception { + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/compute/" + + DefaultDataTestHelper.INSTANCE_ID); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + matcher = new HttpUriRequestMatcher(request); + + String command = "instance --get --url " + Main.DEFAULT_URL + " " + "--id " + + DefaultDataTestHelper.INSTANCE_ID + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + @SuppressWarnings("static-access") + @Test + public void commandDeleteInstance() throws Exception { + HttpUriRequest request = new HttpDelete(Main.DEFAULT_URL + "/compute/" + + DefaultDataTestHelper.INSTANCE_ID); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + matcher = new HttpUriRequestMatcher(request); + + String command = "instance --delete --url " + Main.DEFAULT_URL + " " + "--id " + + DefaultDataTestHelper.INSTANCE_ID + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID; + + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(matcher)); + } + + private String[] createArgs(String command) throws Exception { + return command.trim().split(" "); + } + + class HttpUriRequestMatcher extends ArgumentMatcher { + + private HttpUriRequest request; + + public HttpUriRequestMatcher(HttpUriRequest request) { + this.request = request; + } + + public boolean matches(Object object) { + HttpUriRequest comparedRequest = (HttpUriRequest) object; + if (!this.request.getURI().equals(comparedRequest.getURI())) { + return false; + } + if (!checkHeaders(comparedRequest.getAllHeaders())) { + return false; + } + if (!this.request.getMethod().equals(comparedRequest.getMethod())) { + return false; + } + return true; + } + + public boolean checkHeaders(Header[] comparedHeaders) { + for (Header comparedHeader : comparedHeaders) { + boolean headerEquals = false; + for (Header header : this.request.getAllHeaders()) { + if (header.getName().equals(comparedHeader.getName()) + && header.getValue().equals(comparedHeader.getValue())) { + headerEquals = true; + continue; + } + } + if (!headerEquals) { + return false; + } + } + return true; + } + } +} From a2332360cfd94bc8dbc40833327972af8f873599 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Fri, 23 May 2014 16:36:23 -0300 Subject: [PATCH 155/185] Refactoring --- .../manager/core/DefaultMemberValidator.java | 11 + .../occi/request/RequestServerResource.java | 20 +- .../manager/core/TestManagerController.java | 329 ++++++++++-------- .../manager/core/util/ManagerTestHelper.java | 53 ++- .../occi/plugins/TestIdentityOpenStack.java | 16 +- .../manager/occi/util/PluginHelper.java | 17 +- 6 files changed, 259 insertions(+), 187 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java index 4358a66e..575af000 100644 --- a/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/DefaultMemberValidator.java @@ -1,9 +1,20 @@ package org.fogbowcloud.manager.core; +import java.util.Properties; + import org.fogbowcloud.manager.core.model.FederationMember; public class DefaultMemberValidator implements FederationMemberValidator { + //TODO review the real need of these constructor + public DefaultMemberValidator(){ + + } + + public DefaultMemberValidator(Properties properties){ + + } + @Override public boolean canDonateTo(FederationMember member) { return true; diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java index f7362f82..dce6b14b 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestServerResource.java @@ -27,16 +27,16 @@ public class RequestServerResource extends ServerResource { public String fetch() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); - String userToken = HeaderUtils.getAuthToken(req.getHeaders()); + String accessId = HeaderUtils.getAuthToken(req.getHeaders()); String requestId = (String) getRequestAttributes().get("requestId"); if (requestId == null) { - LOGGER.info("Getting all requests of token :" + userToken); - return generateResponse(application.getRequestsFromUser(userToken), req); + LOGGER.info("Getting all requests of token :" + accessId); + return generateResponse(application.getRequestsFromUser(accessId), req); } - LOGGER.info("Getting request(" + requestId + ") of token :" + userToken); - Request request = application.getRequest(userToken, requestId); + LOGGER.info("Getting request(" + requestId + ") of token :" + accessId); + Request request = application.getRequest(accessId, requestId); return request.toHttpMessageFormat(); } @@ -44,17 +44,17 @@ public String fetch() { public String remove() { OCCIApplication application = (OCCIApplication) getApplication(); HttpRequest req = (HttpRequest) getRequest(); - String userToken = HeaderUtils.getAuthToken(req.getHeaders()); + String accessId = HeaderUtils.getAuthToken(req.getHeaders()); String requestId = (String) getRequestAttributes().get("requestId"); if (requestId == null) { - LOGGER.info("Removing all requests of token :" + userToken); - application.removeAllRequests(userToken); + LOGGER.info("Removing all requests of token :" + accessId); + application.removeAllRequests(accessId); return ResponseConstants.OK; } - LOGGER.info("Removing request(" + requestId + ") of token :" + userToken); - application.removeRequest(userToken, requestId); + LOGGER.info("Removing request(" + requestId + ") of token :" + accessId); + application.removeRequest(accessId, requestId); return ResponseConstants.OK; } diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 29c71b24..f5a25e70 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -8,7 +8,6 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; -import java.util.Properties; import org.fogbowcloud.manager.core.model.DateUtils; import org.fogbowcloud.manager.core.model.FederationMember; @@ -17,7 +16,6 @@ import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; -import org.fogbowcloud.manager.core.ssh.SSHTunnel; import org.fogbowcloud.manager.core.util.DefaultDataTestHelper; import org.fogbowcloud.manager.core.util.ManagerTestHelper; import org.fogbowcloud.manager.occi.core.Category; @@ -39,55 +37,21 @@ public class TestManagerController { - private static final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; public static final String ACCESS_TOKEN_ID_2 = "2222CVXV23T4TG42VVCV"; - private Token userToken; private ManagerController managerController; private ManagerTestHelper managerTestHelper; private Map xOCCIAtt; - private IdentityPlugin identityPlugin; - private ComputePlugin computePlugin; @Before public void setUp() throws Exception { managerTestHelper = new ManagerTestHelper(); + managerController = managerTestHelper.createDefaultManagerController(); // default instance count value is 1 xOCCIAtt = new HashMap(); xOCCIAtt.put(RequestAttribute.INSTANCE_COUNT.getValue(), String.valueOf(RequestConstants.DEFAULT_INSTANCE_COUNT)); - - HashMap tokenAttr = new HashMap(); - userToken = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, - DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttr); - - Properties properties = new Properties(); - properties.put("federation_user_name", DefaultDataTestHelper.USER_NAME); - properties.put("federation_user_password", DefaultDataTestHelper.USER_PASS); - properties.put("federation_user_tenant_name", DefaultDataTestHelper.TENANT_NAME); - properties.put("scheduler_period", DefaultDataTestHelper.SCHEDULER_PERIOD.toString()); - properties.put("instance_monitoring_period", Long.toString(DefaultDataTestHelper.LONG_TIME)); - managerController = new ManagerController(properties); - - // mocking compute - computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenThrow( - new OCCIException(ErrorType.QUOTA_EXCEEDED, - ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); - - // mocking identity - identityPlugin = Mockito.mock(IdentityPlugin.class); - Mockito.when(identityPlugin.getToken(DefaultDataTestHelper.ACCESS_TOKEN_ID)).thenReturn(userToken); - - // mocking sshTunnel - SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); - - managerController.setIdentityPlugin(identityPlugin); - managerController.setComputePlugin(computePlugin); - managerController.setSSHTunnel(sshTunnel); } @Test @@ -97,23 +61,26 @@ public void testGetFederationMember() throws InterruptedException { Map tokenCredentials = new HashMap(); tokenCredentials.put(OpenStackIdentityPlugin.USER_KEY, DefaultDataTestHelper.USER_NAME); tokenCredentials.put(OpenStackIdentityPlugin.PASSWORD_KEY, DefaultDataTestHelper.USER_PASS); - tokenCredentials.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, DefaultDataTestHelper.TENANT_NAME); + tokenCredentials.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, + DefaultDataTestHelper.TENANT_NAME); long tokenExpirationTime = System.currentTimeMillis() + 500; Map attributesTokenReturn = new HashMap(); attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_ID_KEY, "987654321"); - attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, DefaultDataTestHelper.TENANT_NAME); - Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date( - tokenExpirationTime), attributesTokenReturn); + attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, + DefaultDataTestHelper.TENANT_NAME); + Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), + attributesTokenReturn); Token token2 = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + DefaultDataTestHelper.LONG_TIME), attributesTokenReturn); Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, token2); - Mockito.when(openStackidentityPlugin.isValid(DefaultDataTestHelper.ACCESS_TOKEN_ID)).thenReturn( - true, false); + Mockito.when(openStackidentityPlugin.isValid(DefaultDataTestHelper.ACCESS_TOKEN_ID)) + .thenReturn(true, false); managerController.setIdentityPlugin(openStackidentityPlugin); // Get new token @@ -141,19 +108,21 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { final int tokenUpdaterInterval = 100; long tokenExpirationTime = now + (4 * tokenUpdaterInterval); - Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date( - tokenExpirationTime), new HashMap()); + Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), + new HashMap()); RequestRepository requestRepository = new RequestRepository(); for (int i = 0; i < 5; i++) { - requestRepository.addRequest(DefaultDataTestHelper.USER_NAME, new Request("id" + i, token, - null, null)); + requestRepository.addRequest(DefaultDataTestHelper.USER_NAME, new Request("id" + i, + token, null, null)); } managerController.setRequests(requestRepository); // adding behaviour on identity mock Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + tokenUpdaterInterval), new HashMap()); - Mockito.when(identityPlugin.createToken(token)).thenReturn(secondToken); + Mockito.when(managerTestHelper.getIdentityPlugin().createToken(token)).thenReturn( + secondToken); // mocking date DateUtils dateUtils = Mockito.mock(DateUtils.class); @@ -180,7 +149,8 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { if (request.getState().in(RequestState.OPEN)) { Assert.assertEquals(ACCESS_TOKEN_ID_2, request.getToken().getAccessId()); @@ -193,31 +163,34 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { @Test public void testMonitorDeletedRequestWithInstance() throws InterruptedException { - Request request1 = new Request("id1", userToken, null, null); + Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request1.setState(RequestState.DELETED); - Request request2 = new Request("id2", userToken, null, null); + Request request2 = new Request("id2", managerTestHelper.getDefaultToken(), null, null); request2.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request2.setState(RequestState.DELETED); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(userToken.getUser(), request1); - requestRepository.addRequest(userToken.getUser(), request2); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request1); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request2); managerController.setRequests(requestRepository); // updating compute mock - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(DefaultDataTestHelper.INSTANCE_ID)); + Mockito.when( + managerTestHelper.getComputePlugin().getInstance(Mockito.anyString(), + Mockito.anyString())).thenReturn( + new Instance(DefaultDataTestHelper.INSTANCE_ID)); - List requestsFromUser = managerController.getRequestsFromUser(userToken - .getAccessId()); + List requestsFromUser = managerController.getRequestsFromUser(managerTestHelper + .getDefaultToken().getAccessId()); Assert.assertEquals(2, requestsFromUser.size()); Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(0).getState()); Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(1).getState()); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(userToken.getAccessId()); + requestsFromUser = managerController.getRequestsFromUser(managerTestHelper + .getDefaultToken().getAccessId()); Assert.assertEquals(2, requestsFromUser.size()); Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(0).getState()); Assert.assertEquals(RequestState.DELETED, requestsFromUser.get(1).getState()); @@ -225,63 +198,84 @@ public void testMonitorDeletedRequestWithInstance() throws InterruptedException @Test public void testMonitorDeletedRequestWithoutInstance() throws InterruptedException { - Request request1 = new Request("id1", userToken, null, null); + Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setState(RequestState.DELETED); - Request request2 = new Request("id2", userToken, null, null); + Request request2 = new Request("id2", managerTestHelper.getDefaultToken(), null, null); request2.setState(RequestState.DELETED); - Request request3 = new Request("id3", userToken, null, null); + Request request3 = new Request("id3", managerTestHelper.getDefaultToken(), null, null); request3.setState(RequestState.OPEN); RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(userToken.getUser(), request1); - requestRepository.addRequest(userToken.getUser(), request2); - requestRepository.addRequest(userToken.getUser(), request3); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request1); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request2); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request3); managerController.setRequests(requestRepository); - //updating compute mock - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - - Assert.assertEquals(3, managerController.getRequestsFromUser(userToken.getAccessId()).size()); - Assert.assertEquals(RequestState.DELETED, - managerController.getRequest(userToken.getAccessId(), "id1").getState()); - Assert.assertEquals(RequestState.DELETED, - managerController.getRequest(userToken.getAccessId(), "id2").getState()); - Assert.assertEquals(RequestState.OPEN, - managerController.getRequest(userToken.getAccessId(), "id3").getState()); + // updating compute mock + Mockito.when( + managerTestHelper.getComputePlugin().getInstance(Mockito.anyString(), + Mockito.anyString())).thenThrow( + new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + + Assert.assertEquals( + 3, + managerController.getRequestsFromUser( + managerTestHelper.getDefaultToken().getAccessId()).size()); + Assert.assertEquals( + RequestState.DELETED, + managerController.getRequest(managerTestHelper.getDefaultToken().getAccessId(), + "id1").getState()); + Assert.assertEquals( + RequestState.DELETED, + managerController.getRequest(managerTestHelper.getDefaultToken().getAccessId(), + "id2").getState()); + Assert.assertEquals( + RequestState.OPEN, + managerController.getRequest(managerTestHelper.getDefaultToken().getAccessId(), + "id3").getState()); managerController.monitorInstances(); - Assert.assertEquals(1, managerController.getRequestsFromUser(userToken.getAccessId()).size()); - Assert.assertEquals(RequestState.OPEN, - managerController.getRequestsFromUser(userToken.getAccessId()).get(0).getState()); + Assert.assertEquals( + 1, + managerController.getRequestsFromUser( + managerTestHelper.getDefaultToken().getAccessId()).size()); + Assert.assertEquals( + RequestState.OPEN, + managerController + .getRequestsFromUser(managerTestHelper.getDefaultToken().getAccessId()) + .get(0).getState()); } @Test public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedException { - Request request1 = new Request("id1", userToken, null, null); + Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", userToken, null, null); + Request request2 = new Request("id2", managerTestHelper.getDefaultToken(), null, null); request2.setState(RequestState.FULFILLED); - + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(userToken.getUser(), request1); - requestRepository.addRequest(userToken.getUser(), request2); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request1); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request2); managerController.setRequests(requestRepository); - //updating compute mock - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - - List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + // updating compute mock + Mockito.when( + managerTestHelper.getComputePlugin().getInstance(Mockito.anyString(), + Mockito.anyString())).thenThrow( + new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + + List requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); } - + managerController.monitorInstances(); - - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + + requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.CLOSED)); @@ -292,63 +286,75 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep public void testMonitorFulfilledAndPersistentRequest() throws InterruptedException { Map attributes = new HashMap(); attributes.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); - Request request1 = new Request("id1", userToken, null, attributes); + Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, attributes); request1.setState(RequestState.FULFILLED); - + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(userToken.getUser(), request1); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request1); managerController.setRequests(requestRepository); - mockRequestInstance(); - - //updating compute mock + // updating compute mock + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + managerController.setComputePlugin(computePlugin); - List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.FULFILLED, requestsFromUser.get(0).getState()); managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.OPEN, requestsFromUser.get(0).getState()); managerController.checkAndSubmitOpenRequests(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.FULFILLED, requestsFromUser.get(0).getState()); } @Test public void testMonitorFulfilledRequestWithInstance() throws InterruptedException { - Request request1 = new Request("id1", userToken, null, null); + final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; + + Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request1.setState(RequestState.FULFILLED); - Request request2 = new Request("id2", userToken, null, null); + Request request2 = new Request("id2", managerTestHelper.getDefaultToken(), null, null); request2.setInstanceId(SECOND_INSTANCE_ID); request2.setState(RequestState.FULFILLED); - + RequestRepository requestRepository = new RequestRepository(); - requestRepository.addRequest(userToken.getUser(), request1); - requestRepository.addRequest(userToken.getUser(), request2); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request1); + requestRepository.addRequest(managerTestHelper.getDefaultToken().getUser(), request2); managerController.setRequests(requestRepository); - //updating compute mock - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenReturn(new Instance(DefaultDataTestHelper.INSTANCE_ID)); - - managerController.monitorInstances(); - List requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + // updating compute mock + Mockito.when( + managerTestHelper.getComputePlugin().getInstance(Mockito.anyString(), + Mockito.anyString())).thenReturn( + new Instance(DefaultDataTestHelper.INSTANCE_ID)); + + managerController.monitorInstances(); + List requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertEquals(RequestState.FULFILLED, request.getState()); } managerController.monitorInstances(); - requestsFromUser = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + requestsFromUser = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); for (Request request : requestsFromUser) { Assert.assertTrue(request.getState().equals(RequestState.FULFILLED)); @@ -399,12 +405,13 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { public void testGetRequestsByUser() throws InterruptedException { mockRequestInstance(); - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.USER_NAME, requests.get(0).getToken().getUser()); @@ -417,12 +424,13 @@ public void testGetRequestsByUser() throws InterruptedException { public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { mockRequestInstance(); - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); @@ -430,7 +438,8 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.INSTANCE_ID); requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -447,12 +456,13 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti mockRequestInstance(); - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); @@ -462,7 +472,8 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.INSTANCE_ID); requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -477,19 +488,20 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti @SuppressWarnings("unchecked") @Test public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws InterruptedException { + final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); - //mocking compute for 2 instances - computePlugin = Mockito.mock(ComputePlugin.class); + // mocking compute for 2 instances + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID, SECOND_INSTANCE_ID); managerController.setComputePlugin(computePlugin); - - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); @@ -504,7 +516,8 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getMemberId()); // removing instance - managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.INSTANCE_ID); requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -530,7 +543,8 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr @Test public void testPersistentRequestSetOpenAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + + DefaultDataTestHelper.SCHEDULER_PERIOD; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); @@ -538,8 +552,8 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException String.valueOf(DateUtils.getDateISO8601Format(expirationRequestTime))); // creating request - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -565,8 +579,8 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException @Test public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD - + DefaultDataTestHelper.GRACE_TIME; + long expirationRequestTime = System.currentTimeMillis() + + DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); @@ -575,12 +589,13 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep mockRequestInstance(); - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); - List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); @@ -592,7 +607,8 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); // removing instance - managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.INSTANCE_ID); Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); @@ -607,7 +623,7 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep } private void mockRequestInstance() { - computePlugin = Mockito.mock(ComputePlugin.class); + ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID); @@ -616,17 +632,19 @@ private void mockRequestInstance() { @Test public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { - long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD; + long expirationRequestTime = System.currentTimeMillis() + + DefaultDataTestHelper.SCHEDULER_PERIOD; xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); // creating request - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -663,8 +681,8 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -716,10 +734,11 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); - List requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -768,8 +787,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -799,7 +818,8 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); // remove instance - managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.INSTANCE_ID); Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); @@ -829,8 +849,8 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce mockRequestInstance(); // creating request - managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), - xOCCIAtt); + managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, + new ArrayList(), xOCCIAtt); List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -862,7 +882,8 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // remove instance - managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, + DefaultDataTestHelper.INSTANCE_ID); Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index 610eaa33..427ac190 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -24,6 +24,10 @@ import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; +import org.fogbowcloud.manager.core.ssh.SSHTunnel; +import org.fogbowcloud.manager.occi.core.ErrorType; +import org.fogbowcloud.manager.occi.core.OCCIException; +import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; @@ -43,12 +47,13 @@ public class ManagerTestHelper extends DefaultDataTestHelper { private ManagerXmppComponent managerXmppComponent; private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; - private Token tokenDefault; + private Token defaultToken; public ManagerTestHelper() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, "tenantId_r4fci3qhbcy3b"); - this.tokenDefault = new Token(ACCESS_TOKEN_ID, USER_NAME, TOKEN_FUTURE_EXPIRATION, tokenAttributes); + this.defaultToken = new Token(ACCESS_TOKEN_ID, USER_NAME, TOKEN_FUTURE_EXPIRATION, + tokenAttributes); } public ResourcesInfo getResources() throws CertificateException, IOException { @@ -164,7 +169,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); - Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(tokenDefault); + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(defaultToken); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -192,14 +197,14 @@ public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Excepti managerFacade.setComputePlugin(computePlugin); managerFacade.setIdentityPlugin(identityPlugin); managerFacade.setValidator(validator); - + managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); - Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(tokenDefault); + Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(defaultToken); managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); @@ -272,4 +277,42 @@ public Properties getProperties(String path) throws IOException { public X509Certificate getCertificate() throws CertificateException, IOException { return CertificateHandlerHelper.getCertificate(getProperties()); } + + public ManagerController createDefaultManagerController() { + Properties properties = new Properties(); + properties.put("federation_user_name", DefaultDataTestHelper.USER_NAME); + properties.put("federation_user_password", DefaultDataTestHelper.USER_PASS); + properties.put("federation_user_tenant_name", DefaultDataTestHelper.TENANT_NAME); + properties.put("scheduler_period", DefaultDataTestHelper.SCHEDULER_PERIOD.toString()); + properties + .put("instance_monitoring_period", Long.toString(DefaultDataTestHelper.LONG_TIME)); + ManagerController managerController = new ManagerController(properties); + + // mocking compute + computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), + Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + + // mocking identity + identityPlugin = Mockito.mock(IdentityPlugin.class); + Mockito.when(identityPlugin.getToken(DefaultDataTestHelper.ACCESS_TOKEN_ID)).thenReturn( + defaultToken); + + // mocking sshTunnel + SSHTunnel sshTunnel = Mockito.mock(SSHTunnel.class); + + managerController.setIdentityPlugin(identityPlugin); + managerController.setComputePlugin(computePlugin); + managerController.setSSHTunnel(sshTunnel); + + return managerController; + } + + public Token getDefaultToken() { + return defaultToken; + } + } diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 9d7701d2..7a689a75 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -38,7 +38,7 @@ public void tearDown() throws Exception { @Test public void testValidToken() { - Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, + Assert.assertEquals(PluginHelper.USERNAME, this.identityOpenStack.getToken(PluginHelper.ACCESS_ID).getUser()); } @@ -49,7 +49,7 @@ public void testInvalidToken() { @Test public void testGetNameUserFromToken() { - Assert.assertEquals(PluginHelper.USERNAME_FOGBOW, + Assert.assertEquals(PluginHelper.USERNAME, this.identityOpenStack.getToken(PluginHelper.ACCESS_ID).getUser()); } @@ -61,8 +61,8 @@ public void testGetNameUserFromTokenInvalid() { @Test public void testGetToken() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME_FOGBOW); - tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.USER_PASS); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); @@ -76,8 +76,8 @@ public void testGetToken() { @Test public void testUpgradeToken() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME_FOGBOW); - tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.USER_PASS); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); @@ -100,7 +100,7 @@ public void testUpgradeToken() { public void testGetTokenWrongUsername() { Map tokenAttributes = new HashMap(); tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, "wrong"); - tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.PASSWORD_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, PluginHelper.USER_PASS); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, ""); this.identityOpenStack.createToken(tokenAttributes); } @@ -108,7 +108,7 @@ public void testGetTokenWrongUsername() { @Test(expected = OCCIException.class) public void testGetTokenWrongPassword() { Map tokenAttributes = new HashMap(); - tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME_FOGBOW); + tokenAttributes.put(OpenStackIdentityPlugin.USER_KEY, PluginHelper.USERNAME); tokenAttributes.put(OpenStackIdentityPlugin.PASSWORD_KEY, "worng"); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, ""); this.identityOpenStack.createToken(tokenAttributes); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java index c6cee093..253b0f64 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/PluginHelper.java @@ -1,6 +1,5 @@ package org.fogbowcloud.manager.occi.util; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,10 +20,8 @@ public class PluginHelper { public static final String TENANT_ID = "fc394f2ab2df4114bde39905f800dc57"; public static final String TENANT_NAME = "admin"; -// public static final Date EXPIRATION_DATE = new Date(System.currentTimeMillis() -// + TestHelperData.LONG_TIME); - public static final String USERNAME_FOGBOW = "admin"; - public static final String PASSWORD_FOGBOW = "reverse"; + public static final String USERNAME = "admin"; + public static final String USER_PASS = "reverse"; public static final int PORT_ENDPOINT = 8182; @@ -39,12 +36,12 @@ public void initializeKeystoneComponent() throws Exception { Map tokenAttributes = new HashMap(); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, TENANT_ID); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, TENANT_NAME); - Token token = new Token(ACCESS_ID, USERNAME_FOGBOW, DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttributes); + Token token = new Token(ACCESS_ID, USERNAME, + DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, tokenAttributes); - // TODO Refactor! We really need all these args to KeytoneApplication? - KeystoneApplication keystoneApplication = new KeystoneApplication(token, PASSWORD_FOGBOW); + KeystoneApplication keystoneApplication = new KeystoneApplication(token, USER_PASS); - keystoneApplication.putTokenAndUser(ACCESS_ID, USERNAME_FOGBOW); + keystoneApplication.putTokenAndUser(ACCESS_ID, USERNAME); this.component.getDefaultHost().attach(keystoneApplication); this.component.start(); @@ -62,7 +59,7 @@ public void initializeComputeComponent(List expectedInstanceIds) throws expectedInstanceIds.get(1), expectedInstanceIds.get(2), expectedInstanceIds.get(3), expectedInstanceIds.get(4)); computeApplication.setIdGenerator(idGenerator); - computeApplication.putTokenAndUser(ACCESS_ID, USERNAME_FOGBOW); + computeApplication.putTokenAndUser(ACCESS_ID, USERNAME); this.component.getDefaultHost().attach(computeApplication); this.component.start(); From 9ccade500f798db64003804890abaa4671546289 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 23 May 2014 16:59:16 -0300 Subject: [PATCH 156/185] Implementing TestCli. --- .../manager/core/ssh/DefaultSSHTunnel.java | 8 ++ .../org/fogbowcloud/manager/cli/TestCli.java | 97 +++++++++++++--- .../occi/core/ssh/TestDefaultSSHTunnel.java | 108 ++++++++++++++++++ 3 files changed, 196 insertions(+), 17 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index 1c7a4476..904619ea 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -90,4 +90,12 @@ private static boolean available(int port) { } return false; } + + public Set getTakenPorts() { + return takenPorts; + } + + public void setTakenPorts(Set takenPorts) { + this.takenPorts = takenPorts; + } } diff --git a/src/test/java/org/fogbowcloud/manager/cli/TestCli.java b/src/test/java/org/fogbowcloud/manager/cli/TestCli.java index 1b07e86b..33f4de72 100644 --- a/src/test/java/org/fogbowcloud/manager/cli/TestCli.java +++ b/src/test/java/org/fogbowcloud/manager/cli/TestCli.java @@ -24,9 +24,11 @@ public class TestCli { + private final String REQUEST_ID = "234GD0-43254435-4543T4"; + private Main cli; private HttpClient client; - private HttpUriRequestMatcher matcher; + private HttpUriRequestMatcher expectedRequest; @SuppressWarnings("static-access") @Before @@ -52,14 +54,14 @@ public void commandGetToken() throws Exception { request.addHeader(OpenStackIdentityPlugin.USER_KEY, user); request.addHeader(OpenStackIdentityPlugin.PASSWORD_KEY, password); request.addHeader(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "token --get --url " + Main.DEFAULT_URL + " --username " + user + " --tenantName " + tenantName + " --password " + password; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } @SuppressWarnings("static-access") @@ -74,13 +76,13 @@ public void commandWithoutUrl() throws Exception { request.addHeader(OpenStackIdentityPlugin.USER_KEY, user); request.addHeader(OpenStackIdentityPlugin.PASSWORD_KEY, password); request.addHeader(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "token --get --username " + user + " --tenantName " + tenantName + " --password " + password; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } @SuppressWarnings("static-access") @@ -110,14 +112,14 @@ public void commandPostRequest() throws Exception { request.addHeader("Category", image + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "request --create --n " + intanceCount + " --url " + Main.DEFAULT_URL + " " + "--image " + image + " --flavor " + flavor + " --auth-token " + DefaultDataTestHelper.ACCESS_TOKEN_ID; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } @SuppressWarnings("static-access") @@ -135,26 +137,87 @@ public void commandPostRequestDefaultValues() throws Exception { request.addHeader("Category", Main.DEFAULT_IMAGE + "; scheme=\"http://schemas.fogbowcloud.org/template/os#\"; class=\"mixin\""); request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "request --create --url " + Main.DEFAULT_URL + " --auth-token " + DefaultDataTestHelper.ACCESS_TOKEN_ID; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } + + @SuppressWarnings("static-access") + @Test + public void commandGetSpecificRequest() throws Exception { + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/request/" + REQUEST_ID); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + expectedRequest = new HttpUriRequestMatcher(request); + + String command = "request --get --url " + Main.DEFAULT_URL + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID + " --id " + REQUEST_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); + } + + @SuppressWarnings("static-access") + @Test + public void commandGetRequest() throws Exception { + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/request"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + expectedRequest = new HttpUriRequestMatcher(request); + + String command = "request --get --url " + Main.DEFAULT_URL + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); + } + + @SuppressWarnings("static-access") + @Test + public void commandDeleteRequest() throws Exception { + HttpUriRequest request = new HttpDelete(Main.DEFAULT_URL + "/request/" + REQUEST_ID); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + + request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); + expectedRequest = new HttpUriRequestMatcher(request); + + String command = "request --delete --url " + Main.DEFAULT_URL + " --auth-token " + + DefaultDataTestHelper.ACCESS_TOKEN_ID + " --id " + REQUEST_ID; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); + } @SuppressWarnings("static-access") @Test public void commandGetQuery() throws Exception { HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/-/"); request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "query --get"; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); + } + + @SuppressWarnings("static-access") + @Test + public void commandGetMember() throws Exception { + HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/members"); + request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); + expectedRequest = new HttpUriRequestMatcher(request); + + String command = "member --get"; + cli.main(createArgs(command)); + + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } @SuppressWarnings("static-access") @@ -163,13 +226,13 @@ public void commandGetInstance() throws Exception { HttpUriRequest request = new HttpGet(Main.DEFAULT_URL + "/compute/"); request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "instance --get --url " + Main.DEFAULT_URL + " " + " --auth-token " + DefaultDataTestHelper.ACCESS_TOKEN_ID; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } @SuppressWarnings("static-access") @@ -179,14 +242,14 @@ public void commandGetSpecificInstance() throws Exception { + DefaultDataTestHelper.INSTANCE_ID); request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "instance --get --url " + Main.DEFAULT_URL + " " + "--id " + DefaultDataTestHelper.INSTANCE_ID + " --auth-token " + DefaultDataTestHelper.ACCESS_TOKEN_ID; cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } @SuppressWarnings("static-access") @@ -196,7 +259,7 @@ public void commandDeleteInstance() throws Exception { + DefaultDataTestHelper.INSTANCE_ID); request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); request.addHeader(OCCIHeaders.X_AUTH_TOKEN, DefaultDataTestHelper.ACCESS_TOKEN_ID); - matcher = new HttpUriRequestMatcher(request); + expectedRequest = new HttpUriRequestMatcher(request); String command = "instance --delete --url " + Main.DEFAULT_URL + " " + "--id " + DefaultDataTestHelper.INSTANCE_ID + " --auth-token " @@ -204,7 +267,7 @@ public void commandDeleteInstance() throws Exception { cli.main(createArgs(command)); - Mockito.verify(client).execute(Mockito.argThat(matcher)); + Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); } private String[] createArgs(String command) throws Exception { diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java new file mode 100644 index 00000000..4e347059 --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java @@ -0,0 +1,108 @@ +package org.fogbowcloud.manager.occi.core.ssh; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.codec.Charsets; +import org.apache.commons.codec.binary.Base64; +import org.fogbowcloud.manager.core.ssh.DefaultSSHTunnel; +import org.fogbowcloud.manager.occi.core.Category; +import org.fogbowcloud.manager.occi.core.Token; +import org.fogbowcloud.manager.occi.request.Request; +import org.fogbowcloud.manager.occi.request.RequestConstants; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +public class TestDefaultSSHTunnel { + + private DefaultSSHTunnel defaultSSHTunnel; + + @Before + public void setUp() { + defaultSSHTunnel = new DefaultSSHTunnel(); + } + + @Test + public void create() throws FileNotFoundException, IOException { + final String host = "10.0.0.1"; + final String user = "fogbow"; + final String portRanger = "50000:59999"; + final String port = "50000"; + + String sshTunnelCmd = getScriptFogbowInjectTunnel(); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_USER#", user); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", host); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_PORT#", port); + + Properties properties = new Properties(); + properties.put("ssh_tunnel_host", host); + properties.put("ssh_tunnel_user", user); + properties.put("ssh_tunnel_port_range", portRanger); + Request request = new Request("is", new Token("accessId", "user", new Date(), + new HashMap()), new ArrayList(), + new HashMap()); + + defaultSSHTunnel.create(properties, request); + + System.out.println(defaultSSHTunnel.getTakenPorts()); + + Assert.assertTrue(request.getCategories().get(0).getTerm() + .equals(RequestConstants.USER_DATA_TERM)); + Assert.assertEquals(Base64.encodeBase64URLSafeString(sshTunnelCmd.getBytes(Charsets.UTF_8)) + .length(), request.getAttValue(DefaultSSHTunnel.USER_DATA_ATT).length()); + Assert.assertEquals(host + ":" + port, + request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT)); + } + + @Test + public void release() { + final int port = 50000; + final int port2 = 50001; + Set takenPorts = new HashSet(); + takenPorts.add(port); + takenPorts.add(port2); + defaultSSHTunnel.setTakenPorts(takenPorts); + String sshAddressAtt = "10.0.0.1:50000"; + + Map attribute = new HashMap(); + attribute.put(DefaultSSHTunnel.SSH_ADDRESS_ATT, sshAddressAtt); + Request request = new Request("id", new Token("accessId", "user", new Date(), + new HashMap()), new ArrayList(), attribute); + + Assert.assertEquals(2, defaultSSHTunnel.getTakenPorts().size()); + + defaultSSHTunnel.release(request); + + Assert.assertEquals(1, defaultSSHTunnel.getTakenPorts().size()); + } + + @SuppressWarnings("resource") + private String getScriptFogbowInjectTunnel() { + BufferedReader bufferedReader = null; + String fullText = null; + try { + bufferedReader = new BufferedReader(new FileReader("bin/fogbow-inject-tunnel")); + StringBuilder sb = new StringBuilder(); + String line = bufferedReader.readLine(); + while (line != null) { + sb.append(line); + sb.append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + fullText = sb.toString(); + } catch (Exception e) { + e.printStackTrace(); + } + return fullText; + } +} From ca88467997ea7d05cba73683a39293ef32c74aa4 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Fri, 23 May 2014 17:09:23 -0300 Subject: [PATCH 157/185] Fixing Tests. --- .../manager/occi/core/ssh/TestDefaultSSHTunnel.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java index 4e347059..d0a5fc69 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java @@ -21,17 +21,20 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; public class TestDefaultSSHTunnel { private DefaultSSHTunnel defaultSSHTunnel; + @Ignore @Before public void setUp() { defaultSSHTunnel = new DefaultSSHTunnel(); } + @Ignore @Test public void create() throws FileNotFoundException, IOException { final String host = "10.0.0.1"; @@ -54,8 +57,6 @@ public void create() throws FileNotFoundException, IOException { defaultSSHTunnel.create(properties, request); - System.out.println(defaultSSHTunnel.getTakenPorts()); - Assert.assertTrue(request.getCategories().get(0).getTerm() .equals(RequestConstants.USER_DATA_TERM)); Assert.assertEquals(Base64.encodeBase64URLSafeString(sshTunnelCmd.getBytes(Charsets.UTF_8)) @@ -64,6 +65,7 @@ public void create() throws FileNotFoundException, IOException { request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT)); } + @Ignore @Test public void release() { final int port = 50000; From a0256ad5171bcabc7a30c3e3bf956e858587d1b6 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 26 May 2014 03:39:54 +0200 Subject: [PATCH 158/185] using a fake xmpp server for tests. --- .../manager/core/util/FakeXMPPServer.java | 122 ++++++++++++++++++ .../manager/core/util/ManagerTestHelper.java | 38 +++--- .../manager/xmpp/TestIAmAlive.java | 3 +- 3 files changed, 139 insertions(+), 24 deletions(-) create mode 100644 src/test/java/org/fogbowcloud/manager/core/util/FakeXMPPServer.java diff --git a/src/test/java/org/fogbowcloud/manager/core/util/FakeXMPPServer.java b/src/test/java/org/fogbowcloud/manager/core/util/FakeXMPPServer.java new file mode 100644 index 00000000..0261316e --- /dev/null +++ b/src/test/java/org/fogbowcloud/manager/core/util/FakeXMPPServer.java @@ -0,0 +1,122 @@ +package org.fogbowcloud.manager.core.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +import org.jamppa.client.XMPPClient; +import org.jamppa.component.XMPPComponent; +import org.jivesoftware.smack.Connection; +import org.jivesoftware.smack.PacketCollector; +import org.jivesoftware.smack.PacketListener; +import org.jivesoftware.smack.XMPPConnection; +import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.util.SyncPacketSend; +import org.jivesoftware.whack.ExternalComponentManager; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.xmpp.component.Component; +import org.xmpp.packet.JID; +import org.xmpp.packet.Packet; + +public class FakeXMPPServer { + + private Map onlineEntities = new HashMap(); + private Executor executor = Executors.newCachedThreadPool(); + + private void send(final Packet p) throws Exception { + Object obj = onlineEntities.get(p.getTo().toBareJID()); + if (obj instanceof Component) { + Component comp = (Component) obj; + comp.processPacket(p); + } else if (obj instanceof XMPPClient) { + XMPPClient xmpp = (XMPPClient) obj; + XMPPConnection conn = xmpp.getConnection(); + Collection collectors = getField(Connection.class, conn, "collectors"); + for (PacketCollector packetCollector : collectors) { + Method processPacketMethod = PacketCollector.class.getDeclaredMethod( + "processPacket", Packet.class); + processPacketMethod.setAccessible(true); + processPacketMethod.invoke(packetCollector, p); + } + + Class listenerWrapperClass = Class.forName("org.jivesoftware.smack.Connection$ListenerWrapper"); + Map recvListeners = getField(Connection.class, conn, "recvListeners"); + for (final Object listenerWrapper : recvListeners.values()) { + final Method notifyListenerMethod = listenerWrapperClass.getDeclaredMethod( + "notifyListener", Packet.class); + notifyListenerMethod.setAccessible(true); + executor.execute(new Runnable() { + @Override + public void run() { + try { + notifyListenerMethod.invoke(listenerWrapper, p); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + } + } + + @SuppressWarnings("unchecked") + private T getField(Class clazz, Object o, String fieldName) + throws Exception { + Field field = clazz.getDeclaredField(fieldName); + field.setAccessible(true); + return (T) field.get(o); + } + + private void connect(String jid, Object o) { + onlineEntities.put(jid, o); + } + + public void connect(final XMPPClient client) throws XMPPException { + final String from = client.getJid().toBareJID(); + connect(from, client); + Mockito.doAnswer(createAnswer(from, 0)).when( + client).send(Mockito.any(Packet.class)); + + Mockito.doAnswer(new Answer() { + @Override + public Packet answer(InvocationOnMock invocation) throws Throwable { + Packet p = (Packet) invocation.getArguments()[0]; + XMPPConnection conn = Mockito.spy(client.getConnection()); + Mockito.doAnswer(createAnswer(from, 0)).when( + conn).sendPacket(Mockito.any(Packet.class)); + return SyncPacketSend.getReply(conn, p); + } + }).when(client).syncSend(Mockito.any(Packet.class)); + } + + private Answer createAnswer(final String from, final int packetArgIdx) { + return new Answer() { + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + Packet p = (Packet) invocation.getArguments()[packetArgIdx]; + p.setFrom(from); + send(p); + return null; + } + }; + } + + public void connect(XMPPComponent component) throws Exception { + String jid = getField(XMPPComponent.class, component, "jid"); + connect(jid, component); + ExternalComponentManager manager = Mockito.mock(ExternalComponentManager.class); + component.initialize(new JID(jid), manager); + Mockito.doAnswer(createAnswer(jid, 1)).when(manager).sendPacket( + Mockito.any(Component.class), Mockito.any(Packet.class)); + } + + public void disconnect(String jid) { + onlineEntities.remove(jid); + } +} diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index 427ac190..14b18bb9 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -31,7 +31,6 @@ import org.fogbowcloud.manager.occi.core.Token; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.jamppa.client.XMPPClient; -import org.jamppa.client.plugin.xep0077.XEP0077; import org.jamppa.component.PacketSender; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.XMPPException; @@ -48,6 +47,7 @@ public class ManagerTestHelper extends DefaultDataTestHelper { private ComputePlugin computePlugin; private IdentityPlugin identityPlugin; private Token defaultToken; + private FakeXMPPServer fakeServer = new FakeXMPPServer(); public ManagerTestHelper() { Map tokenAttributes = new HashMap(); @@ -99,18 +99,9 @@ public IQ createWhoIsAliveResponse(ArrayList aliveIds, IQ iq) public XMPPClient createXMPPClient() throws XMPPException { - XMPPClient xmppClient = new XMPPClient(CLIENT_ADRESS, CLIENT_PASS, SERVER_HOST, - SERVER_CLIENT_PORT); - XEP0077 register = new XEP0077(); - xmppClient.registerPlugin(register); - xmppClient.connect(); - try { - register.createAccount(CLIENT_ADRESS, CLIENT_PASS); - } catch (XMPPException e) { - e.printStackTrace(); - } - - xmppClient.login(); + XMPPClient xmppClient = Mockito.spy(new XMPPClient(CLIENT_ADRESS, CLIENT_PASS, SERVER_HOST, + SERVER_CLIENT_PORT)); + fakeServer.connect(xmppClient); xmppClient.process(false); return xmppClient; @@ -124,7 +115,7 @@ public Packet syncSendPacket(Packet packet) { PacketFilter responseFilter = new PacketIDFilter(packet.getID()); PacketCollector response = xmppClient.getConnection().createPacketCollector( responseFilter); - xmppClient.getConnection().sendPacket(packet); + xmppClient.send(packet); Packet result = response.nextResult(5000); response.cancel(); return result; @@ -146,6 +137,7 @@ public IdentityPlugin getIdentityPlugin() { return identityPlugin; } + @SuppressWarnings("unchecked") public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws Exception { this.computePlugin = Mockito.mock(ComputePlugin.class); @@ -163,8 +155,8 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws FederationMemberValidator validator = new DefaultMemberValidator(); managerFacade.setValidator(validator); - managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, - MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); + managerXmppComponent = Mockito.spy(new ManagerXmppComponent(MANAGER_COMPONENT_URL, + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade)); Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); @@ -174,7 +166,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); managerXmppComponent.setRendezvousAddress(CLIENT_ADRESS + SMACK_ENDING); - managerXmppComponent.connect(); + fakeServer.connect(managerXmppComponent); managerXmppComponent.process(); if (init) { managerXmppComponent.init(); @@ -182,6 +174,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws return managerXmppComponent; } + @SuppressWarnings("unchecked") public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Exception { this.computePlugin = Mockito.mock(ComputePlugin.class); @@ -198,18 +191,18 @@ public ManagerXmppComponent initializeLocalXMPPManagerComponent() throws Excepti managerFacade.setIdentityPlugin(identityPlugin); managerFacade.setValidator(validator); - managerXmppComponent = new ManagerXmppComponent(MANAGER_COMPONENT_URL, - MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade); + managerXmppComponent = Mockito.spy(new ManagerXmppComponent(MANAGER_COMPONENT_URL, + MANAGER_COMPONENT_PASS, SERVER_HOST, SERVER_COMPONENT_PORT, managerFacade)); Mockito.when(computePlugin.getResourcesInfo(Mockito.any(Token.class))).thenReturn( getResources()); Mockito.when(identityPlugin.createToken(Mockito.anyMap())).thenReturn(defaultToken); - + managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); managerXmppComponent.setRendezvousAddress(CLIENT_ADRESS + SMACK_ENDING); - managerXmppComponent.connect(); + fakeServer.connect(managerXmppComponent); managerXmppComponent.process(); return managerXmppComponent; } @@ -220,7 +213,7 @@ public IQ CreateImAliveResponse(IQ iq) { } public void shutdown() throws ComponentException { - managerXmppComponent.disconnect(); + fakeServer.disconnect(managerXmppComponent.getJID().toBareJID()); } @SuppressWarnings("unchecked") @@ -278,6 +271,7 @@ public X509Certificate getCertificate() throws CertificateException, IOException return CertificateHandlerHelper.getCertificate(getProperties()); } + @SuppressWarnings("unchecked") public ManagerController createDefaultManagerController() { Properties properties = new Properties(); properties.put("federation_user_name", DefaultDataTestHelper.USER_NAME); diff --git a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java index 0e9b395f..18c274cc 100644 --- a/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java +++ b/src/test/java/org/fogbowcloud/manager/xmpp/TestIAmAlive.java @@ -41,8 +41,7 @@ public void testIAmAlive() throws Exception { .initializeXMPPManagerComponent(false); final XMPPClient xmppClient = managerTestHelper.createXMPPClient(); - final BlockingQueue blockingQueue = new LinkedBlockingQueue( - 1); + final BlockingQueue blockingQueue = new LinkedBlockingQueue(1); final PacketListener callback = new PacketListener() { public void processPacket(Packet packet) { From 7d10148b8d1acc10b46a7260e815a5a9a7288346 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Mon, 26 May 2014 09:28:41 -0300 Subject: [PATCH 159/185] Fixing TestDefaultSHHTunnel. --- .../manager/occi/core/ssh/TestDefaultSSHTunnel.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java index d0a5fc69..662be1ae 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java @@ -28,13 +28,11 @@ public class TestDefaultSSHTunnel { private DefaultSSHTunnel defaultSSHTunnel; - @Ignore @Before public void setUp() { defaultSSHTunnel = new DefaultSSHTunnel(); } - @Ignore @Test public void create() throws FileNotFoundException, IOException { final String host = "10.0.0.1"; @@ -65,7 +63,6 @@ public void create() throws FileNotFoundException, IOException { request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT)); } - @Ignore @Test public void release() { final int port = 50000; @@ -97,8 +94,7 @@ private String getScriptFogbowInjectTunnel() { StringBuilder sb = new StringBuilder(); String line = bufferedReader.readLine(); while (line != null) { - sb.append(line); - sb.append(System.lineSeparator()); + sb.append(line + "\n"); line = bufferedReader.readLine(); } fullText = sb.toString(); From 661884fc82305f1b47821c23e70b92b4a56c4937 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Mon, 26 May 2014 12:04:02 -0300 Subject: [PATCH 160/185] Adding log and fixing remove instance from deleted request bug --- .../manager/core/ManagerController.java | 24 +++++++---- .../manager/occi/request/Request.java | 2 +- .../occi/plugins/TestComputeOpenStack.java | 40 ++++++++----------- 3 files changed, 34 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 78f16289..ec0a0ee7 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -209,13 +209,17 @@ private void removeInstance(String accessId, String instanceId, Request request) } private void instanceRemoved(Request request) { - if (isPersistent(request)) { - request.setState(RequestState.OPEN); - if (!requestSchedulerTimer.isScheduled()) { - scheduleRequests(); + if (request.getState().notIn(RequestState.DELETED)){ + if (isPersistent(request)) { + LOGGER.debug("Request: " + request + ", setting state to " + RequestState.OPEN); + request.setState(RequestState.OPEN); + if (!requestSchedulerTimer.isScheduled()) { + scheduleRequests(); + } + } else { + LOGGER.debug("Request: " + request + ", setting state to " + RequestState.CLOSED); + request.setState(RequestState.CLOSED); } - } else { - request.setState(RequestState.CLOSED); } } @@ -370,13 +374,16 @@ public void run() { protected void monitorInstances() { boolean turnOffTimer = true; - + LOGGER.info("Monitoring instances."); + for (Request request : requests.getAll()) { if (request.getState().in(RequestState.FULFILLED, RequestState.DELETED)){ turnOffTimer = false; try { + LOGGER.debug("Monitoring instance of request: " + request); getInstance(request); } catch (OCCIException e) { + LOGGER.debug("Error while getInstance of " + request.getInstanceId(), e); if (request.getState().in(RequestState.FULFILLED)){ instanceRemoved(requests.get(request.getId())); } else if (request.getState().in(RequestState.DELETED)){ @@ -408,6 +415,8 @@ public void run() { protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { List allRequests = requests.getAll(); boolean turnOffTimer = true; + + LOGGER.info("Checking and updating request token."); for (Request request : allRequests) { if (request.getState().notIn(RequestState.CLOSED, RequestState.FAILED)) { @@ -416,6 +425,7 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { - dateUtils.currentTimeMillis(); if (validInterval < 2 * tokenUpdatePeriod) { Token newToken = identityPlugin.createToken(request.getToken()); + LOGGER.info("Setting new token "+ newToken + " on request " + request.getId()); requests.get(request.getId()).setToken(newToken); } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java index 4c9023ad..200502ba 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/Request.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/Request.java @@ -74,7 +74,7 @@ public void putAttValue(String attributeName, String attributeValue) { } public String toHttpMessageFormat() { - return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId= " + instanceId; + return "RequestId=" + id + "; State=" + state.getValue() + "; InstanceId=" + instanceId; } public Token getToken() { diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java index 067fef3d..ef2f102c 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestComputeOpenStack.java @@ -30,7 +30,7 @@ public class TestComputeOpenStack { private static final String SECOND_INSTANCE_ID = "at62f3ad-67ac-56gb-8a55-adbm98cdee9f"; private static final String URL = "http://localhost:" + PluginHelper.PORT_ENDPOINT; - + private OpenStackComputePlugin computeOpenStack; private PluginHelper pluginHelper; List expectedInstanceIds; @@ -71,12 +71,10 @@ public void testRequestAValidInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); - Instance instance = computeOpenStack - .getInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID); + Instance instance = computeOpenStack.getInstance(PluginHelper.ACCESS_ID, FIRST_INSTANCE_ID); Assert.assertEquals(1, Integer.parseInt(getAttValueFromDetails( instance.toOCCIMassageFormatDetails(), ComputeApplication.CORE_ATTRIBUTE_OCCI))); @@ -119,9 +117,8 @@ public void testRequestWithoutSizeCateory() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); } @Test(expected = OCCIException.class) @@ -233,9 +230,8 @@ public void testGetAllInstanceIds() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); // check getting all instance ids instanceLocations = getInstanceLocations(computeOpenStack @@ -257,9 +253,8 @@ public void testGetAllManyInstanceIds() { RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(instanceId, computeOpenStack - .requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(instanceId, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); } // check getting all instance ids @@ -292,9 +287,8 @@ public void testGetInstanceDetails() { List categories = new ArrayList(); categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); - Assert.assertEquals(FIRST_INSTANCE_ID, - computeOpenStack.requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(FIRST_INSTANCE_ID, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); // check instance details instanceLocations = getInstanceLocations(computeOpenStack @@ -337,9 +331,8 @@ public void testDeleteAllManyInstances() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(instanceId, computeOpenStack - .requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(instanceId, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); } // check number of instances @@ -365,9 +358,8 @@ public void testDeleteOneInstance() { categories.add(new Category(RequestConstants.LINUX_X86_TERM, RequestConstants.TEMPLATE_OS_SCHEME, RequestConstants.MIXIN_CLASS)); for (String instanceId : expectedInstanceIds) { - Assert.assertEquals(instanceId, computeOpenStack - .requestInstance(PluginHelper.ACCESS_ID, categories, - new HashMap())); + Assert.assertEquals(instanceId, computeOpenStack.requestInstance( + PluginHelper.ACCESS_ID, categories, new HashMap())); } // check number of instances From 2bf216246f7f9433f72af3375beef4fdb3401172 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 26 May 2014 22:07:37 +0200 Subject: [PATCH 161/185] Fix concurrency issues with org.fogbowcloud.manager.core.TestManagerController.testMonitorFulfilledAndPersistentRequest --- .../manager/core/ManagerController.java | 6 +++--- .../manager/core/TestManagerController.java | 14 +++++++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index ec0a0ee7..4bf68035 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -214,7 +214,7 @@ private void instanceRemoved(Request request) { LOGGER.debug("Request: " + request + ", setting state to " + RequestState.OPEN); request.setState(RequestState.OPEN); if (!requestSchedulerTimer.isScheduled()) { - scheduleRequests(); + triggerRequestScheduler(); } } else { LOGGER.debug("Request: " + request + ", setting state to " + RequestState.CLOSED); @@ -350,7 +350,7 @@ public List createRequests(String accessId, List categories, requests.addRequest(userToken.getUser(), request); } if (!requestSchedulerTimer.isScheduled()) { - scheduleRequests(); + triggerRequestScheduler(); } if (!tokenUpdaterTimer.isScheduled()) { triggerTokenUpdater(); @@ -491,7 +491,7 @@ private boolean createLocalInstance(Request request) { return true; } - private void scheduleRequests() { + private void triggerRequestScheduler() { String schedulerPeriodStr = properties.getProperty("scheduler_period"); long schedulerPeriod = schedulerPeriodStr == null ? DEFAULT_SCHEDULER_PERIOD : Long .valueOf(schedulerPeriodStr); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index f5a25e70..7765f835 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -282,6 +282,7 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep } } + @SuppressWarnings("unchecked") @Test public void testMonitorFulfilledAndPersistentRequest() throws InterruptedException { Map attributes = new HashMap(); @@ -295,9 +296,6 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti // updating compute mock ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID); Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); managerController.setComputePlugin(computePlugin); @@ -314,6 +312,14 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.OPEN, requestsFromUser.get(0).getState()); + Mockito.reset(computePlugin); + Mockito.when( + computePlugin.requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))) + .thenReturn(DefaultDataTestHelper.INSTANCE_ID); + Mockito.when( + computePlugin.getInstance(Mockito.anyString(), Mockito.eq(DefaultDataTestHelper.INSTANCE_ID))) + .thenReturn(new Instance(DefaultDataTestHelper.INSTANCE_ID)); managerController.checkAndSubmitOpenRequests(); requestsFromUser = managerController @@ -622,6 +628,7 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") private void mockRequestInstance() { ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); Mockito.when( @@ -898,6 +905,7 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getMemberId()); } + @SuppressWarnings("unchecked") @Test public void testSubmitRequestForRemoteMemberValidation() { ResourcesInfo resources = Mockito.mock(ResourcesInfo.class); From bbba9564860a80bfa2cae3c271484e0a231315d2 Mon Sep 17 00:00:00 2001 From: fgan1 Date: Tue, 27 May 2014 11:24:36 -0300 Subject: [PATCH 162/185] Refatoring cli.Main. --- src/main/java/org/fogbowcloud/manager/cli/Main.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 70f5fc4b..1dc10968 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -44,8 +44,8 @@ public static void main(String[] args) throws Exception { jc.addCommand("instance", instance); TokenCommand token = new TokenCommand(); jc.addCommand("token", token); - QueryCommand query = new QueryCommand(); - jc.addCommand("query", query); + ResourceCommand resource = new ResourceCommand(); + jc.addCommand("resource", resource); jc.setProgramName("fogbow-cli"); jc.parse(args); @@ -130,7 +130,7 @@ public static void main(String[] args) throws Exception { headers.add(new BasicHeader(OpenStackIdentityPlugin.TENANT_NAME_KEY, token.tenantName)); doRequest("get", url + "/token", null, headers); - } else if (parsedCommand.equals("query")) { + } else if (parsedCommand.equals("resource")) { String url = token.url; doRequest("get", url + "/-/", null); @@ -241,7 +241,7 @@ private static class TokenCommand extends Command { } @Parameters(separators = "=", commandDescription = "Resources Fogbow") - private static class QueryCommand extends Command { + private static class ResourceCommand extends Command { @Parameter(names = "--get", description = "Get all resources") Boolean get = false; } From 80cc311586812383ce77779759e4fecf76e9c307 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Tue, 27 May 2014 15:33:09 -0300 Subject: [PATCH 163/185] Adding comments in tests and reviewing mock objects --- .../manager/occi/request/RequestState.java | 3 +- .../org/fogbowcloud/manager/cli/TestCli.java | 2 +- .../manager/core/TestManagerController.java | 268 ++++++++++++------ 3 files changed, 185 insertions(+), 88 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java index 12954da3..d3fba5ef 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java +++ b/src/main/java/org/fogbowcloud/manager/occi/request/RequestState.java @@ -10,8 +10,7 @@ public enum RequestState { * Fulfilled: The request is currently active (fulfilled) and has an * associated Instance. * - * Canceled: The request is canceled because the request went past its - * expiration date. + * Deleted: The request was deleted, but it still has a instance related to it. * * Closed: The request either completed (a Instance was launched and * subsequently was interrupted or terminated), or was not fulfilled within diff --git a/src/test/java/org/fogbowcloud/manager/cli/TestCli.java b/src/test/java/org/fogbowcloud/manager/cli/TestCli.java index 33f4de72..dee6c44a 100644 --- a/src/test/java/org/fogbowcloud/manager/cli/TestCli.java +++ b/src/test/java/org/fogbowcloud/manager/cli/TestCli.java @@ -201,7 +201,7 @@ public void commandGetQuery() throws Exception { request.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.OCCI_CONTENT_TYPE); expectedRequest = new HttpUriRequestMatcher(request); - String command = "query --get"; + String command = "resource --get"; cli.main(createArgs(command)); Mockito.verify(client).execute(Mockito.argThat(expectedRequest)); diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 7765f835..e90f31c7 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -46,6 +46,12 @@ public class TestManagerController { @Before public void setUp() throws Exception { managerTestHelper = new ManagerTestHelper(); + /* + * Default manager controller: computePlugin.requestInstance returns + * QuotaExceededException identityPlugin.getToken(AccessId) returns + * defaulToken schedulerPeriod and monitoringPeriod are long time (one + * day) + */ managerController = managerTestHelper.createDefaultManagerController(); // default instance count value is 1 @@ -56,8 +62,6 @@ public void setUp() throws Exception { @Test public void testGetFederationMember() throws InterruptedException { - OpenStackIdentityPlugin openStackidentityPlugin = Mockito - .mock(OpenStackIdentityPlugin.class); Map tokenCredentials = new HashMap(); tokenCredentials.put(OpenStackIdentityPlugin.USER_KEY, DefaultDataTestHelper.USER_NAME); tokenCredentials.put(OpenStackIdentityPlugin.PASSWORD_KEY, DefaultDataTestHelper.USER_PASS); @@ -70,15 +74,18 @@ public void testGetFederationMember() throws InterruptedException { attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_ID_KEY, "987654321"); attributesTokenReturn.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, DefaultDataTestHelper.TENANT_NAME); - Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, + + Token firstToken = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), attributesTokenReturn); - - Token token2 = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( + Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + DefaultDataTestHelper.LONG_TIME), attributesTokenReturn); - Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(token, - token2); + // mocking identity plugin + OpenStackIdentityPlugin openStackidentityPlugin = Mockito + .mock(OpenStackIdentityPlugin.class); + Mockito.when(openStackidentityPlugin.createToken(tokenCredentials)).thenReturn(firstToken, + secondToken); Mockito.when(openStackidentityPlugin.isValid(DefaultDataTestHelper.ACCESS_TOKEN_ID)) .thenReturn(true, false); managerController.setIdentityPlugin(openStackidentityPlugin); @@ -95,7 +102,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), DateUtils dateUtils = Mockito.mock(DateUtils.class); Mockito.when(dateUtils.currentTimeMillis()).thenReturn( tokenExpirationTime + DefaultDataTestHelper.GRACE_TIME); - token.setDateUtils(dateUtils); + firstToken.setDateUtils(dateUtils); // Get new token accessToken = managerController.getFederationUserToken().getAccessId(); @@ -108,20 +115,22 @@ public void testcheckAndUpdateRequestToken() throws InterruptedException { final int tokenUpdaterInterval = 100; long tokenExpirationTime = now + (4 * tokenUpdaterInterval); - Token token = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, + Token firstToken = new Token(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), new HashMap()); + + // setting request repository RequestRepository requestRepository = new RequestRepository(); for (int i = 0; i < 5; i++) { requestRepository.addRequest(DefaultDataTestHelper.USER_NAME, new Request("id" + i, - token, null, null)); + firstToken, null, null)); } managerController.setRequests(requestRepository); // adding behaviour on identity mock Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + tokenUpdaterInterval), new HashMap()); - Mockito.when(managerTestHelper.getIdentityPlugin().createToken(token)).thenReturn( + Mockito.when(managerTestHelper.getIdentityPlugin().createToken(firstToken)).thenReturn( secondToken); // mocking date @@ -131,6 +140,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); + // check if requests has firstToken List requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { @@ -149,6 +159,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); + // check if open requests updated to secondToken requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { @@ -163,6 +174,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), @Test public void testMonitorDeletedRequestWithInstance() throws InterruptedException { + // setting request repository Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request1.setState(RequestState.DELETED); @@ -181,6 +193,7 @@ public void testMonitorDeletedRequestWithInstance() throws InterruptedException Mockito.anyString())).thenReturn( new Instance(DefaultDataTestHelper.INSTANCE_ID)); + // checking deleted requests List requestsFromUser = managerController.getRequestsFromUser(managerTestHelper .getDefaultToken().getAccessId()); Assert.assertEquals(2, requestsFromUser.size()); @@ -189,6 +202,7 @@ public void testMonitorDeletedRequestWithInstance() throws InterruptedException managerController.monitorInstances(); + // checking request was not removed requestsFromUser = managerController.getRequestsFromUser(managerTestHelper .getDefaultToken().getAccessId()); Assert.assertEquals(2, requestsFromUser.size()); @@ -198,6 +212,7 @@ public void testMonitorDeletedRequestWithInstance() throws InterruptedException @Test public void testMonitorDeletedRequestWithoutInstance() throws InterruptedException { + // setting request repository Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setState(RequestState.DELETED); Request request2 = new Request("id2", managerTestHelper.getDefaultToken(), null, null); @@ -217,6 +232,7 @@ public void testMonitorDeletedRequestWithoutInstance() throws InterruptedExcepti Mockito.anyString())).thenThrow( new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + // checking requests Assert.assertEquals( 3, managerController.getRequestsFromUser( @@ -236,6 +252,7 @@ public void testMonitorDeletedRequestWithoutInstance() throws InterruptedExcepti managerController.monitorInstances(); + // checking deleted request was removed Assert.assertEquals( 1, managerController.getRequestsFromUser( @@ -249,6 +266,7 @@ public void testMonitorDeletedRequestWithoutInstance() throws InterruptedExcepti @Test public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedException { + // setting request repository Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setState(RequestState.FULFILLED); Request request2 = new Request("id2", managerTestHelper.getDefaultToken(), null, null); @@ -265,6 +283,7 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep Mockito.anyString())).thenThrow( new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + // checking if requests were fulfilled List requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); @@ -274,6 +293,7 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep managerController.monitorInstances(); + // checking if requests were closed requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); @@ -287,6 +307,8 @@ public void testMonitorFulfilledRequestWithoutInstance() throws InterruptedExcep public void testMonitorFulfilledAndPersistentRequest() throws InterruptedException { Map attributes = new HashMap(); attributes.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); + + // setting request repository Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, attributes); request1.setState(RequestState.FULFILLED); @@ -295,11 +317,12 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti managerController.setRequests(requestRepository); // updating compute mock - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when(computePlugin.getInstance(Mockito.anyString(), Mockito.anyString())) - .thenThrow(new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - managerController.setComputePlugin(computePlugin); + Mockito.when( + managerTestHelper.getComputePlugin().getInstance(Mockito.anyString(), + Mockito.anyString())).thenThrow( + new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); + // checking if request is fulfilled List requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); @@ -312,14 +335,18 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti Assert.assertEquals(1, requestsFromUser.size()); Assert.assertEquals(RequestState.OPEN, requestsFromUser.get(0).getState()); - Mockito.reset(computePlugin); + // updating compute mock + Mockito.reset(managerTestHelper.getComputePlugin()); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), - Mockito.any(List.class), Mockito.any(Map.class))) - .thenReturn(DefaultDataTestHelper.INSTANCE_ID); + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenReturn( + DefaultDataTestHelper.INSTANCE_ID); Mockito.when( - computePlugin.getInstance(Mockito.anyString(), Mockito.eq(DefaultDataTestHelper.INSTANCE_ID))) - .thenReturn(new Instance(DefaultDataTestHelper.INSTANCE_ID)); + managerTestHelper.getComputePlugin().getInstance(Mockito.anyString(), + Mockito.eq(DefaultDataTestHelper.INSTANCE_ID))).thenReturn( + new Instance(DefaultDataTestHelper.INSTANCE_ID)); + + // getting instance for request managerController.checkAndSubmitOpenRequests(); requestsFromUser = managerController @@ -332,6 +359,7 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti public void testMonitorFulfilledRequestWithInstance() throws InterruptedException { final String SECOND_INSTANCE_ID = "rt22e67-5fgt-457a-3rt6-gt78124fhj9p"; + // setting request repository Request request1 = new Request("id1", managerTestHelper.getDefaultToken(), null, null); request1.setInstanceId(DefaultDataTestHelper.INSTANCE_ID); request1.setState(RequestState.FULFILLED); @@ -351,6 +379,8 @@ public void testMonitorFulfilledRequestWithInstance() throws InterruptedExceptio new Instance(DefaultDataTestHelper.INSTANCE_ID)); managerController.monitorInstances(); + + // checking if requests were fulfilled yet List requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); @@ -359,6 +389,8 @@ public void testMonitorFulfilledRequestWithInstance() throws InterruptedExceptio } managerController.monitorInstances(); + + // checking if request state did not change requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); @@ -411,14 +443,15 @@ public void testGetManyItemsFromIQ() throws CertificateException, IOException { public void testGetRequestsByUser() throws InterruptedException { mockRequestInstance(); + // creating request managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - managerController.checkAndSubmitOpenRequests(); List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + // checking if request was rightly created Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.USER_NAME, requests.get(0).getToken().getUser()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); @@ -430,19 +463,23 @@ public void testGetRequestsByUser() throws InterruptedException { public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedException { mockRequestInstance(); + // creating request managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - managerController.checkAndSubmitOpenRequests(); + // checking if request was rightly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); + // updating compute mock + Mockito.doNothing().when(managerTestHelper.getComputePlugin()).removeInstance( + DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // removing instance managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); @@ -457,19 +494,18 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio @Test public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedException { + mockRequestInstance(); xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); - mockRequestInstance(); - + // creating request managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - managerController.checkAndSubmitOpenRequests(); + // checking if request was rightly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -477,12 +513,21 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); + // updating compute mock + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + Mockito.doNothing().when(managerTestHelper.getComputePlugin()).removeInstance( + DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // removing instance managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // checking request state was set to open requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -498,22 +543,19 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); - // mocking compute for 2 instances - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); - Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID, - SECOND_INSTANCE_ID); - managerController.setComputePlugin(computePlugin); + // mocking compute + mockRequestInstance(); + // creating requests managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + managerController.checkAndSubmitOpenRequests(); + // Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + + // DefaultDataTestHelper.GRACE_TIME); - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - + // checking if request was fulfilled with instanceID List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -521,12 +563,22 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); + // updating compute mock + Mockito.reset(managerTestHelper.getComputePlugin()); + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + Mockito.doNothing().when(managerTestHelper.getComputePlugin()).removeInstance( + DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // removing instance managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // checking if request state was to open requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -534,11 +586,19 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // updating compute mock + Mockito.reset(managerTestHelper.getComputePlugin()); + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenReturn( + SECOND_INSTANCE_ID); + // getting second instance - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 2); + // Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 2); + managerController.checkAndSubmitOpenRequests(); + // checking if request was fulfilled with secondInstance requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(SECOND_INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -552,6 +612,7 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD; + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), @@ -561,9 +622,9 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + // checking if request is OPEN List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -571,10 +632,12 @@ public void testPersistentRequestSetOpenAndClosed() throws InterruptedException Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // waiting expiration time Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - + managerController.checkAndSubmitOpenRequests(); requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); + // checking if request was closed Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -588,6 +651,7 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME; + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.PERSISTENT.getValue())); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), @@ -595,14 +659,16 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep mockRequestInstance(); + // creating request managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); + managerController.checkAndSubmitOpenRequests(); + // checking request is fulfilled List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -610,16 +676,26 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep Assert.assertEquals(RequestState.FULFILLED, requests.get(0).getState()); Assert.assertNull(requests.get(0).getMemberId()); + // waiting expiration time Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); + // updating compute mock + Mockito.reset(managerTestHelper.getComputePlugin()); + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + Mockito.doNothing().when(managerTestHelper.getComputePlugin()).removeInstance( + DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // removing instance managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + managerController.checkAndSubmitOpenRequests(); - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD); - + // checking if request state was set to closed requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -630,11 +706,11 @@ public void testPersistentRequestSetFulfilledAndClosed() throws InterruptedExcep @SuppressWarnings("unchecked") private void mockRequestInstance() { - ComputePlugin computePlugin = Mockito.mock(ComputePlugin.class); + Mockito.reset(managerTestHelper.getComputePlugin()); Mockito.when( - computePlugin.requestInstance(Mockito.anyString(), Mockito.any(List.class), - Mockito.any(Map.class))).thenReturn(DefaultDataTestHelper.INSTANCE_ID); - managerController.setComputePlugin(computePlugin); + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenReturn( + DefaultDataTestHelper.INSTANCE_ID); } @Test @@ -642,6 +718,7 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { long expirationRequestTime = System.currentTimeMillis() + DefaultDataTestHelper.SCHEDULER_PERIOD; + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); xOCCIAtt.put(RequestAttribute.VALID_UNTIL.getValue(), DateUtils.getDateISO8601Format(expirationRequestTime)); @@ -650,9 +727,9 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + // checking if request was rightly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -660,10 +737,11 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // waiting expiration time Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + // checking if request state was set to closed requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -678,6 +756,7 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); long expirationRequestTime = now + DefaultDataTestHelper.LONG_TIME; + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), String.valueOf(RequestType.ONE_TIME.getValue())); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), @@ -691,9 +770,9 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + // checking if request was rightly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -701,11 +780,12 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // sleeping for a time and request not valid yet Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); + // check request is not in valid period yet requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - - // request is not in valid period yet Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -713,11 +793,12 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // sleeping for a time and request is into valid period Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); - // request is in valid period + // check request is in valid period requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -732,6 +813,7 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); long expirationRequestTime = now + DefaultDataTestHelper.LONG_TIME; + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); @@ -744,9 +826,9 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); + // checking if request was rightly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -754,11 +836,12 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // sleeping for a time and request not valid yet Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); + // check request is not in valid period yet requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - - // request is not in valid period yet Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -766,11 +849,12 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // sleeping for a time and request is into valid period Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); - // request is in valid period + // check request is in valid period requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -785,6 +869,7 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); @@ -797,14 +882,12 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - + // waiting for a time and request is not valid yet Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - // request is not in valid period yet + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -812,11 +895,11 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // waiting for a time and request is into valid period Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - // request is in valid period + // checking is request is fulfilled requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -824,15 +907,24 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - // remove instance + // updating compute mock + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + Mockito.doNothing().when(managerTestHelper.getComputePlugin()).removeInstance( + DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + + // removing instance managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // waiting for a time and request is not into valid period anymore Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - // request is not in valid period anymore + // checking if request is not in valid period anymore requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -847,6 +939,7 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); + // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); xOCCIAtt.put(RequestAttribute.VALID_FROM.getValue(), DateUtils.getDateISO8601Format(startRequestTime)); @@ -859,14 +952,12 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - List requests = managerController - .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - + // waiting for a time and request is not valid yet Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - // request is not in valid period yet + List requests = managerController + .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -874,11 +965,11 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); + // waiting for a time and request is into valid period Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - // request is in valid period + // checking is request is fulfilled requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); @@ -886,17 +977,24 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + // updating compute mock + Mockito.when( + managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), + Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( + new OCCIException(ErrorType.QUOTA_EXCEEDED, + ResponseConstants.QUOTA_EXCEEDED_FOR_INSTANCES)); + Mockito.doNothing().when(managerTestHelper.getComputePlugin()).removeInstance( + DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - // remove instance + // removing instance managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); + // waiting for a time and request is not into valid period anymore Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - // request is not in valid period anymore + // checking if request is not in valid period anymore requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), requests.get(0).getAttValue(RequestAttribute.TYPE.getValue())); From 0c47f01c4f5a052fc57782e01a84f82ff3989d4d Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Tue, 27 May 2014 22:15:32 +0200 Subject: [PATCH 164/185] Fixing docs. --- .../manager/core/TestManagerController.java | 53 ++++++++++--------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index e90f31c7..c660014f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -46,11 +46,12 @@ public class TestManagerController { @Before public void setUp() throws Exception { managerTestHelper = new ManagerTestHelper(); + /* - * Default manager controller: computePlugin.requestInstance returns - * QuotaExceededException identityPlugin.getToken(AccessId) returns - * defaulToken schedulerPeriod and monitoringPeriod are long time (one - * day) + * Default manager controller: + * computePlugin.requestInstance always throws QuotaExceededException + * identityPlugin.getToken(AccessId) always returns DefaultDataTestHelper.ACCESS_TOKEN_ID + * schedulerPeriod and monitoringPeriod are long enough (a day) to avoid reeschudeling */ managerController = managerTestHelper.createDefaultManagerController(); @@ -127,7 +128,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), } managerController.setRequests(requestRepository); - // adding behaviour on identity mock + // adding behaviour to identity mock Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + tokenUpdaterInterval), new HashMap()); Mockito.when(managerTestHelper.getIdentityPlugin().createToken(firstToken)).thenReturn( @@ -140,7 +141,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - // check if requests has firstToken + // check if requests have firstToken List requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { @@ -159,7 +160,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), managerController.checkAndUpdateRequestToken(tokenUpdaterInterval); - // check if open requests updated to secondToken + // check if open requests have been updated to secondToken requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); for (Request request : requestsFromUser) { @@ -202,7 +203,7 @@ public void testMonitorDeletedRequestWithInstance() throws InterruptedException managerController.monitorInstances(); - // checking request was not removed + // making sure the requests were not removed requestsFromUser = managerController.getRequestsFromUser(managerTestHelper .getDefaultToken().getAccessId()); Assert.assertEquals(2, requestsFromUser.size()); @@ -232,7 +233,7 @@ public void testMonitorDeletedRequestWithoutInstance() throws InterruptedExcepti Mockito.anyString())).thenThrow( new OCCIException(ErrorType.NOT_FOUND, ResponseConstants.NOT_FOUND)); - // checking requests + // checking if requests still have the initial state Assert.assertEquals( 3, managerController.getRequestsFromUser( @@ -252,7 +253,7 @@ public void testMonitorDeletedRequestWithoutInstance() throws InterruptedExcepti managerController.monitorInstances(); - // checking deleted request was removed + // checking if deleted requests were removed Assert.assertEquals( 1, managerController.getRequestsFromUser( @@ -330,6 +331,7 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti managerController.monitorInstances(); + // checking if request has lost its instance requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); @@ -349,6 +351,7 @@ public void testMonitorFulfilledAndPersistentRequest() throws InterruptedExcepti // getting instance for request managerController.checkAndSubmitOpenRequests(); + // checking if request has been fulfilled again requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requestsFromUser.size()); @@ -380,7 +383,7 @@ public void testMonitorFulfilledRequestWithInstance() throws InterruptedExceptio managerController.monitorInstances(); - // checking if requests were fulfilled yet + // checking if requests are still fulfilled List requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); @@ -390,7 +393,7 @@ public void testMonitorFulfilledRequestWithInstance() throws InterruptedExceptio managerController.monitorInstances(); - // checking if request state did not change + // checking if requests' state haven't been changed requestsFromUser = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(2, requestsFromUser.size()); @@ -451,7 +454,7 @@ public void testGetRequestsByUser() throws InterruptedException { List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); - // checking if request was rightly created + // checking if request was created Assert.assertEquals(1, requests.size()); Assert.assertEquals(DefaultDataTestHelper.USER_NAME, requests.get(0).getToken().getUser()); Assert.assertEquals(DefaultDataTestHelper.INSTANCE_ID, requests.get(0).getInstanceId()); @@ -468,7 +471,7 @@ public void testOneTimeRequestSetFulfilledAndClosed() throws InterruptedExceptio new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - // checking if request was rightly created + // checking if request was properly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -503,7 +506,7 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - // checking if request was rightly created + // checking if request was properly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -577,7 +580,7 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - // checking if request state was to open + // checking if request state was set to open requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -727,7 +730,7 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - // checking if request was rightly created + // checking if request was properly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -770,7 +773,7 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - // checking if request was rightly created + // checking if request was properly created List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -784,7 +787,7 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); managerController.checkAndSubmitOpenRequests(); - // check request is not in valid period yet + // check that request is not in valid period yet requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -793,11 +796,11 @@ public void testOneTimeRequestWithValidFromAttInFuture() throws InterruptedExcep Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - // sleeping for a time and request is into valid period + // sleeping for the scheduler period and submitting request Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); managerController.checkAndSubmitOpenRequests(); - // check request is in valid period + // check if request is in valid period requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.ONE_TIME.getValue(), @@ -849,11 +852,11 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - // sleeping for a time and request is into valid period + // sleeping for the scheduler period and submitting request Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); managerController.checkAndSubmitOpenRequests(); - // check request is in valid period + // check if request is in valid period requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); Assert.assertEquals(RequestType.PERSISTENT.getValue(), @@ -895,7 +898,7 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getInstanceId()); Assert.assertNull(requests.get(0).getMemberId()); - // waiting for a time and request is into valid period + // sleeping for the scheduler period and submitting request Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // checking is request is fulfilled @@ -990,7 +993,7 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce managerController.removeInstance(DefaultDataTestHelper.ACCESS_TOKEN_ID, DefaultDataTestHelper.INSTANCE_ID); - // waiting for a time and request is not into valid period anymore + // waiting for the scheduler period so that request is not into valid period anymore Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); // checking if request is not in valid period anymore From e955079e5b61e02f6e1bad1329df19c83c28df89 Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 28 May 2014 10:22:49 -0300 Subject: [PATCH 165/185] Creating default properties for all plugins. Solves #49 --- manager.conf.example | 1 + .../java/org/fogbowcloud/manager/Main.java | 37 +++++++++++++++---- .../manager/core/ManagerController.java | 2 +- .../core/RestrictCAsMemberValidator.java | 36 +++++++++++++++--- 4 files changed, 61 insertions(+), 15 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index aa760271..d3688f61 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -21,6 +21,7 @@ federation_user_password=fogbow federation_user_tenant_name=demo member_validator=org.fogbowcloud.manager.core.DefaultMemberValidator +member_validator_ca_dir= cert_path= diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 418ebbd9..87ca3257 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -3,29 +3,50 @@ import java.io.FileInputStream; import java.util.Properties; +import org.apache.log4j.Logger; +import org.fogbowcloud.manager.core.DefaultMemberValidator; import org.fogbowcloud.manager.core.FederationMemberValidator; import org.fogbowcloud.manager.core.ManagerController; import org.fogbowcloud.manager.core.plugins.ComputePlugin; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackComputePlugin; +import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.OCCIApplication; import org.fogbowcloud.manager.xmpp.ManagerXmppComponent; import org.restlet.Component; import org.restlet.data.Protocol; public class Main { - - public static void main(String[] args) throws Exception { + + private static final Logger LOGGER = Logger.getLogger(Main.class); + + public static void main(String[] args) throws Exception { Properties properties = new Properties(); FileInputStream input = new FileInputStream(args[0]); properties.load(input); - ComputePlugin computePlugin = (ComputePlugin) createInstance( - "compute_class", properties); - IdentityPlugin identityPlugin = (IdentityPlugin) createInstance( - "identity_class", properties); + ComputePlugin computePlugin = new OpenStackComputePlugin(properties); + try { + computePlugin = (ComputePlugin) createInstance( + "compute_class", properties); + } catch (Exception e) { + LOGGER.warn("Compute Plugin not especified in the properties."); + } + IdentityPlugin identityPlugin = new OpenStackIdentityPlugin(properties); + try { + identityPlugin = (IdentityPlugin) createInstance( + "identity_class", properties); + } catch (Exception e) { + LOGGER.warn("Identity Plugin not especified in the properties."); + } - FederationMemberValidator validator = (FederationMemberValidator) createInstance( - "member_validator", properties); + FederationMemberValidator validator = new DefaultMemberValidator(); + try { + validator = (FederationMemberValidator) createInstance( + "member_validator", properties); + } catch (Exception e) { + LOGGER.warn("Member Validator not especified in the properties."); + } ManagerController facade = new ManagerController(properties); facade.setComputePlugin(computePlugin); diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index ec0a0ee7..7a8dec86 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -53,7 +53,7 @@ public class ManagerController { private IdentityPlugin identityPlugin; private Properties properties; private PacketSender packetSender; - private FederationMemberValidator validator = new RestrictCAsMemberValidator(); + private FederationMemberValidator validator = new DefaultMemberValidator(); private DateUtils dateUtils = new DateUtils(); private SSHTunnel sshTunnel = new DefaultSSHTunnel(); diff --git a/src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java b/src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java index 45db8068..2dd5d5d3 100644 --- a/src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java +++ b/src/main/java/org/fogbowcloud/manager/core/RestrictCAsMemberValidator.java @@ -1,16 +1,41 @@ package org.fogbowcloud.manager.core; +import java.io.File; +import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.LinkedList; import java.util.List; +import java.util.Properties; +import org.apache.log4j.Logger; import org.fogbowcloud.manager.core.model.FederationMember; -public class RestrictCAsMemberValidator implements - FederationMemberValidator { +public class RestrictCAsMemberValidator implements FederationMemberValidator { - List validCAs = new LinkedList(); + private static final Logger LOGGER = Logger + .getLogger(RestrictCAsMemberValidator.class); + private List validCAs; + public RestrictCAsMemberValidator(Properties properties) { + String caDir = properties.getProperty("member_validator_ca_dir"); + File caDirFile = new File(caDir); + List validCAsList = new LinkedList(); + for (File caFile : caDirFile.listFiles()) { + try { + X509Certificate certificate = CertificateHandlerHelper + .getCertificate(caFile.getAbsolutePath()); + validCAsList.add(certificate); + } catch (CertificateException e) { + LOGGER.warn("Failed to load CA certificate file.", e); + } + } + setValidCAs(validCAsList); + } + + protected RestrictCAsMemberValidator() { + + } + @Override public boolean canDonateTo(FederationMember member) { if (member == null) { @@ -38,9 +63,9 @@ public boolean canReceiveFrom(FederationMember member) { if (member == null) { return false; } - + X509Certificate cert = member.getResourcesInfo().getCert(); - + try { cert.checkValidity(); } catch (Exception e) { @@ -59,7 +84,6 @@ public boolean canReceiveFrom(FederationMember member) { public void setValidCAs(List list) { this.validCAs = list; - } } From 2035f6c8f2761451ce1df731ee69b303ec6c981d Mon Sep 17 00:00:00 2001 From: leticiamaia Date: Wed, 28 May 2014 10:26:58 -0300 Subject: [PATCH 166/185] Creating Default properties for plugins. Fixes #49 --- src/main/java/org/fogbowcloud/manager/Main.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/Main.java b/src/main/java/org/fogbowcloud/manager/Main.java index 87ca3257..1804c9f6 100644 --- a/src/main/java/org/fogbowcloud/manager/Main.java +++ b/src/main/java/org/fogbowcloud/manager/Main.java @@ -78,5 +78,4 @@ private static Object createInstance(String propName, Properties properties) return Class.forName(properties.getProperty(propName)) .getConstructor(Properties.class).newInstance(properties); } - } From c34763067d9a92b3f4701aa40a2ed4ee67329377 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Wed, 28 May 2014 16:05:53 -0300 Subject: [PATCH 167/185] Fixing openstack date format bug --- .../manager/core/ManagerController.java | 22 +++++++----- .../openstack/OpenStackIdentityPlugin.java | 36 +++++++++++++++++-- .../fogbowcloud/manager/occi/core/Token.java | 2 +- .../manager/core/TestManagerController.java | 3 -- .../occi/plugins/TestIdentityOpenStack.java | 16 ++++++--- .../occi/util/KeystoneApplication.java | 8 ++--- 6 files changed, 63 insertions(+), 24 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 4bf68035..b5d44ef0 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -293,6 +293,7 @@ protected Token getFederationUserToken() { return this.federationUserToken; } + //TODO Think about getting token independent of OpenStackPlugin Map federationUserCredentials = new HashMap(); String username = properties.getProperty("federation_user_name"); String password = properties.getProperty("federation_user_password"); @@ -419,15 +420,20 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { LOGGER.info("Checking and updating request token."); for (Request request : allRequests) { - if (request.getState().notIn(RequestState.CLOSED, RequestState.FAILED)) { - turnOffTimer = false; - long validInterval = request.getToken().getExpirationDate().getTime() - - dateUtils.currentTimeMillis(); - if (validInterval < 2 * tokenUpdatePeriod) { - Token newToken = identityPlugin.createToken(request.getToken()); - LOGGER.info("Setting new token "+ newToken + " on request " + request.getId()); - requests.get(request.getId()).setToken(newToken); + try{ + if (request.getState().notIn(RequestState.CLOSED, RequestState.FAILED)) { + turnOffTimer = false; + long validInterval = request.getToken().getExpirationDate().getTime() + - dateUtils.currentTimeMillis(); + LOGGER.debug("Valid interval of requestId " + request.getId() + " is " + validInterval); + if (validInterval < 2 * tokenUpdatePeriod) { + Token newToken = identityPlugin.createToken(request.getToken()); + LOGGER.info("Setting new token "+ newToken + " on request " + request.getId()); + requests.get(request.getId()).setToken(newToken); + } } + } catch (Exception e){ + LOGGER.error("Exception while checking token.", e); } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 616ac0ce..1ec5025c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -1,9 +1,12 @@ package org.fogbowcloud.manager.core.plugins.openstack; +import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Properties; +import java.util.TimeZone; import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; @@ -28,6 +31,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { + public static final String OPEN_STACK_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX"; // keys for attributes map public static final String USER_KEY = "X-Token-User"; public static final String PASSWORD_KEY = "X-Token-Password"; @@ -49,7 +53,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String NAME_KEYSTONE = "name"; private static final int LAST_SUCCESSFUL_STATUS = 204; - private final Logger LOGGER = Logger.getLogger(OpenStackIdentityPlugin.class); + private final static Logger LOGGER = Logger.getLogger(OpenStackIdentityPlugin.class); private static String V2_ENDPOINT_PATH = "/v2.0/tokens"; private String v2Endpoint; @@ -158,7 +162,11 @@ private Token getTokenFromJson(String responseStr) { Map tokenAtt = new HashMap(); tokenAtt.put(TENANT_ID_KEY, tenantId); tokenAtt.put(TENANT_NAME_KEY, tenantName); - return new Token(token, user, DateUtils.getDateFromISO8601Format(expirationDateToken), + LOGGER.debug("json token: " + token); + LOGGER.debug("json user: " + user); + LOGGER.debug("json expirationDate: " + expirationDateToken); + LOGGER.debug("json attributes: " + tokenAtt); + return new Token(token, user, getDateFromOpenStackFormat(expirationDateToken), tokenAtt); } catch (Exception e) { LOGGER.error("Exception while getting token from json.", e); @@ -185,7 +193,11 @@ public Token getToken(String accessId) { tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, tenantId); - expirationTime = DateUtils.getDateFromISO8601Format(expirationTimeStr); + LOGGER.debug("json accessId: " + accessId); + LOGGER.debug("json user: " + user); + LOGGER.debug("json expirationDate: " + expirationTimeStr); + LOGGER.debug("json attributes: " + tokenAttributes); + expirationTime = getDateFromOpenStackFormat(expirationTimeStr); } catch (Exception e) { LOGGER.error(e); } @@ -225,4 +237,22 @@ public boolean isValid(String accessId) { return false; } } + + public static String getDateOpenStackFormat(Date date) { + SimpleDateFormat dateFormatOpenStack = new SimpleDateFormat(OPEN_STACK_DATE_FORMAT, Locale.ROOT); + String expirationDate = dateFormatOpenStack.format(date); + return expirationDate; + + } + + public static Date getDateFromOpenStackFormat(String expirationDateStr) { + SimpleDateFormat dateFormatOpenStack = new SimpleDateFormat( + OPEN_STACK_DATE_FORMAT, Locale.ROOT); + try { + return dateFormatOpenStack.parse(expirationDateStr); + } catch (Exception e) { + LOGGER.error("Exception while parsing date.", e); + return null; + } + } } diff --git a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java index df338537..bf43ee15 100644 --- a/src/main/java/org/fogbowcloud/manager/occi/core/Token.java +++ b/src/main/java/org/fogbowcloud/manager/occi/core/Token.java @@ -48,7 +48,7 @@ public void setDateUtils(DateUtils dateUtils) { public String toString() { return "AccessId: " + accessId + ", User: " + user + ", expirationDate: " + expirationDate - + " attributes: " + attributes; + + ", attributes: " + attributes; } public String getUser() { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index e90f31c7..db646c49 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -550,8 +550,6 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); managerController.checkAndSubmitOpenRequests(); - // Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + - // DefaultDataTestHelper.GRACE_TIME); // checking if request was fulfilled with instanceID List requests = managerController @@ -594,7 +592,6 @@ public void testPersistentRequestSetFulfilledAndOpenAndFulfilled() throws Interr SECOND_INSTANCE_ID); // getting second instance - // Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 2); managerController.checkAndSubmitOpenRequests(); // checking if request was fulfilled with secondInstance diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 7a689a75..6b92d651 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -66,11 +66,15 @@ public void testGetToken() { tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, PluginHelper.TENANT_NAME); Token token = this.identityOpenStack.createToken(tokenAttributes); String authToken = token.getAccessId(); + String user = token.getUser(); String tenantID = token.get(OpenStackIdentityPlugin.TENANT_ID_KEY); Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); + Assert.assertEquals(PluginHelper.USERNAME, user); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(OpenStackIdentityPlugin + .getDateOpenStackFormat(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION), + OpenStackIdentityPlugin.getDateOpenStackFormat(expirationDate)); } @Test @@ -85,15 +89,19 @@ public void testUpgradeToken() { Date expirationDate = token.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, expirationDate); - + Assert.assertEquals(OpenStackIdentityPlugin + .getDateOpenStackFormat(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION), + OpenStackIdentityPlugin.getDateOpenStackFormat(expirationDate)); + Token token2 = this.identityOpenStack.createToken(token); authToken = token2.getAccessId(); tenantID = token2.get(OpenStackIdentityPlugin.TENANT_ID_KEY); expirationDate = token2.getExpirationDate(); Assert.assertEquals(PluginHelper.ACCESS_ID, authToken); Assert.assertEquals(PluginHelper.TENANT_ID, tenantID); - Assert.assertEquals(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION, expirationDate); + Assert.assertEquals(OpenStackIdentityPlugin + .getDateOpenStackFormat(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION), + OpenStackIdentityPlugin.getDateOpenStackFormat(expirationDate)); } @Test(expected = OCCIException.class) diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 43ddb718..c4f4a056 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -2,13 +2,13 @@ import java.io.IOException; import java.text.SimpleDateFormat; +import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.apache.http.HttpStatus; -import org.fogbowcloud.manager.core.model.FederationMember; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; @@ -133,10 +133,8 @@ private String mountJSONResponseAuthenticateToken(Token token) { String tenantId = token.get(OpenStackIdentityPlugin.TENANT_ID_KEY); String tenantName = token.get(OpenStackIdentityPlugin.TENANT_NAME_KEY); - SimpleDateFormat dateFormatISO8601 = new SimpleDateFormat( - FederationMember.ISO_8601_DATE_FORMAT, Locale.ROOT); - dateFormatISO8601.setTimeZone(TimeZone.getTimeZone("GMT")); - String expirationDate = dateFormatISO8601.format(token.getExpirationDate()); + String expirationDate = OpenStackIdentityPlugin.getDateOpenStackFormat(token + .getExpirationDate()); JSONObject rootIdToken = new JSONObject(); From b604f36c2bbe7c21ab39cee4e351e63979b96473 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 29 May 2014 10:41:36 -0300 Subject: [PATCH 168/185] Changing OpenStack date foramt --- .../manager/core/plugins/openstack/OpenStackIdentityPlugin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 1ec5025c..b8a48d43 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -31,7 +31,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { - public static final String OPEN_STACK_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssX"; + public static final String OPEN_STACK_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // keys for attributes map public static final String USER_KEY = "X-Token-User"; public static final String PASSWORD_KEY = "X-Token-Password"; From d59c2ebe715dd20c952e8eca579955cd348b9d17 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 29 May 2014 12:05:59 -0300 Subject: [PATCH 169/185] Checking if computePlugin returns a null instanceId --- .../java/org/fogbowcloud/manager/core/ManagerController.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 8ec4ee7a..84576d98 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -476,6 +476,9 @@ private boolean createLocalInstance(Request request) { try { instanceId = computePlugin.requestInstance(request.getToken().getAccessId(), request.getCategories(), request.getxOCCIAtt()); + if (instanceId == null) { + return false; + } } catch (OCCIException e) { if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); From 1e8e061476e38f99ee579440bb2326140f23621b Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 29 May 2014 15:28:27 -0300 Subject: [PATCH 170/185] Adding ssh-tunnel-public-host property at manager configuration file and chaging ssh-tunnel-private-host to ssh-tunnel-public-host at instance attributes --- manager.conf.example | 3 ++- .../fogbowcloud/manager/core/ManagerController.java | 4 ++-- .../manager/core/ssh/DefaultSSHTunnel.java | 9 ++++++--- .../manager/occi/core/ssh/TestDefaultSSHTunnel.java | 12 ++++++++---- 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/manager.conf.example b/manager.conf.example index d3688f61..b1c1b276 100644 --- a/manager.conf.example +++ b/manager.conf.example @@ -29,7 +29,8 @@ scheduler_period=30000 token_update_period=300000 instance_monitoring_period=120000 -ssh_tunnel_host=10.0.0.1 +ssh_tunnel_public_host=150.165.80.1 +ssh_tunnel_private_host=10.0.0.1 ssh_tunnel_user=fogbow ssh_tunnel_port_range=50000:59999 diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 84576d98..52fb0735 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -168,9 +168,9 @@ private Instance getInstance(Request request) { + request.getMemberId() + " to get its information."); instance = getRemoteInstance(request); } - String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT); + String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT); if (sshAddress != null) { - instance.addAttribute(DefaultSSHTunnel.SSH_ADDRESS_ATT, sshAddress); + instance.addAttribute(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT, sshAddress); } return instance; } diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index 904619ea..ebf4bb92 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -20,6 +20,7 @@ public class DefaultSSHTunnel implements SSHTunnel { public static final String USER_DATA_ATT = "org.fogbowcloud.request.user-data"; public static final String SSH_ADDRESS_ATT = "org.fogbowcloud.request.ssh-address"; + public static final String SSH_PUBLIC_ADDRESS_ATT = "org.fogbowcloud.request.ssh-public-address"; private Set takenPorts = new HashSet(); public void create(Properties properties, Request request) throws FileNotFoundException, IOException { @@ -28,10 +29,11 @@ public void create(Properties properties, Request request) throws FileNotFoundEx RequestConstants.SCHEME, RequestConstants.MIXIN_CLASS)); String sshTunnelCmd = IOUtils.toString(new FileInputStream("bin/fogbow-inject-tunnel")); - String sshHost = properties.getProperty("ssh_tunnel_host"); + String sshPrivateHostIP = properties.getProperty("ssh_tunnel_private_host"); + String sshPublicHostIP = properties.getProperty("ssh_tunnel_public_host"); sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_USER#", properties.getProperty("ssh_tunnel_user")); - sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", sshHost); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", sshPrivateHostIP); String[] portRange = properties.getProperty("ssh_tunnel_port_range").split(":"); Integer portFloor = Integer.parseInt(portRange[0]); @@ -53,7 +55,8 @@ public void create(Properties properties, Request request) throws FileNotFoundEx sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_PORT#", sshPort.toString()); request.putAttValue(USER_DATA_ATT, Base64.encodeBase64URLSafeString( sshTunnelCmd.getBytes(Charsets.UTF_8))); - request.putAttValue(SSH_ADDRESS_ATT, sshHost + ":" + sshPort); + request.putAttValue(SSH_ADDRESS_ATT, sshPrivateHostIP + ":" + sshPort); + request.putAttValue(SSH_PUBLIC_ADDRESS_ATT, sshPublicHostIP + ":" + sshPort); } public void release(Request request) { diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java index 662be1ae..ac6346ef 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java @@ -35,18 +35,20 @@ public void setUp() { @Test public void create() throws FileNotFoundException, IOException { - final String host = "10.0.0.1"; + final String privateHostIP = "10.0.0.1"; + final String publicHostIP = "150.165.80.1"; final String user = "fogbow"; final String portRanger = "50000:59999"; final String port = "50000"; String sshTunnelCmd = getScriptFogbowInjectTunnel(); sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_USER#", user); - sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", host); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", privateHostIP); sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_PORT#", port); Properties properties = new Properties(); - properties.put("ssh_tunnel_host", host); + properties.put("ssh_tunnel_public_host", publicHostIP); + properties.put("ssh_tunnel_private_host", privateHostIP); properties.put("ssh_tunnel_user", user); properties.put("ssh_tunnel_port_range", portRanger); Request request = new Request("is", new Token("accessId", "user", new Date(), @@ -59,8 +61,10 @@ public void create() throws FileNotFoundException, IOException { .equals(RequestConstants.USER_DATA_TERM)); Assert.assertEquals(Base64.encodeBase64URLSafeString(sshTunnelCmd.getBytes(Charsets.UTF_8)) .length(), request.getAttValue(DefaultSSHTunnel.USER_DATA_ATT).length()); - Assert.assertEquals(host + ":" + port, + Assert.assertEquals(privateHostIP + ":" + port, request.getAttValue(DefaultSSHTunnel.SSH_ADDRESS_ATT)); + Assert.assertEquals(publicHostIP + ":" + port, + request.getAttValue(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT)); } @Test From 6893fd56d7ee7ca4a9df2ebcf260ca5cde3b296c Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 29 May 2014 16:42:21 -0300 Subject: [PATCH 171/185] Fixing identity call on v2 identity endpoint in OpenStackIdentityPlugin --- .../openstack/OpenStackIdentityPlugin.java | 35 +++++++------------ .../core/util/DefaultDataTestHelper.java | 4 +-- 2 files changed, 14 insertions(+), 25 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index b8a48d43..93f7c109 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -176,32 +176,21 @@ private Token getTokenFromJson(String responseStr) { @Override public Token getToken(String accessId) { - String responseJson = getResponseJson(accessId); - Date expirationTime = null; - String user = null; - Map tokenAttributes = new HashMap(); + JSONObject root; try { - JSONObject root = new JSONObject(responseJson); - user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) - .getString(NAME_KEYSTONE); - String expirationTimeStr = root.getJSONObject(ACCESS_KEYSTONE) - .getJSONObject(TOKEN_KEYSTONE).getString(EXPIRES_KEYSTONE); - String tenantName = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) - .getJSONObject(TENANT_KEYSTONE).getString(NAME_KEYSTONE); - String tenantId = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(TOKEN_KEYSTONE) - .getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); - - tokenAttributes.put(OpenStackIdentityPlugin.TENANT_NAME_KEY, tenantName); - tokenAttributes.put(OpenStackIdentityPlugin.TENANT_ID_KEY, tenantId); - LOGGER.debug("json accessId: " + accessId); - LOGGER.debug("json user: " + user); - LOGGER.debug("json expirationDate: " + expirationTimeStr); - LOGGER.debug("json attributes: " + tokenAttributes); - expirationTime = getDateFromOpenStackFormat(expirationTimeStr); - } catch (Exception e) { + JSONObject idToken = new JSONObject(); + idToken.put(ID_KEYSTONE, accessId); + JSONObject auth = new JSONObject(); + auth.put(TOKEN_KEYSTONE, idToken); + root = new JSONObject(); + root.put(AUTH_KEYSTONE, auth); + } catch (JSONException e) { LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - return new Token(accessId, user, expirationTime, tokenAttributes); + + String responseStr = doPostRequest(v2Endpoint, root); + return getTokenFromJson(responseStr); } /* diff --git a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java index ff093df3..8df26802 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java @@ -28,7 +28,7 @@ public class DefaultDataTestHelper { //test default values public static final String USER_NAME = "user"; public static final String USER_PASS = "password"; - public static final String ACCESS_TOKEN_ID = "HgjhgYUDFTGBgrbelihBDFGBÇuyrb"; + public static final String ACCESS_TOKEN_ID = "accesstoken"; public static final String TENANT_NAME = "tenantName"; - public static final String INSTANCE_ID = "b122f3ad-503c-4abb-8a55-ba8d90cfce9f"; + public static final String INSTANCE_ID = "instanceid"; } \ No newline at end of file From 0eb97ce25913b59157180a918ef1651b80fb021d Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 29 May 2014 17:02:33 -0300 Subject: [PATCH 172/185] Comment tenant properties at OpenStackIdentityPlugin --- .../plugins/openstack/OpenStackIdentityPlugin.java | 12 ++++++------ .../manager/occi/util/KeystoneApplication.java | 12 +++++++----- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 93f7c109..0f2cd133 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -151,17 +151,17 @@ private Token getTokenFromJson(String responseStr) { JSONObject root = new JSONObject(responseStr); JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( TOKEN_KEYSTONE); - String token = tokenKeyStone.getString(ID_KEYSTONE); - String tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); - String tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( - NAME_KEYSTONE); + String token = tokenKeyStone.getString(ID_KEYSTONE); +// String tenantId = tokenKeyStone.optJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); +// String tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( +// NAME_KEYSTONE); String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); String user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) .getString(NAME_KEYSTONE); Map tokenAtt = new HashMap(); - tokenAtt.put(TENANT_ID_KEY, tenantId); - tokenAtt.put(TENANT_NAME_KEY, tenantName); +// tokenAtt.put(TENANT_ID_KEY, tenantId); +// tokenAtt.put(TENANT_NAME_KEY, tenantName); LOGGER.debug("json token: " + token); LOGGER.debug("json user: " + user); LOGGER.debug("json expirationDate: " + expirationDateToken); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index c4f4a056..71afaf54 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -70,15 +70,17 @@ public void checkUserByAccessId(String accessId) { } public void authenticationCheckToken(String accessId, String tenantName) { - if (!defaultToken.getAccessId().equals(accessId) - || !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)) { + if (!defaultToken.getAccessId().equals(accessId)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); - } + } else if (tenantName != null && !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)){ + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); + } } public void checkAuthenticationCredentials(String username, String password, String tenantName) { - if (!defaultToken.getUser().equals(username) || !this.userPassword.equals(password) - || !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)) { + if (!defaultToken.getUser().equals(username) || !this.userPassword.equals(password)) { + throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); + } else if (tenantName != null && !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)){ throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } From 4e24564f6fd46705f49ca883f72886a953bb7c49 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Thu, 29 May 2014 17:20:36 -0300 Subject: [PATCH 173/185] Checking if tenant properties exist on JSONObject on OpenStackIdentityPlugin --- .../openstack/OpenStackIdentityPlugin.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 0f2cd133..537b9fc4 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -152,16 +152,22 @@ private Token getTokenFromJson(String responseStr) { JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( TOKEN_KEYSTONE); String token = tokenKeyStone.getString(ID_KEYSTONE); -// String tenantId = tokenKeyStone.optJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); -// String tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( -// NAME_KEYSTONE); + String tenantId = ""; + String tenantName = ""; + Map tokenAtt = new HashMap(); + try { + tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); + tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( + NAME_KEYSTONE); + tokenAtt.put(TENANT_ID_KEY, tenantId); + tokenAtt.put(TENANT_NAME_KEY, tenantName); + } catch (JSONException e) { + LOGGER.debug("There are not tenant properties on json."); + } String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); String user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) .getString(NAME_KEYSTONE); - - Map tokenAtt = new HashMap(); -// tokenAtt.put(TENANT_ID_KEY, tenantId); -// tokenAtt.put(TENANT_NAME_KEY, tenantName); + LOGGER.debug("json token: " + token); LOGGER.debug("json user: " + user); LOGGER.debug("json expirationDate: " + expirationDateToken); From b3874f268c7561693bcbed1d5a2ad7731bf16f00 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Fri, 30 May 2014 14:05:53 -0300 Subject: [PATCH 174/185] Fixing OpenStackIdentityPlugin v2 API call. --- .../manager/core/ManagerController.java | 2 +- .../manager/core/plugins/IdentityPlugin.java | 2 +- .../openstack/OpenStackComputePlugin.java | 6 + .../openstack/OpenStackIdentityPlugin.java | 124 +++++++++++------- .../manager/core/TestManagerController.java | 2 +- .../occi/plugins/TestIdentityOpenStack.java | 2 +- .../occi/util/KeystoneApplication.java | 110 ++++++++++------ 7 files changed, 151 insertions(+), 97 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 52fb0735..0db593d8 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -427,7 +427,7 @@ protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { - dateUtils.currentTimeMillis(); LOGGER.debug("Valid interval of requestId " + request.getId() + " is " + validInterval); if (validInterval < 2 * tokenUpdatePeriod) { - Token newToken = identityPlugin.createToken(request.getToken()); + Token newToken = identityPlugin.reIssueToken(request.getToken()); LOGGER.info("Setting new token "+ newToken + " on request " + request.getId()); requests.get(request.getId()).setToken(newToken); } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java index 97167dd0..2a429eb3 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/IdentityPlugin.java @@ -8,7 +8,7 @@ public interface IdentityPlugin { public Token createToken(Map userCredentials); - public Token createToken(Token token); + public Token reIssueToken(Token token); public Token getToken(String accessId); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java index adcf8952..54de396c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackComputePlugin.java @@ -89,6 +89,10 @@ private static Category createFlavorCategory(String flavorPropName, Properties p @Override public String requestInstance(String authToken, List categories, Map xOCCIAtt) { + + LOGGER.debug("Requesting instance with accessId=" + authToken + "; categories=" + + categories + "; xOCCIAtt=" + xOCCIAtt); + List openStackCategories = new ArrayList(); Category categoryCompute = new Category(TERM_COMPUTE, SCHEME_COMPUTE, CLASS_COMPUTE); @@ -214,6 +218,8 @@ private Response doRequest(String method, String endpoint, String authToken, request.addHeader(header); } + LOGGER.debug("AccessId=" + authToken + "; headers=" + additionalHeaders); + HttpClient client = new DefaultHttpClient(); httpResponse = client.execute(request); diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index 537b9fc4..df23c97f 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -6,7 +6,6 @@ import java.util.Locale; import java.util.Map; import java.util.Properties; -import java.util.TimeZone; import org.apache.commons.codec.Charsets; import org.apache.http.HttpResponse; @@ -19,13 +18,13 @@ import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; -import org.fogbowcloud.manager.core.model.DateUtils; import org.fogbowcloud.manager.core.plugins.IdentityPlugin; import org.fogbowcloud.manager.occi.core.ErrorType; import org.fogbowcloud.manager.occi.core.OCCIException; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.ResponseConstants; import org.fogbowcloud.manager.occi.core.Token; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -39,27 +38,36 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { public static final String TENANT_NAME_KEY = "X-Token-TenantName"; // keystone json data - public static final String TENANT_NAME_KEYSTONE = "tenantName"; - public static final String USERNAME_KEYSTONE = "username"; - public static final String PASSWORD_KEYSTONE = "password"; - public static final String PASSWORD_CREDENTIALS_KEYSTONE = "passwordCredentials"; - public static final String AUTH_KEYSTONE = "auth"; - public static final String TOKEN_KEYSTONE = "token"; - public static final String ID_KEYSTONE = "id"; - public static final String TENANT_KEYSTONE = "tenant"; - public static final String ACCESS_KEYSTONE = "access"; - public static final String EXPIRES_KEYSTONE = "expires"; - public static final String USER_KEYSTONE = "user"; - public static final String NAME_KEYSTONE = "name"; + public static final String TENANT_NAME_PROP = "tenantName"; + public static final String USERNAME_PROP = "username"; + public static final String PASSWORD_PROP = "password"; + public static final String PASSWORD_CREDENTIALS_PROP = "passwordCredentials"; + public static final String AUTH_PROP = "auth"; + public static final String TOKEN_PROP = "token"; + public static final String ID_PROP = "id"; + public static final String TENANT_PROP = "tenant"; + public static final String TENANTS_PROP = "tenants"; + public static final String ACCESS_PROP = "access"; + public static final String EXPIRES_PROP = "expires"; + public static final String USER_PROP = "user"; + public static final String NAME_PROP = "name"; private static final int LAST_SUCCESSFUL_STATUS = 204; private final static Logger LOGGER = Logger.getLogger(OpenStackIdentityPlugin.class); - private static String V2_ENDPOINT_PATH = "/v2.0/tokens"; - private String v2Endpoint; + /* + * The json response format can be seen in the following link: + * http://developer.openstack.org/api-ref-identity-v2.html + */ + public static String V2_TOKENS_ENDPOINT_PATH = "/v2.0/tokens"; + public static String V2_TENANTS_ENDPOINT_PATH = "/v2.0/tenants"; + + private String v2TokensEndpoint; + private String v2TenantsEndpoint; public OpenStackIdentityPlugin(Properties properties) { String keystoneUrl = properties.getProperty("identity_openstack_url"); - this.v2Endpoint = keystoneUrl + V2_ENDPOINT_PATH; + this.v2TokensEndpoint = keystoneUrl + V2_TOKENS_ENDPOINT_PATH; + this.v2TenantsEndpoint = keystoneUrl + V2_TENANTS_ENDPOINT_PATH; } @Override @@ -72,21 +80,21 @@ public Token createToken(Map credentials) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - String responseStr = doPostRequest(v2Endpoint, json); + String responseStr = doPostRequest(v2TokensEndpoint, json); return getTokenFromJson(responseStr); } private JSONObject mountJson(Map credentials) throws JSONException { JSONObject passwordCredentials = new JSONObject(); - passwordCredentials.put(USERNAME_KEYSTONE, + passwordCredentials.put(USERNAME_PROP, credentials.get(OpenStackIdentityPlugin.USER_KEY)); - passwordCredentials.put(PASSWORD_KEYSTONE, + passwordCredentials.put(PASSWORD_PROP, credentials.get(OpenStackIdentityPlugin.PASSWORD_KEY)); JSONObject auth = new JSONObject(); - auth.put(TENANT_NAME_KEYSTONE, credentials.get(TENANT_NAME_KEY)); - auth.put(PASSWORD_CREDENTIALS_KEYSTONE, passwordCredentials); + auth.put(TENANT_NAME_PROP, credentials.get(TENANT_NAME_KEY)); + auth.put(PASSWORD_CREDENTIALS_PROP, passwordCredentials); JSONObject root = new JSONObject(); - root.put(AUTH_KEYSTONE, auth); + root.put(AUTH_PROP, auth); return root; } @@ -112,7 +120,7 @@ private String doPostRequest(String endpoint, JSONObject json) { } @Override - public Token createToken(Token token) { + public Token reIssueToken(Token token) { JSONObject json; try { json = mountJson(token); @@ -121,18 +129,18 @@ public Token createToken(Token token) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - String responseStr = doPostRequest(v2Endpoint, json); + String responseStr = doPostRequest(v2TokensEndpoint, json); return getTokenFromJson(responseStr); } private JSONObject mountJson(Token token) throws JSONException { JSONObject idToken = new JSONObject(); - idToken.put(ID_KEYSTONE, token.getAccessId()); + idToken.put(ID_PROP, token.getAccessId()); JSONObject auth = new JSONObject(); - auth.put(TENANT_NAME_KEYSTONE, token.get(TENANT_NAME_KEY)); - auth.put(TOKEN_KEYSTONE, idToken); + auth.put(TENANT_NAME_PROP, token.get(TENANT_NAME_KEY)); + auth.put(TOKEN_PROP, idToken); JSONObject root = new JSONObject(); - root.put(AUTH_KEYSTONE, auth); + root.put(AUTH_PROP, auth); return root; } @@ -149,24 +157,24 @@ private void checkStatusResponse(HttpResponse response) { private Token getTokenFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - JSONObject tokenKeyStone = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject( - TOKEN_KEYSTONE); - String token = tokenKeyStone.getString(ID_KEYSTONE); + JSONObject tokenKeyStone = root.getJSONObject(ACCESS_PROP).getJSONObject( + TOKEN_PROP); + String token = tokenKeyStone.getString(ID_PROP); String tenantId = ""; String tenantName = ""; Map tokenAtt = new HashMap(); try { - tenantId = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString(ID_KEYSTONE); - tenantName = tokenKeyStone.getJSONObject(TENANT_KEYSTONE).getString( - NAME_KEYSTONE); + tenantId = tokenKeyStone.getJSONObject(TENANT_PROP).getString(ID_PROP); + tenantName = tokenKeyStone.getJSONObject(TENANT_PROP).getString( + NAME_PROP); tokenAtt.put(TENANT_ID_KEY, tenantId); tokenAtt.put(TENANT_NAME_KEY, tenantName); } catch (JSONException e) { LOGGER.debug("There are not tenant properties on json."); } - String expirationDateToken = tokenKeyStone.getString(EXPIRES_KEYSTONE); - String user = root.getJSONObject(ACCESS_KEYSTONE).getJSONObject(USER_KEYSTONE) - .getString(NAME_KEYSTONE); + String expirationDateToken = tokenKeyStone.getString(EXPIRES_PROP); + String user = root.getJSONObject(ACCESS_PROP).getJSONObject(USER_PROP) + .getString(NAME_PROP); LOGGER.debug("json token: " + token); LOGGER.debug("json user: " + user); @@ -182,36 +190,40 @@ private Token getTokenFromJson(String responseStr) { @Override public Token getToken(String accessId) { + String responseStr; + String tenantName = getTenantName(accessId); + JSONObject root; try { JSONObject idToken = new JSONObject(); - idToken.put(ID_KEYSTONE, accessId); + idToken.put(ID_PROP, accessId); + JSONObject auth = new JSONObject(); - auth.put(TOKEN_KEYSTONE, idToken); + auth.put(TOKEN_PROP, idToken); + auth.put(TENANT_NAME_PROP, tenantName); + root = new JSONObject(); - root.put(AUTH_KEYSTONE, auth); + root.put(AUTH_PROP, auth); } catch (JSONException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - String responseStr = doPostRequest(v2Endpoint, root); + responseStr = doPostRequest(v2TokensEndpoint, root); return getTokenFromJson(responseStr); } - /* - * The json response format can be seen in the following link: - * http://developer.openstack.org/api-ref-identity-v2.html - */ - public String getResponseJson(String accessId) { + private String getTenantName(String accessId) { HttpResponse response; String responseStr = null; try { HttpClient httpCLient = new DefaultHttpClient(); - HttpGet httpGet = new HttpGet(this.v2Endpoint + "/" + accessId); + HttpGet httpGet = new HttpGet(this.v2TenantsEndpoint); httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, accessId); + httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); + httpGet.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_CONTENT_TYPE); + response = httpCLient.execute(httpGet); - responseStr = EntityUtils .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); } catch (Exception e) { @@ -219,8 +231,20 @@ public String getResponseJson(String accessId) { throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } checkStatusResponse(response); + return getTenantNameFromJson(responseStr); + } - return responseStr; + private String getTenantNameFromJson(String responseStr) { + try { + System.out.println(responseStr); + JSONObject root = new JSONObject(responseStr); + JSONArray tenantsStone = root.getJSONArray(TENANTS_PROP); + JSONObject tenantStone = tenantsStone.getJSONObject(0); //getting first tenant + return tenantStone.getString(NAME_PROP); + } catch (JSONException e) { + LOGGER.error(e); + throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); + } } @Override diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index db646c49..72c2a71a 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -130,7 +130,7 @@ DefaultDataTestHelper.USER_NAME, new Date(tokenExpirationTime), // adding behaviour on identity mock Token secondToken = new Token(ACCESS_TOKEN_ID_2, DefaultDataTestHelper.USER_NAME, new Date( tokenExpirationTime + tokenUpdaterInterval), new HashMap()); - Mockito.when(managerTestHelper.getIdentityPlugin().createToken(firstToken)).thenReturn( + Mockito.when(managerTestHelper.getIdentityPlugin().reIssueToken(firstToken)).thenReturn( secondToken); // mocking date diff --git a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java index 6b92d651..743524a2 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java +++ b/src/test/java/org/fogbowcloud/manager/occi/plugins/TestIdentityOpenStack.java @@ -93,7 +93,7 @@ public void testUpgradeToken() { .getDateOpenStackFormat(DefaultDataTestHelper.TOKEN_FUTURE_EXPIRATION), OpenStackIdentityPlugin.getDateOpenStackFormat(expirationDate)); - Token token2 = this.identityOpenStack.createToken(token); + Token token2 = this.identityOpenStack.reIssueToken(token); authToken = token2.getAccessId(); tenantID = token2.get(OpenStackIdentityPlugin.TENANT_ID_KEY); expirationDate = token2.getExpirationDate(); diff --git a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java index 71afaf54..1df48ca4 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java +++ b/src/test/java/org/fogbowcloud/manager/occi/util/KeystoneApplication.java @@ -1,17 +1,14 @@ package org.fogbowcloud.manager.occi.util; import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.HashMap; -import java.util.Locale; import java.util.Map; -import java.util.TimeZone; import org.apache.http.HttpStatus; import org.fogbowcloud.manager.core.plugins.openstack.OpenStackIdentityPlugin; import org.fogbowcloud.manager.occi.core.OCCIHeaders; import org.fogbowcloud.manager.occi.core.Token; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.restlet.Application; @@ -28,9 +25,6 @@ public class KeystoneApplication extends Application { - public static String TARGET_TOKEN_POST = "/v2.0/tokens"; - public static String TARGET_TOKEN_GET = "/v2.0/tokens/{tokenId}"; - private Map accessIdToUser; private String userPassword; @@ -49,8 +43,8 @@ public KeystoneApplication(Token defaultToken, String userPassword) { @Override public Restlet createInboundRoot() { Router router = new Router(getContext()); - router.attach(TARGET_TOKEN_POST, KeystoneServer.class); - router.attach(TARGET_TOKEN_GET, KeystoneServer.class); + router.attach(OpenStackIdentityPlugin.V2_TOKENS_ENDPOINT_PATH, KeystoneServer.class); + router.attach(OpenStackIdentityPlugin.V2_TENANTS_ENDPOINT_PATH, KeystoneServer.class); return router; } @@ -72,15 +66,17 @@ public void checkUserByAccessId(String accessId) { public void authenticationCheckToken(String accessId, String tenantName) { if (!defaultToken.getAccessId().equals(accessId)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); - } else if (tenantName != null && !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)){ + } else if (tenantName != null + && !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); - } + } } public void checkAuthenticationCredentials(String username, String password, String tenantName) { if (!defaultToken.getUser().equals(username) || !this.userPassword.equals(password)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); - } else if (tenantName != null && !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)){ + } else if (tenantName != null + && !defaultToken.get(OpenStackIdentityPlugin.TENANT_NAME_KEY).equals(tenantName)) { throw new ResourceException(HttpStatus.SC_UNAUTHORIZED); } } @@ -97,39 +93,64 @@ public String fetch() { HttpRequest req = (HttpRequest) getRequest(); String token = req.getHeaders().getValues(OCCIHeaders.X_AUTH_TOKEN); keyStoneApplication.checkUserByAccessId(token); - String user = keyStoneApplication.getUserFromToken(token); - return mountJSONResponseUserPerToken(token, user); + if (getRequest().getResourceRef().toString() + .endsWith(OpenStackIdentityPlugin.V2_TOKENS_ENDPOINT_PATH)) { + String user = keyStoneApplication.getUserFromToken(token); + return createUserTokenJSONResponse(token, user); + } else { + return createTenantJSONResponse(keyStoneApplication.getDefaultToken()); + + } + } + + private String createTenantJSONResponse(Token token) { + JSONObject rootTenant = new JSONObject(); + try { + rootTenant.put(OpenStackIdentityPlugin.ID_PROP, + token.get(OpenStackIdentityPlugin.TENANT_ID_KEY)); + rootTenant.put(OpenStackIdentityPlugin.NAME_PROP, + token.get(OpenStackIdentityPlugin.TENANT_NAME_KEY)); + + JSONArray tenants = new JSONArray(); + tenants.put(rootTenant); + JSONObject root = new JSONObject(); + return root.put(OpenStackIdentityPlugin.TENANTS_PROP, tenants).toString(); + } catch (JSONException e) { + e.printStackTrace(); + } + return null; } @Post public Representation post(Representation entity) { KeystoneApplication keyStoneApplication = (KeystoneApplication) getApplication(); - + String jsonCredentials = ""; try { jsonCredentials = entity.getText(); } catch (IOException e) { + e.printStackTrace(); } String tenantName = getTenantName(jsonCredentials); - String idToken = getIdToken(jsonCredentials); + String idToken = getTokenAccessId(jsonCredentials); if (idToken != null) { keyStoneApplication.authenticationCheckToken(idToken, tenantName); } else { String username = getUserFeatureCredentials(jsonCredentials, - OpenStackIdentityPlugin.USERNAME_KEYSTONE); + OpenStackIdentityPlugin.USERNAME_PROP); String password = getUserFeatureCredentials(jsonCredentials, - OpenStackIdentityPlugin.PASSWORD_KEYSTONE); + OpenStackIdentityPlugin.PASSWORD_PROP); keyStoneApplication.checkAuthenticationCredentials(username, password, tenantName); } return new StringRepresentation( - mountJSONResponseAuthenticateToken(keyStoneApplication.getDefaultToken()), + createAuthenticationJSONResponse(keyStoneApplication.getDefaultToken()), MediaType.TEXT_ALL); } - private String mountJSONResponseAuthenticateToken(Token token) { + private String createAuthenticationJSONResponse(Token token) { try { String tokenAccessId = token.getAccessId(); String tenantId = token.get(OpenStackIdentityPlugin.TENANT_ID_KEY); @@ -141,18 +162,18 @@ private String mountJSONResponseAuthenticateToken(Token token) { JSONObject rootIdToken = new JSONObject(); JSONObject rootTenant = new JSONObject(); - rootTenant.put(OpenStackIdentityPlugin.ID_KEYSTONE, tenantId); - rootTenant.put(OpenStackIdentityPlugin.NAME_KEYSTONE, tenantName); - rootIdToken.put(OpenStackIdentityPlugin.ID_KEYSTONE, tokenAccessId); - rootIdToken.put(OpenStackIdentityPlugin.EXPIRES_KEYSTONE, expirationDate); - rootIdToken.put(OpenStackIdentityPlugin.TENANT_KEYSTONE, rootTenant); + rootTenant.put(OpenStackIdentityPlugin.ID_PROP, tenantId); + rootTenant.put(OpenStackIdentityPlugin.NAME_PROP, tenantName); + rootIdToken.put(OpenStackIdentityPlugin.ID_PROP, tokenAccessId); + rootIdToken.put(OpenStackIdentityPlugin.EXPIRES_PROP, expirationDate); + rootIdToken.put(OpenStackIdentityPlugin.TENANT_PROP, rootTenant); JSONObject rootAccess = new JSONObject(); - rootAccess.put(OpenStackIdentityPlugin.TOKEN_KEYSTONE, rootIdToken); + rootAccess.put(OpenStackIdentityPlugin.TOKEN_PROP, rootIdToken); JSONObject rootUserName = new JSONObject(); - rootUserName.put(OpenStackIdentityPlugin.NAME_KEYSTONE, token.getUser()); - rootAccess.put(OpenStackIdentityPlugin.USER_KEYSTONE, rootUserName); + rootUserName.put(OpenStackIdentityPlugin.NAME_PROP, token.getUser()); + rootAccess.put(OpenStackIdentityPlugin.USER_PROP, rootUserName); JSONObject rootMain = new JSONObject(); - rootMain.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, rootAccess); + rootMain.put(OpenStackIdentityPlugin.ACCESS_PROP, rootAccess); return rootMain.toString(); } catch (JSONException e) { e.printStackTrace(); @@ -160,48 +181,51 @@ private String mountJSONResponseAuthenticateToken(Token token) { return null; } - private String getIdToken(String jsonCredentials) { + private String getTokenAccessId(String jsonCredentials) { try { JSONObject root = new JSONObject(jsonCredentials); - return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) - .getJSONObject(OpenStackIdentityPlugin.TOKEN_KEYSTONE) - .getString(OpenStackIdentityPlugin.ID_KEYSTONE).toString(); + return root.getJSONObject(OpenStackIdentityPlugin.AUTH_PROP) + .getJSONObject(OpenStackIdentityPlugin.TOKEN_PROP) + .getString(OpenStackIdentityPlugin.ID_PROP).toString(); } catch (JSONException e) { - return null; + e.printStackTrace(); } + return null; } private String getTenantName(String jsonCredentials) { try { JSONObject root = new JSONObject(jsonCredentials); - return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) - .getString(OpenStackIdentityPlugin.TENANT_NAME_KEYSTONE).toString(); + return root.getJSONObject(OpenStackIdentityPlugin.AUTH_PROP) + .getString(OpenStackIdentityPlugin.TENANT_NAME_PROP).toString(); } catch (JSONException e) { - return null; + e.printStackTrace(); } + return null; } private String getUserFeatureCredentials(String jsonCredentials, String feature) { try { JSONObject root = new JSONObject(jsonCredentials); - return root.getJSONObject(OpenStackIdentityPlugin.AUTH_KEYSTONE) - .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS_KEYSTONE) + return root.getJSONObject(OpenStackIdentityPlugin.AUTH_PROP) + .getJSONObject(OpenStackIdentityPlugin.PASSWORD_CREDENTIALS_PROP) .getString(feature).toString(); } catch (JSONException e) { return null; } } - private String mountJSONResponseUserPerToken(String token, String username) { + private String createUserTokenJSONResponse(String accessId, String user) { try { JSONObject usernameObject = new JSONObject(); - usernameObject.put(OpenStackIdentityPlugin.NAME_KEYSTONE, username); + usernameObject.put(OpenStackIdentityPlugin.NAME_PROP, user); JSONObject userObject = new JSONObject(); - userObject.put(OpenStackIdentityPlugin.USER_KEYSTONE, usernameObject); + userObject.put(OpenStackIdentityPlugin.USER_PROP, usernameObject); JSONObject accessObject = new JSONObject(); - accessObject.put(OpenStackIdentityPlugin.ACCESS_KEYSTONE, userObject); + accessObject.put(OpenStackIdentityPlugin.ACCESS_PROP, userObject); return accessObject.toString(); } catch (JSONException e) { + e.printStackTrace(); } return null; } From 7d77031039a3336b591c32ca9b2137f4b4897460 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Fri, 30 May 2014 14:36:02 -0300 Subject: [PATCH 175/185] Changing ManagerController to create local instance with federation user before trying to create at remote clouds. --- .../manager/core/ManagerController.java | 26 +++++++++- .../manager/core/RoundRobinMemberPicker.java | 22 +++++---- .../openstack/OpenStackIdentityPlugin.java | 47 +++++++++---------- 3 files changed, 60 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 0db593d8..38ea21cb 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -264,6 +264,9 @@ public FederationMember getFederationMember(String memberId) { return member; } } + if (memberId.equals(properties.get("xmpp_jid"))) { + return new FederationMember(getResourcesInfo()); + } return null; } @@ -523,7 +526,8 @@ protected void checkAndSubmitOpenRequests() { for (String keyAttributes : RequestAttribute.getValues()) { xOCCIAtt.remove(keyAttributes); } - allFulfilled &= createLocalInstance(request) || createRemoteInstance(request); + allFulfilled &= createLocalInstance(request) + || createLocalInstanceWithFederationUser(request) || createRemoteInstance(request); } else if (request.isExpired()) { request.setState(RequestState.CLOSED); } else { @@ -536,6 +540,26 @@ protected void checkAndSubmitOpenRequests() { } } + private boolean createLocalInstanceWithFederationUser(Request request) { + request.setMemberId(properties.getProperty("xmpp_jid")); + + LOGGER.info("Submiting request " + request + " with federation user locally."); + + String remoteInstanceId = createInstanceForRemoteMember(properties.getProperty("xmpp_jid"), + request.getCategories(), request.getxOCCIAtt()); + + if (remoteInstanceId == null) { + return false; + } + + request.setState(RequestState.FULFILLED); + request.setInstanceId(remoteInstanceId); + if (!instanceMonitoringTimer.isScheduled()) { + triggerInstancesMonitor(); + } + return true; + } + public void setPacketSender(PacketSender packetSender) { this.packetSender = packetSender; } diff --git a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java index 68177db8..b5822a1a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java +++ b/src/main/java/org/fogbowcloud/manager/core/RoundRobinMemberPicker.java @@ -15,17 +15,19 @@ public FederationMember pick(ManagerController facade) { return null; } current = (current + 1) % members.size(); - FederationMember currentMember = members.get(current); - - String myJid = facade.getProperties().getProperty("xmpp_jid"); - if (currentMember.getResourcesInfo().getId().equals(myJid) - && members.size() > 1 - && facade.getValidator().canReceiveFrom(currentMember)) { - current = (current + 1) % members.size(); - currentMember = members.get(current); - } - return members.get(current); + for (int i = 0; i < members.size(); i++) { + FederationMember currentMember = members.get(current); + + String myJid = facade.getProperties().getProperty("xmpp_jid"); + if (currentMember.getResourcesInfo().getId().equals(myJid) + || !facade.getValidator().canReceiveFrom(currentMember)) { + current = (current + 1) % members.size(); + continue; + } + return members.get(current); + } + return null; } } diff --git a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java index df23c97f..57897b6d 100644 --- a/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java +++ b/src/main/java/org/fogbowcloud/manager/core/plugins/openstack/OpenStackIdentityPlugin.java @@ -60,7 +60,7 @@ public class OpenStackIdentityPlugin implements IdentityPlugin { */ public static String V2_TOKENS_ENDPOINT_PATH = "/v2.0/tokens"; public static String V2_TENANTS_ENDPOINT_PATH = "/v2.0/tenants"; - + private String v2TokensEndpoint; private String v2TenantsEndpoint; @@ -86,8 +86,7 @@ public Token createToken(Map credentials) { private JSONObject mountJson(Map credentials) throws JSONException { JSONObject passwordCredentials = new JSONObject(); - passwordCredentials.put(USERNAME_PROP, - credentials.get(OpenStackIdentityPlugin.USER_KEY)); + passwordCredentials.put(USERNAME_PROP, credentials.get(OpenStackIdentityPlugin.USER_KEY)); passwordCredentials.put(PASSWORD_PROP, credentials.get(OpenStackIdentityPlugin.PASSWORD_KEY)); JSONObject auth = new JSONObject(); @@ -157,16 +156,14 @@ private void checkStatusResponse(HttpResponse response) { private Token getTokenFromJson(String responseStr) { try { JSONObject root = new JSONObject(responseStr); - JSONObject tokenKeyStone = root.getJSONObject(ACCESS_PROP).getJSONObject( - TOKEN_PROP); - String token = tokenKeyStone.getString(ID_PROP); + JSONObject tokenKeyStone = root.getJSONObject(ACCESS_PROP).getJSONObject(TOKEN_PROP); + String token = tokenKeyStone.getString(ID_PROP); String tenantId = ""; String tenantName = ""; Map tokenAtt = new HashMap(); try { tenantId = tokenKeyStone.getJSONObject(TENANT_PROP).getString(ID_PROP); - tenantName = tokenKeyStone.getJSONObject(TENANT_PROP).getString( - NAME_PROP); + tenantName = tokenKeyStone.getJSONObject(TENANT_PROP).getString(NAME_PROP); tokenAtt.put(TENANT_ID_KEY, tenantId); tokenAtt.put(TENANT_NAME_KEY, tenantName); } catch (JSONException e) { @@ -175,13 +172,12 @@ private Token getTokenFromJson(String responseStr) { String expirationDateToken = tokenKeyStone.getString(EXPIRES_PROP); String user = root.getJSONObject(ACCESS_PROP).getJSONObject(USER_PROP) .getString(NAME_PROP); - + LOGGER.debug("json token: " + token); LOGGER.debug("json user: " + user); LOGGER.debug("json expirationDate: " + expirationDateToken); - LOGGER.debug("json attributes: " + tokenAtt); - return new Token(token, user, getDateFromOpenStackFormat(expirationDateToken), - tokenAtt); + LOGGER.debug("json attributes: " + tokenAtt); + return new Token(token, user, getDateFromOpenStackFormat(expirationDateToken), tokenAtt); } catch (Exception e) { LOGGER.error("Exception while getting token from json.", e); return null; @@ -192,23 +188,23 @@ private Token getTokenFromJson(String responseStr) { public Token getToken(String accessId) { String responseStr; String tenantName = getTenantName(accessId); - + JSONObject root; try { JSONObject idToken = new JSONObject(); idToken.put(ID_PROP, accessId); - + JSONObject auth = new JSONObject(); auth.put(TOKEN_PROP, idToken); auth.put(TENANT_NAME_PROP, tenantName); - + root = new JSONObject(); - root.put(AUTH_PROP, auth); + root.put(AUTH_PROP, auth); } catch (JSONException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); } - + responseStr = doPostRequest(v2TokensEndpoint, root); return getTokenFromJson(responseStr); } @@ -222,7 +218,7 @@ private String getTenantName(String accessId) { httpGet.addHeader(OCCIHeaders.X_AUTH_TOKEN, accessId); httpGet.addHeader(OCCIHeaders.CONTENT_TYPE, OCCIHeaders.JSON_CONTENT_TYPE); httpGet.addHeader(OCCIHeaders.ACCEPT, OCCIHeaders.JSON_CONTENT_TYPE); - + response = httpCLient.execute(httpGet); responseStr = EntityUtils .toString(response.getEntity(), String.valueOf(Charsets.UTF_8)); @@ -239,8 +235,10 @@ private String getTenantNameFromJson(String responseStr) { System.out.println(responseStr); JSONObject root = new JSONObject(responseStr); JSONArray tenantsStone = root.getJSONArray(TENANTS_PROP); - JSONObject tenantStone = tenantsStone.getJSONObject(0); //getting first tenant - return tenantStone.getString(NAME_PROP); + JSONObject tenantStone = tenantsStone.getJSONObject(0); // getting + // first + // tenant + return tenantStone.getString(NAME_PROP); } catch (JSONException e) { LOGGER.error(e); throw new OCCIException(ErrorType.BAD_REQUEST, ResponseConstants.IRREGULAR_SYNTAX); @@ -258,15 +256,16 @@ public boolean isValid(String accessId) { } public static String getDateOpenStackFormat(Date date) { - SimpleDateFormat dateFormatOpenStack = new SimpleDateFormat(OPEN_STACK_DATE_FORMAT, Locale.ROOT); + SimpleDateFormat dateFormatOpenStack = new SimpleDateFormat(OPEN_STACK_DATE_FORMAT, + Locale.ROOT); String expirationDate = dateFormatOpenStack.format(date); return expirationDate; } - + public static Date getDateFromOpenStackFormat(String expirationDateStr) { - SimpleDateFormat dateFormatOpenStack = new SimpleDateFormat( - OPEN_STACK_DATE_FORMAT, Locale.ROOT); + SimpleDateFormat dateFormatOpenStack = new SimpleDateFormat(OPEN_STACK_DATE_FORMAT, + Locale.ROOT); try { return dateFormatOpenStack.parse(expirationDateStr); } catch (Exception e) { From 1f0bb7226a286f4810602da3cba1064f878444b2 Mon Sep 17 00:00:00 2001 From: giovannifs Date: Fri, 30 May 2014 15:05:15 -0300 Subject: [PATCH 176/185] Adding try catch block at create instance with federation user locally. --- .../fogbowcloud/manager/core/ManagerController.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 38ea21cb..3ad5ff2b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -545,9 +545,15 @@ private boolean createLocalInstanceWithFederationUser(Request request) { LOGGER.info("Submiting request " + request + " with federation user locally."); - String remoteInstanceId = createInstanceForRemoteMember(properties.getProperty("xmpp_jid"), - request.getCategories(), request.getxOCCIAtt()); - + String remoteInstanceId = null; + try { + remoteInstanceId = createInstanceForRemoteMember( + properties.getProperty("xmpp_jid"), request.getCategories(), + request.getxOCCIAtt()); + } catch (Exception e) { + LOGGER.info("Could not create instance with federation user locally."); + } + if (remoteInstanceId == null) { return false; } From a2f366fc58bdf3edee14be76de7534177e93dade Mon Sep 17 00:00:00 2001 From: giovannifs Date: Fri, 30 May 2014 15:55:27 -0300 Subject: [PATCH 177/185] Fixing tests and excluding deleted requests if the instance was removed --- .../manager/core/ManagerController.java | 78 ++++++++++--------- .../manager/core/util/ManagerTestHelper.java | 1 + 2 files changed, 43 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 3ad5ff2b..28b4450f 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -38,7 +38,8 @@ public class ManagerController { private static final Logger LOGGER = Logger.getLogger(ManagerController.class); public static final long DEFAULT_SCHEDULER_PERIOD = 30000; // 30 seconds private static final long DEFAULT_TOKEN_UPDATE_PERIOD = 300000; // 5 minutes - private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 minutes + private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 + // minutes private ManagerTimer requestSchedulerTimer = new ManagerTimer(); private ManagerTimer tokenUpdaterTimer = new ManagerTimer(); @@ -203,23 +204,26 @@ private void removeInstance(String accessId, String instanceId, Request request) } else { removeRemoteInstance(request); } - request.setInstanceId(null); - request.setMemberId(null); - instanceRemoved(request); + + if (request.getState().equals(RequestState.DELETED)){ + requests.exclude(request.getId()); + } else { + request.setInstanceId(null); + request.setMemberId(null); + instanceRemoved(request); + } } private void instanceRemoved(Request request) { - if (request.getState().notIn(RequestState.DELETED)){ - if (isPersistent(request)) { - LOGGER.debug("Request: " + request + ", setting state to " + RequestState.OPEN); - request.setState(RequestState.OPEN); - if (!requestSchedulerTimer.isScheduled()) { - triggerRequestScheduler(); - } - } else { - LOGGER.debug("Request: " + request + ", setting state to " + RequestState.CLOSED); - request.setState(RequestState.CLOSED); + if (isPersistent(request)) { + LOGGER.debug("Request: " + request + ", setting state to " + RequestState.OPEN); + request.setState(RequestState.OPEN); + if (!requestSchedulerTimer.isScheduled()) { + triggerRequestScheduler(); } + } else { + LOGGER.debug("Request: " + request + ", setting state to " + RequestState.CLOSED); + request.setState(RequestState.CLOSED); } } @@ -269,14 +273,14 @@ public FederationMember getFederationMember(String memberId) { } return null; } - + public String createInstanceForRemoteMember(String memberId, List categories, Map xOCCIAtt) { - + FederationMember member = getFederationMember(memberId); if (!validator.canDonateTo(member)) { return null; - } + } LOGGER.info("Submiting request with categories: " + categories + " and xOCCIAtt: " + xOCCIAtt + " for remote member."); String federationTokenAccessId = getFederationUserToken().getAccessId(); @@ -296,7 +300,7 @@ protected Token getFederationUserToken() { return this.federationUserToken; } - //TODO Think about getting token independent of OpenStackPlugin + // TODO Think about getting token independent of OpenStackPlugin Map federationUserCredentials = new HashMap(); String username = properties.getProperty("federation_user_name"); String password = properties.getProperty("federation_user_password"); @@ -380,21 +384,21 @@ protected void monitorInstances() { boolean turnOffTimer = true; LOGGER.info("Monitoring instances."); - for (Request request : requests.getAll()) { - if (request.getState().in(RequestState.FULFILLED, RequestState.DELETED)){ + for (Request request : requests.getAll()) { + if (request.getState().in(RequestState.FULFILLED, RequestState.DELETED)) { turnOffTimer = false; try { LOGGER.debug("Monitoring instance of request: " + request); getInstance(request); } catch (OCCIException e) { LOGGER.debug("Error while getInstance of " + request.getInstanceId(), e); - if (request.getState().in(RequestState.FULFILLED)){ + if (request.getState().in(RequestState.FULFILLED)) { instanceRemoved(requests.get(request.getId())); - } else if (request.getState().in(RequestState.DELETED)){ - requests.exclude(request.getId()); + } else if (request.getState().in(RequestState.DELETED)) { + requests.exclude(request.getId()); } - } - } + } + } } if (turnOffTimer) { @@ -419,23 +423,25 @@ public void run() { protected void checkAndUpdateRequestToken(long tokenUpdatePeriod) { List allRequests = requests.getAll(); boolean turnOffTimer = true; - + LOGGER.info("Checking and updating request token."); for (Request request : allRequests) { - try{ + try { if (request.getState().notIn(RequestState.CLOSED, RequestState.FAILED)) { turnOffTimer = false; long validInterval = request.getToken().getExpirationDate().getTime() - dateUtils.currentTimeMillis(); - LOGGER.debug("Valid interval of requestId " + request.getId() + " is " + validInterval); + LOGGER.debug("Valid interval of requestId " + request.getId() + " is " + + validInterval); if (validInterval < 2 * tokenUpdatePeriod) { Token newToken = identityPlugin.reIssueToken(request.getToken()); - LOGGER.info("Setting new token "+ newToken + " on request " + request.getId()); + LOGGER.info("Setting new token " + newToken + " on request " + + request.getId()); requests.get(request.getId()).setToken(newToken); } } - } catch (Exception e){ + } catch (Exception e) { LOGGER.error("Exception while checking token.", e); } } @@ -527,7 +533,8 @@ protected void checkAndSubmitOpenRequests() { xOCCIAtt.remove(keyAttributes); } allFulfilled &= createLocalInstance(request) - || createLocalInstanceWithFederationUser(request) || createRemoteInstance(request); + || createLocalInstanceWithFederationUser(request) + || createRemoteInstance(request); } else if (request.isExpired()) { request.setState(RequestState.CLOSED); } else { @@ -547,13 +554,12 @@ private boolean createLocalInstanceWithFederationUser(Request request) { String remoteInstanceId = null; try { - remoteInstanceId = createInstanceForRemoteMember( - properties.getProperty("xmpp_jid"), request.getCategories(), - request.getxOCCIAtt()); + remoteInstanceId = createInstanceForRemoteMember(properties.getProperty("xmpp_jid"), + request.getCategories(), request.getxOCCIAtt()); } catch (Exception e) { LOGGER.info("Could not create instance with federation user locally."); } - + if (remoteInstanceId == null) { return false; } @@ -585,7 +591,7 @@ public Properties getProperties() { public void setDateUtils(DateUtils dateUtils) { this.dateUtils = dateUtils; } - + public FederationMemberValidator getValidator() { return validator; } diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index 14b18bb9..edeaef98 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -274,6 +274,7 @@ public X509Certificate getCertificate() throws CertificateException, IOException @SuppressWarnings("unchecked") public ManagerController createDefaultManagerController() { Properties properties = new Properties(); + properties.put("federation_user_name", DefaultDataTestHelper.MANAGER_COMPONENT_URL); properties.put("federation_user_name", DefaultDataTestHelper.USER_NAME); properties.put("federation_user_password", DefaultDataTestHelper.USER_PASS); properties.put("federation_user_tenant_name", DefaultDataTestHelper.TENANT_NAME); From 5f1dd28bbc74b48eb2a4229d088389c7349aa36e Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 30 May 2014 22:05:14 +0200 Subject: [PATCH 178/185] fogbow-cli: enables request type --- .../java/org/fogbowcloud/manager/cli/Main.java | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/cli/Main.java b/src/main/java/org/fogbowcloud/manager/cli/Main.java index 1dc10968..6444edd4 100644 --- a/src/main/java/org/fogbowcloud/manager/cli/Main.java +++ b/src/main/java/org/fogbowcloud/manager/cli/Main.java @@ -28,8 +28,9 @@ public class Main { protected static String DEFAULT_URL = "http://localhost:8182"; protected static int DEFAULT_INTANCE_COUNT = 1; - protected static String DEFAULT_FLAVOR = "fogbow-small"; - protected static String DEFAULT_IMAGE = "fogbow-linux-x86"; + protected static final String DEFAULT_TYPE = "one-time"; + protected static final String DEFAULT_FLAVOR = "fogbow-small"; + protected static final String DEFAULT_IMAGE = "fogbow-linux-x86"; private static HttpClient client = new DefaultHttpClient(); @@ -84,13 +85,19 @@ public static void main(String[] args) throws Exception { return; } + if (!request.type.equals("one-time") + && !request.type.equals("persistent")) { + jc.usage(); + return; + } + Set
headers = new HashSet
(); headers.add(new BasicHeader("Category", "fogbow-request; scheme=\"http://schemas.fogbowcloud.org/request#\"; class=\"kind\"")); headers.add(new BasicHeader("X-OCCI-Attribute", "org.fogbowcloud.request.instance-count=" + request.instanceCount)); headers.add(new BasicHeader("X-OCCI-Attribute", - "org.fogbowcloud.request.type=one-time")); + "org.fogbowcloud.request.type=" + request.type)); headers.add(new BasicHeader("Category", request.flavor + "; scheme=\"http://schemas.fogbowcloud.org/template/resource#\"; class=\"mixin\"")); headers.add(new BasicHeader("Category", @@ -211,6 +218,9 @@ private static class RequestCommand extends AuthedCommand { @Parameter(names = "--flavor", description = "Instance flavor") String flavor = Main.DEFAULT_FLAVOR; + + @Parameter(names = "--type", description = "Request type (one-time|persistent)") + String type = Main.DEFAULT_TYPE; } @Parameters(separators = "=", commandDescription = "Instance operations") From 1847e4c2b9911b8f871e8b2444f003272378d9fd Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 30 May 2014 22:18:13 +0200 Subject: [PATCH 179/185] Using a better way to check if ports are available. --- .../manager/core/ssh/DefaultSSHTunnel.java | 31 ++++++++----------- 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index ebf4bb92..61639112 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -3,8 +3,8 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.DatagramSocket; -import java.net.ServerSocket; +import java.net.InetSocketAddress; +import java.net.Socket; import java.util.HashSet; import java.util.Properties; import java.util.Set; @@ -70,28 +70,23 @@ public void release(Request request) { } private static boolean available(int port) { - ServerSocket ss = null; - DatagramSocket ds = null; + Socket socket = null; try { - ss = new ServerSocket(port); - ss.setReuseAddress(true); - ds = new DatagramSocket(port); - ds.setReuseAddress(true); - return true; - } catch (IOException e) { - } finally { - if (ds != null) { - ds.close(); - } - if (ss != null) { + socket = new Socket(); + socket.connect(new InetSocketAddress(port), 200); + socket.close(); + return true; + } catch (Exception ex) { + return false; + } finally { + if (socket != null) { try { - ss.close(); + socket.close(); } catch (IOException e) { /* should not be thrown */ } } - } - return false; + } } public Set getTakenPorts() { From 77570478576e5ff713824438d0c43a221c3f1935 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 30 May 2014 23:24:22 +0200 Subject: [PATCH 180/185] Fixing tunneling stuff. --- .../manager/core/ManagerController.java | 24 +++++++------------ .../manager/core/ssh/DefaultSSHTunnel.java | 2 +- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 28b4450f..fee25e1b 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -198,24 +198,22 @@ public void removeInstance(String accessId, String instanceId) { } private void removeInstance(String accessId, String instanceId, Request request) { - sshTunnel.release(request); if (isLocal(request)) { this.computePlugin.removeInstance(accessId, instanceId); } else { removeRemoteInstance(request); } - - if (request.getState().equals(RequestState.DELETED)){ - requests.exclude(request.getId()); - } else { - request.setInstanceId(null); - request.setMemberId(null); - instanceRemoved(request); - } + instanceRemoved(request); } private void instanceRemoved(Request request) { - if (isPersistent(request)) { + sshTunnel.release(request); + request.setInstanceId(null); + request.setMemberId(null); + + if (request.getState().equals(RequestState.DELETED)){ + requests.exclude(request.getId()); + } else if (isPersistent(request)) { LOGGER.debug("Request: " + request + ", setting state to " + RequestState.OPEN); request.setState(RequestState.OPEN); if (!requestSchedulerTimer.isScheduled()) { @@ -392,11 +390,7 @@ protected void monitorInstances() { getInstance(request); } catch (OCCIException e) { LOGGER.debug("Error while getInstance of " + request.getInstanceId(), e); - if (request.getState().in(RequestState.FULFILLED)) { - instanceRemoved(requests.get(request.getId())); - } else if (request.getState().in(RequestState.DELETED)) { - requests.exclude(request.getId()); - } + instanceRemoved(requests.get(request.getId())); } } } diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index 61639112..b4eda48c 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -42,7 +42,7 @@ public void create(Properties properties, Request request) throws FileNotFoundEx Integer sshPort = null; for (Integer i = portFloor; i <= portCeiling; i++) { - if (!takenPorts.contains(i) && available(i)) { + if (!takenPorts.contains(i)/* && available(i)*/) { sshPort = i; takenPorts.add(i); break; From 8accdc133c2ac2660dab1f3a98ac3881b1744f48 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 30 May 2014 23:43:04 +0200 Subject: [PATCH 181/185] Avoid reuse of the same instance of xOCCIAtt --- .../java/org/fogbowcloud/manager/core/ManagerController.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index fee25e1b..8a1494f6 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -344,7 +344,8 @@ public List createRequests(String accessId, List categories, List currentRequests = new ArrayList(); for (int i = 0; i < instanceCount; i++) { String requestId = String.valueOf(UUID.randomUUID()); - Request request = new Request(requestId, userToken, categories, xOCCIAtt); + Request request = new Request(requestId, userToken, + new LinkedList(categories), new HashMap(xOCCIAtt)); try { sshTunnel.create(properties, request); } catch (Exception e) { From e8e4be9bd7ef7e8b3f3d91558c5a0f295216e3f0 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Fri, 30 May 2014 23:46:30 +0200 Subject: [PATCH 182/185] Reverting DefaultSSHTunnel to its default behaviour. --- .../manager/core/ssh/DefaultSSHTunnel.java | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index b4eda48c..ebf4bb92 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -3,8 +3,8 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; +import java.net.DatagramSocket; +import java.net.ServerSocket; import java.util.HashSet; import java.util.Properties; import java.util.Set; @@ -42,7 +42,7 @@ public void create(Properties properties, Request request) throws FileNotFoundEx Integer sshPort = null; for (Integer i = portFloor; i <= portCeiling; i++) { - if (!takenPorts.contains(i)/* && available(i)*/) { + if (!takenPorts.contains(i) && available(i)) { sshPort = i; takenPorts.add(i); break; @@ -70,23 +70,28 @@ public void release(Request request) { } private static boolean available(int port) { - Socket socket = null; + ServerSocket ss = null; + DatagramSocket ds = null; try { - socket = new Socket(); - socket.connect(new InetSocketAddress(port), 200); - socket.close(); - return true; - } catch (Exception ex) { - return false; - } finally { - if (socket != null) { + ss = new ServerSocket(port); + ss.setReuseAddress(true); + ds = new DatagramSocket(port); + ds.setReuseAddress(true); + return true; + } catch (IOException e) { + } finally { + if (ds != null) { + ds.close(); + } + if (ss != null) { try { - socket.close(); + ss.close(); } catch (IOException e) { /* should not be thrown */ } } - } + } + return false; } public Set getTakenPorts() { From b3f2c0424c5e3fce923ebd897bac0eefd36d186a Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sun, 1 Jun 2014 02:06:21 +0200 Subject: [PATCH 183/185] Using Schedulers intead of Timers --- .../manager/core/ManagerController.java | 10 +++++-- .../manager/core/ManagerTimer.java | 28 +++++++++++-------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 8a1494f6..186ba8d6 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -8,6 +8,8 @@ import java.util.Properties; import java.util.TimerTask; import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; import org.apache.http.HttpStatus; import org.apache.log4j.Logger; @@ -41,9 +43,11 @@ public class ManagerController { private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 // minutes - private ManagerTimer requestSchedulerTimer = new ManagerTimer(); - private ManagerTimer tokenUpdaterTimer = new ManagerTimer(); - private ManagerTimer instanceMonitoringTimer = new ManagerTimer(); + private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); + + private ManagerTimer requestSchedulerTimer = new ManagerTimer(executor); + private ManagerTimer tokenUpdaterTimer = new ManagerTimer(executor); + private ManagerTimer instanceMonitoringTimer = new ManagerTimer(executor); private Token federationUserToken; private List members = new LinkedList(); diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java b/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java index 22b067af..40f1a0f8 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerTimer.java @@ -1,28 +1,32 @@ package org.fogbowcloud.manager.core; -import java.util.Timer; -import java.util.TimerTask; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; public class ManagerTimer { - private Timer timer; - private boolean scheduled; + private ScheduledExecutorService executor; + private ScheduledFuture future; - public void scheduleAtFixedRate(TimerTask task, long delay, long period) { - timer = new Timer(); - timer.scheduleAtFixedRate(task, delay, period); - scheduled = true; + public ManagerTimer(ScheduledExecutorService executor) { + this.executor = executor; + } + + public void scheduleAtFixedRate(Runnable task, long delay, long period) { + this.future = executor.scheduleWithFixedDelay(task, delay, + period, TimeUnit.MILLISECONDS); } public void cancel() { - if (timer != null) { - timer.cancel(); + if (future != null) { + future.cancel(false); } - scheduled = false; + future = null; } public boolean isScheduled() { - return scheduled; + return future != null && !future.isCancelled(); } } From 9648ef9b9451ba3ba9bc211d94b38b11468b3832 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Sun, 1 Jun 2014 18:22:09 +0200 Subject: [PATCH 184/185] Creating SSH tunnel during instance creation. --- .../manager/core/ManagerController.java | 55 ++++++++++++++----- .../manager/core/ssh/DefaultSSHTunnel.java | 49 ++++++++++++++--- .../manager/core/ssh/SSHTunnel.java | 10 +++- .../manager/core/util/ManagerTestHelper.java | 1 + .../occi/core/ssh/TestDefaultSSHTunnel.java | 42 ++++++++++---- 5 files changed, 122 insertions(+), 35 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index 186ba8d6..a5d5a5af 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -168,15 +168,15 @@ private Instance getInstance(Request request) { + " is local, getting its information in the local cloud."); instance = this.computePlugin.getInstance(request.getToken().getAccessId(), request.getInstanceId()); + String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT); + if (sshAddress != null) { + instance.addAttribute(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT, sshAddress); + } } else { LOGGER.debug(request.getInstanceId() + " is remote, going out to " + request.getMemberId() + " to get its information."); instance = getRemoteInstance(request); } - String sshAddress = request.getAttValue(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT); - if (sshAddress != null) { - instance.addAttribute(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT, sshAddress); - } return instance; } @@ -211,7 +211,7 @@ private void removeInstance(String accessId, String instanceId, Request request) } private void instanceRemoved(Request request) { - sshTunnel.release(request); + sshTunnel.release(request.getInstanceId()); request.setInstanceId(null); request.setMemberId(null); @@ -278,7 +278,7 @@ public FederationMember getFederationMember(String memberId) { public String createInstanceForRemoteMember(String memberId, List categories, Map xOCCIAtt) { - + Integer sshPort = null; FederationMember member = getFederationMember(memberId); if (!validator.canDonateTo(member)) { return null; @@ -287,8 +287,21 @@ public String createInstanceForRemoteMember(String memberId, List cate + xOCCIAtt + " for remote member."); String federationTokenAccessId = getFederationUserToken().getAccessId(); try { - return computePlugin.requestInstance(federationTokenAccessId, categories, xOCCIAtt); + sshPort = sshTunnel.create(properties, new Request(null, null, categories, xOCCIAtt)); + } catch (Exception e) { + LOGGER.warn("Exception while creating ssh tunnel.", e); + return null; + } + try { + String instanceId = computePlugin.requestInstance(federationTokenAccessId, categories, xOCCIAtt); + if (instanceId != null) { + sshTunnel.update(instanceId, sshPort); + } else { + sshTunnel.release(sshPort); + } + return instanceId; } catch (OCCIException e) { + sshTunnel.release(sshPort); if (e.getStatus().getCode() == HttpStatus.SC_BAD_REQUEST) { return null; } @@ -319,7 +332,12 @@ public Instance getInstanceForRemoteMember(String instanceId) { LOGGER.info("Getting instance " + instanceId + " for remote member."); String federationTokenAccessId = getFederationUserToken().getAccessId(); try { - return computePlugin.getInstance(federationTokenAccessId, instanceId); + Instance instance = computePlugin.getInstance(federationTokenAccessId, instanceId); + String sshAddress = sshTunnel.getPublicAddress(properties, instanceId); + if (sshAddress != null) { + instance.addAttribute(DefaultSSHTunnel.SSH_PUBLIC_ADDRESS_ATT, sshAddress); + } + return instance; } catch (OCCIException e) { LOGGER.warn("Exception while getting instance " + instanceId + " for remote member.", e); if (e.getStatus().getCode() == HttpStatus.SC_NOT_FOUND) { @@ -333,6 +351,7 @@ public void removeInstanceForRemoteMember(String instanceId) { LOGGER.info("Removing instance " + instanceId + " for remote member."); String federationTokenAccessId = getFederationUserToken().getAccessId(); computePlugin.removeInstance(federationTokenAccessId, instanceId); + sshTunnel.release(instanceId); } public List createRequests(String accessId, List categories, @@ -350,12 +369,6 @@ public List createRequests(String accessId, List categories, String requestId = String.valueOf(UUID.randomUUID()); Request request = new Request(requestId, userToken, new LinkedList(categories), new HashMap(xOCCIAtt)); - try { - sshTunnel.create(properties, request); - } catch (Exception e) { - LOGGER.warn("Exception while creating ssh tunnel.", e); - request.setState(RequestState.FAILED); - } LOGGER.info("Created request: " + request); currentRequests.add(request); requests.addRequest(userToken.getUser(), request); @@ -478,16 +491,29 @@ private boolean createRemoteInstance(Request request) { private boolean createLocalInstance(Request request) { request.setMemberId(null); String instanceId = null; + Integer port = null; LOGGER.info("Submiting local request " + request); try { + try { + port = sshTunnel.create(properties, request); + } catch (Exception e) { + LOGGER.warn("Exception while creating ssh tunnel.", e); + request.setState(RequestState.FAILED); + return false; + } instanceId = computePlugin.requestInstance(request.getToken().getAccessId(), request.getCategories(), request.getxOCCIAtt()); if (instanceId == null) { + sshTunnel.release(port); return false; } + sshTunnel.update(instanceId, port); } catch (OCCIException e) { + if (port != null) { + sshTunnel.release(port); + } if (e.getStatus().getCode() == HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE) { LOGGER.warn("Request failed locally for quota exceeded.", e); return false; @@ -497,6 +523,7 @@ private boolean createLocalInstance(Request request) { LOGGER.warn("Request failed locally for an unknown reason.", e); return true; } + } request.setInstanceId(instanceId); diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java index ebf4bb92..e728e399 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/DefaultSSHTunnel.java @@ -5,7 +5,9 @@ import java.io.IOException; import java.net.DatagramSocket; import java.net.ServerSocket; +import java.util.HashMap; import java.util.HashSet; +import java.util.Map; import java.util.Properties; import java.util.Set; @@ -21,12 +23,23 @@ public class DefaultSSHTunnel implements SSHTunnel { public static final String USER_DATA_ATT = "org.fogbowcloud.request.user-data"; public static final String SSH_ADDRESS_ATT = "org.fogbowcloud.request.ssh-address"; public static final String SSH_PUBLIC_ADDRESS_ATT = "org.fogbowcloud.request.ssh-public-address"; + private Set takenPorts = new HashSet(); + private Map instanceToPort = new HashMap(); - public void create(Properties properties, Request request) throws FileNotFoundException, IOException { + public Integer create(Properties properties, Request request) throws FileNotFoundException, IOException { - request.addCategory(new Category(RequestConstants.USER_DATA_TERM, - RequestConstants.SCHEME, RequestConstants.MIXIN_CLASS)); + boolean hasCategory = false; + for (Category category : request.getCategories()) { + if (category.getTerm().equals(RequestConstants.USER_DATA_TERM)) { + hasCategory = true; + break; + } + } + if (!hasCategory) { + request.addCategory(new Category(RequestConstants.USER_DATA_TERM, + RequestConstants.SCHEME, RequestConstants.MIXIN_CLASS)); + } String sshTunnelCmd = IOUtils.toString(new FileInputStream("bin/fogbow-inject-tunnel")); String sshPrivateHostIP = properties.getProperty("ssh_tunnel_private_host"); @@ -57,16 +70,34 @@ public void create(Properties properties, Request request) throws FileNotFoundEx sshTunnelCmd.getBytes(Charsets.UTF_8))); request.putAttValue(SSH_ADDRESS_ATT, sshPrivateHostIP + ":" + sshPort); request.putAttValue(SSH_PUBLIC_ADDRESS_ATT, sshPublicHostIP + ":" + sshPort); + + return sshPort; + } + + public void update(String instanceId, Integer port) { + instanceToPort.put(instanceId, port); } - public void release(Request request) { - String sshAddress = request.getAttValue(SSH_ADDRESS_ATT); - if (sshAddress == null) { + public void release(String instanceId) { + if (instanceId == null) { return; } - String[] sshAddressSplit = sshAddress.split(":"); - int sshPort = Integer.parseInt(sshAddressSplit[1]); - takenPorts.remove(sshPort); + Integer port = instanceToPort.remove(instanceId); + release(port); + } + + public void release(Integer port) { + if (port == null) { + return; + } + takenPorts.remove(port); + } + + @Override + public String getPublicAddress(Properties properties, String instanceId) { + String sshPublicHostIP = properties.getProperty("ssh_tunnel_public_host"); + Integer port = instanceToPort.get(instanceId); + return sshPublicHostIP + ":" + port; } private static boolean available(int port) { diff --git a/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java b/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java index 05bfcd1d..d0dcc05a 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java +++ b/src/main/java/org/fogbowcloud/manager/core/ssh/SSHTunnel.java @@ -6,8 +6,14 @@ public interface SSHTunnel { - public void create(Properties properties, Request request) throws Exception; + public Integer create(Properties properties, Request request) throws Exception; - public void release(Request request); + public void update(String instanceId, Integer port); + + public void release(String instanceId); + + public void release(Integer port); + + public String getPublicAddress(Properties properties, String instanceId); } diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index edeaef98..7c083f3f 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -166,6 +166,7 @@ public ManagerXmppComponent initializeXMPPManagerComponent(boolean init) throws managerXmppComponent.setDescription("Manager Component"); managerXmppComponent.setName("Manager"); managerXmppComponent.setRendezvousAddress(CLIENT_ADRESS + SMACK_ENDING); + managerXmppComponent.getManagerFacade().setSSHTunnel(Mockito.mock(SSHTunnel.class)); fakeServer.connect(managerXmppComponent); managerXmppComponent.process(); if (init) { diff --git a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java index ac6346ef..3384d6c7 100644 --- a/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java +++ b/src/test/java/org/fogbowcloud/manager/occi/core/ssh/TestDefaultSSHTunnel.java @@ -8,7 +8,6 @@ import java.util.Date; import java.util.HashMap; import java.util.HashSet; -import java.util.Map; import java.util.Properties; import java.util.Set; @@ -21,7 +20,6 @@ import org.fogbowcloud.manager.occi.request.RequestConstants; import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; public class TestDefaultSSHTunnel { @@ -68,26 +66,50 @@ public void create() throws FileNotFoundException, IOException { } @Test - public void release() { + public void releasePort() { final int port = 50000; final int port2 = 50001; Set takenPorts = new HashSet(); takenPorts.add(port); takenPorts.add(port2); defaultSSHTunnel.setTakenPorts(takenPorts); - String sshAddressAtt = "10.0.0.1:50000"; - - Map attribute = new HashMap(); - attribute.put(DefaultSSHTunnel.SSH_ADDRESS_ATT, sshAddressAtt); - Request request = new Request("id", new Token("accessId", "user", new Date(), - new HashMap()), new ArrayList(), attribute); Assert.assertEquals(2, defaultSSHTunnel.getTakenPorts().size()); - defaultSSHTunnel.release(request); + defaultSSHTunnel.release(port); Assert.assertEquals(1, defaultSSHTunnel.getTakenPorts().size()); } + + @Test + public void releaseInstanceId() throws FileNotFoundException, IOException { + final String privateHostIP = "10.0.0.1"; + final String publicHostIP = "150.165.80.1"; + final String user = "fogbow"; + final String portRanger = "50000:59999"; + final String port = "50000"; + + String sshTunnelCmd = getScriptFogbowInjectTunnel(); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_USER#", user); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_HOST#", privateHostIP); + sshTunnelCmd = sshTunnelCmd.replace("#REMOTE_PORT#", port); + + Properties properties = new Properties(); + properties.put("ssh_tunnel_public_host", publicHostIP); + properties.put("ssh_tunnel_private_host", privateHostIP); + properties.put("ssh_tunnel_user", user); + properties.put("ssh_tunnel_port_range", portRanger); + Request request = new Request("is", new Token("accessId", "user", new Date(), + new HashMap()), new ArrayList(), + new HashMap()); + + defaultSSHTunnel.update("instanceId", + defaultSSHTunnel.create(properties, request)); + + defaultSSHTunnel.release("instanceId"); + + Assert.assertTrue(defaultSSHTunnel.getTakenPorts().isEmpty()); + } @SuppressWarnings("resource") private String getScriptFogbowInjectTunnel() { From 0872193e2612f043d36ee4343250cd15995e65a7 Mon Sep 17 00:00:00 2001 From: Abmar Barros Date: Mon, 2 Jun 2014 04:42:03 +0200 Subject: [PATCH 185/185] Removing race conditions from the tests by mocking the executor. --- .../manager/core/ManagerController.java | 17 +++++++----- .../manager/core/TestManagerController.java | 26 ++++++++++--------- .../core/util/DefaultDataTestHelper.java | 2 +- .../manager/core/util/ManagerTestHelper.java | 4 ++- 4 files changed, 29 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java index a5d5a5af..a699ccb8 100644 --- a/src/main/java/org/fogbowcloud/manager/core/ManagerController.java +++ b/src/main/java/org/fogbowcloud/manager/core/ManagerController.java @@ -43,11 +43,9 @@ public class ManagerController { private static final long DEFAULT_INSTANCE_MONITORING_PERIOD = 120000; // 2 // minutes - private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10); - - private ManagerTimer requestSchedulerTimer = new ManagerTimer(executor); - private ManagerTimer tokenUpdaterTimer = new ManagerTimer(executor); - private ManagerTimer instanceMonitoringTimer = new ManagerTimer(executor); + private final ManagerTimer requestSchedulerTimer; + private final ManagerTimer tokenUpdaterTimer; + private final ManagerTimer instanceMonitoringTimer; private Token federationUserToken; private List members = new LinkedList(); @@ -64,10 +62,17 @@ public class ManagerController { private SSHTunnel sshTunnel = new DefaultSSHTunnel(); public ManagerController(Properties properties) { - this.properties = properties; + this(properties, Executors.newScheduledThreadPool(10)); + } + + public ManagerController(Properties properties, ScheduledExecutorService executor) { if (properties == null) { throw new IllegalArgumentException(); } + this.properties = properties; + this.requestSchedulerTimer = new ManagerTimer(executor); + this.tokenUpdaterTimer = new ManagerTimer(executor); + this.instanceMonitoringTimer = new ManagerTimer(executor); } public void setSSHTunnel(SSHTunnel sshTunnel) { diff --git a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java index 87741545..2978841a 100644 --- a/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java +++ b/src/test/java/org/fogbowcloud/manager/core/TestManagerController.java @@ -517,6 +517,7 @@ public void testPersistentRequestSetFulfilledAndOpen() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); // updating compute mock + Mockito.reset(managerTestHelper.getComputePlugin()); Mockito.when( managerTestHelper.getComputePlugin().requestInstance(Mockito.anyString(), Mockito.any(List.class), Mockito.any(Map.class))).thenThrow( @@ -740,6 +741,8 @@ public void testOneTimeRequestSetOpenAndClosed() throws InterruptedException { // waiting expiration time Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); + // checking if request state was set to closed requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -866,8 +869,8 @@ public void testPersistentRequestWithValidFromAttInFuture() throws InterruptedEx @Test public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedException { long now = System.currentTimeMillis(); - long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); + long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); + long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 6); // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.ONE_TIME.getValue()); @@ -882,9 +885,6 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - // waiting for a time and request is not valid yet - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - // request is not in valid period yet List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -896,8 +896,10 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti Assert.assertNull(requests.get(0).getMemberId()); // sleeping for the scheduler period and submitting request - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 3 + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); + // checking is request is fulfilled requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); @@ -937,7 +939,7 @@ public void testOneTimeRequestValidityPeriodInFuture() throws InterruptedExcepti public void testPersistentRequestValidityPeriodInFuture() throws InterruptedException { long now = System.currentTimeMillis(); long startRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 2); - long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 3); + long expirationRequestTime = now + (DefaultDataTestHelper.SCHEDULER_PERIOD * 4); // setting request attributes xOCCIAtt.put(RequestAttribute.TYPE.getValue(), RequestType.PERSISTENT.getValue()); @@ -952,9 +954,6 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce managerController.createRequests(DefaultDataTestHelper.ACCESS_TOKEN_ID, new ArrayList(), xOCCIAtt); - // waiting for a time and request is not valid yet - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); - // request is not in valid period yet List requests = managerController .getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -966,7 +965,8 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce Assert.assertNull(requests.get(0).getMemberId()); // waiting for a time and request is into valid period - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 2 + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); // checking is request is fulfilled requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); @@ -991,8 +991,10 @@ public void testPersistentRequestValidityPeriodInFuture() throws InterruptedExce DefaultDataTestHelper.INSTANCE_ID); // waiting for the scheduler period so that request is not into valid period anymore - Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD + DefaultDataTestHelper.GRACE_TIME); + Thread.sleep(DefaultDataTestHelper.SCHEDULER_PERIOD * 2 + DefaultDataTestHelper.GRACE_TIME); + managerController.checkAndSubmitOpenRequests(); + // checking if request is not in valid period anymore requests = managerController.getRequestsFromUser(DefaultDataTestHelper.ACCESS_TOKEN_ID); Assert.assertEquals(1, requests.size()); diff --git a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java index 8df26802..2f1ef3e8 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/DefaultDataTestHelper.java @@ -21,7 +21,7 @@ public class DefaultDataTestHelper { //time data public static final Long SCHEDULER_PERIOD = 500L; - public static final Long GRACE_TIME = 30L; + public static final Long GRACE_TIME = 250L; public static final long LONG_TIME = 1 * 24 * 60 * 60 * 1000; //one day public static final Date TOKEN_FUTURE_EXPIRATION = new Date(System.currentTimeMillis() + LONG_TIME); diff --git a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java index 7c083f3f..9f89deb1 100644 --- a/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java +++ b/src/test/java/org/fogbowcloud/manager/core/util/ManagerTestHelper.java @@ -11,6 +11,7 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.concurrent.ScheduledExecutorService; import org.dom4j.Attribute; import org.dom4j.Element; @@ -282,7 +283,8 @@ public ManagerController createDefaultManagerController() { properties.put("scheduler_period", DefaultDataTestHelper.SCHEDULER_PERIOD.toString()); properties .put("instance_monitoring_period", Long.toString(DefaultDataTestHelper.LONG_TIME)); - ManagerController managerController = new ManagerController(properties); + ManagerController managerController = new ManagerController(properties, + Mockito.mock(ScheduledExecutorService.class)); // mocking compute computePlugin = Mockito.mock(ComputePlugin.class);