[rhq] 3 commits - .mailmap modules/enterprise modules/integration-tests
by Heiko W. Rupp
.mailmap | 1
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AbstractRestBean.java | 40
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertDefinitionHandlerBean.java | 88 -
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerBean.java | 16
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/CustomExceptionMapper.java | 26
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerBean.java | 185 +-
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ParameterMissingException.java | 3
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ReportsHandlerBean.java | 20
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java | 9
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RootHandlerBean.java | 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/SetCallerInterceptor.java | 7
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerBean.java | 4
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerBean.java | 57
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/domain/AlertDefinitionRest.java | 24
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/helper/ConfigurationHelper.java | 432 +++++
modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/ConfigurationHelperTest.java | 756 ++++++++++
modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/AlertTest.java | 22
modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/OperationsTest.java | 188 ++
modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/ResourcesTest.java | 49
modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/RootURITest.java | 2
modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/d/AlertDefinition.java | 21
21 files changed, 1743 insertions(+), 209 deletions(-)
New commits:
commit db8f9686b96e2e3c44e61162b1a0d2d388fc59e9
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 8 13:48:42 2013 +0200
BZ 960529 - check for non-existing resources when obtaining availability
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java
index 4e00625..3e1d195 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java
@@ -338,6 +338,10 @@ public class ResourceHandlerBean extends AbstractRestBean {
@ApiParam(value="Start time", defaultValue = "30 days ago") @QueryParam("start") long start,
@ApiParam(value="End time", defaultValue = "Now") @QueryParam("end") long end,
@Context HttpHeaders headers) {
+
+ // Vaildate it the resource exists
+ fetchResource(resourceId);
+
if (end==0)
end = System.currentTimeMillis();
diff --git a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/ResourcesTest.java b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/ResourcesTest.java
index 1dee0f1..c71bbd8 100644
--- a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/ResourcesTest.java
+++ b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/ResourcesTest.java
@@ -499,6 +499,22 @@ public class ResourcesTest extends AbstractBase {
}
@Test
+ public void testCreateChildForUnknownParent() throws Exception {
+
+ given()
+ .body("{\"value\":\"CPU\"}") // Type of new resource
+ .header("Content-Type", "application/json")
+ .header("Accept", "application/json")
+ .pathParam("name", "test")
+ .queryParam("plugin", "Platforms")
+ .queryParam("parentId", 321)
+ .expect()
+ .statusCode(404)
+ .log().ifError()
+ .when().post("/resource/{name}");
+ }
+
+ @Test
public void testAlertsForResource() throws Exception {
given()
.header("Accept", "application/json")
@@ -521,6 +537,17 @@ public class ResourcesTest extends AbstractBase {
}
@Test
+ public void testSchedulesForUnknownResource() throws Exception {
+ given()
+ .header("Accept", "application/json")
+ .pathParam("id", 123)
+ .expect()
+ .statusCode(404)
+ .when()
+ .get("/resource/{id}/schedules");
+ }
+
+ @Test
public void testAvailabilityForResourceJson() throws Exception {
given()
.header(acceptJson)
@@ -532,6 +559,17 @@ public class ResourcesTest extends AbstractBase {
}
@Test
+ public void testAvailabilityForUnknownResource() throws Exception {
+ given()
+ .header(acceptJson)
+ .pathParam("id", 532)
+ .expect()
+ .statusCode(404)
+ .when()
+ .get("/resource/{id}/availability");
+ }
+
+ @Test
public void testAvailabilityForResourceXml() throws Exception {
given()
.header(acceptXml)
@@ -554,6 +592,17 @@ public class ResourcesTest extends AbstractBase {
}
@Test
+ public void testAvailabilityHistoryForUnknownResource() throws Exception {
+ given()
+ .header(acceptJson)
+ .pathParam("id", -42)
+ .expect()
+ .statusCode(404)
+ .when()
+ .get("/resource/{id}/availability/history");
+ }
+
+ @Test
public void testAvailabilityHistoryForResourceXml() throws Exception {
given()
.header(acceptXml)
commit 17c3db8f19d0b70a6f0d910450523c245cd6f8b9
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 8 09:17:48 2013 +0200
Code cleanup and improvements for the REST-api
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AbstractRestBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AbstractRestBean.java
index 2746823..7a198bd 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AbstractRestBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AbstractRestBean.java
@@ -81,21 +81,21 @@ import org.rhq.enterprise.server.rest.domain.ResourceWithType;
@SuppressWarnings("unchecked")
public class AbstractRestBean {
- Log log = LogFactory.getLog(getClass().getName());
+ protected Log log = LogFactory.getLog(getClass().getName());
- static private final CacheKey META_KEY = new CacheKey("rhq.rest.resourceMeta", 0);
+ private static final CacheKey META_KEY = new CacheKey("rhq.rest.resourceMeta", 0);
@javax.annotation.Resource( name = "ISPN")
- protected CacheContainer container;
+ private CacheContainer container;
protected Cache<CacheKey, Object> cache;
/** Subject of the caller that gets injected via {@link SetCallerInterceptor} */
protected Subject caller;
@EJB
- ResourceManagerLocal resMgr;
+ protected ResourceManagerLocal resMgr;
@EJB
- ResourceGroupManagerLocal resourceGroupManager;
+ protected ResourceGroupManagerLocal resourceGroupManager;
@PostConstruct
public void start() {
@@ -116,15 +116,15 @@ public class AbstractRestBean {
freemarker.template.Configuration config = new freemarker.template.Configuration();
// XXX fall-over to ClassTL after failure in FTL seems not to work
- // FileTemplateLoader ftl = new FileTemplateLoader(new File("src/main/resources"));
ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "/rest_templates/");
TemplateLoader[] loaders = new TemplateLoader[] { ctl };
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
config.setTemplateLoader(mtl);
- if (!templateName.endsWith(".ftl"))
+ if (!templateName.endsWith(".ftl")) {
templateName = templateName + ".ftl";
+ }
Template template = config.getTemplate(templateName);
StringWriter out = new StringWriter();
@@ -171,8 +171,9 @@ public class AbstractRestBean {
CacheValue value = (CacheValue) cache.get(key);
+ boolean debugEnabled = log.isDebugEnabled();
if (null != value) {
- if (log.isDebugEnabled()) {
+ if (debugEnabled) {
log.debug("Cache Hit for " + key);
}
@@ -180,12 +181,12 @@ public class AbstractRestBean {
o = value.getValue();
} else {
- if (log.isDebugEnabled()) {
+ if (debugEnabled) {
log.debug("Cache Hit ignored, caller " + caller.toString() + " not found");
}
}
} else {
- if (log.isDebugEnabled()) {
+ if (debugEnabled) {
log.debug("Cache Miss for " + key);
}
}
@@ -351,8 +352,9 @@ public class AbstractRestBean {
Resource parent = res.getParentResource();
if (parent != null) {
rwt.setParentId(parent.getId());
- } else
+ } else {
rwt.setParentId(0);
+ }
rwt.setAncestry(res.getAncestry());
@@ -429,8 +431,9 @@ public class AbstractRestBean {
protected ResourceGroup fetchGroup(int groupId, boolean requireCompatible) {
ResourceGroup resourceGroup;
resourceGroup = resourceGroupManager.getResourceGroup(caller, groupId);
- if (resourceGroup == null)
+ if (resourceGroup == null) {
throw new StuffNotFoundException("Group with id " + groupId);
+ }
if (requireCompatible) {
if (resourceGroup.getGroupCategory() != GroupCategory.COMPATIBLE) {
throw new BadArgumentException("Group with id " + groupId,"it is no compatible group");
@@ -445,8 +448,9 @@ public class AbstractRestBean {
gr.setId(group.getId());
gr.setCategory(group.getGroupCategory());
gr.setRecursive(group.isRecursive());
- if (group.getGroupDefinition()!=null)
+ if (group.getGroupDefinition()!=null) {
gr.setDynaGroupDefinitionId(group.getGroupDefinition().getId());
+ }
gr.setExplicitCount(group.getExplicitResources().size());
gr.setImplicitCount(group.getImplicitResources().size());
UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
@@ -526,16 +530,6 @@ public class AbstractRestBean {
return ms;
}
- Configuration mapToConfiguration(Map<String,Object> in) {
- Configuration config = new Configuration();
- for (Map.Entry<String,Object> entry : in.entrySet()) {
- config.put(new PropertySimple(entry.getKey(),entry.getValue())); // TODO honor more types
- }
-
- return config;
-
- }
-
/**
* Set the caching header on the response
* @param builder Response builder to put the caching header on
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertDefinitionHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertDefinitionHandlerBean.java
index 06bc8ae..d203cd3 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertDefinitionHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertDefinitionHandlerBean.java
@@ -106,22 +106,22 @@ import org.rhq.enterprise.server.rest.domain.Link;
public class AlertDefinitionHandlerBean extends AbstractRestBean {
@EJB
- AlertDefinitionManagerLocal alertDefinitionManager;
+ private AlertDefinitionManagerLocal alertDefinitionManager;
@EJB
- AlertNotificationManagerLocal notificationMgr;
+ private AlertNotificationManagerLocal notificationMgr;
@EJB
- AlertConditionManagerLocal conditionMgr;
+ private AlertConditionManagerLocal conditionMgr;
@EJB
- AlertManagerLocal alertManager;
+ private AlertManagerLocal alertManager;
@EJB
- ResourceGroupManagerLocal resourceGroupMgr;
+ private ResourceGroupManagerLocal resourceGroupMgr;
@EJB
- ResourceTypeManagerLocal resourceTypeMgr;
+ private ResourceTypeManagerLocal resourceTypeMgr;
@PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME)
@@ -169,8 +169,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
@Context Request request, @Context UriInfo uriInfo) {
AlertDefinition def = alertDefinitionManager.getAlertDefinition(caller, definitionId);
- if (def==null)
+ if (def==null) {
throw new StuffNotFoundException("AlertDefinition with id " + definitionId );
+ }
EntityTag eTag = new EntityTag(Integer.toHexString(def.hashCode()));
Response.ResponseBuilder builder = request.evaluatePreconditions(eTag);
@@ -285,8 +286,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
@Context UriInfo uriInfo) {
AlertDefinition definition = alertDefinitionManager.getAlertDefinition(caller,definitionId);
- if (definition==null)
+ if (definition==null) {
throw new StuffNotFoundException("AlertDefinition with id " + definitionId);
+ }
definition = new AlertDefinition(definition); // detach
@@ -302,10 +304,12 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
// Set the recovery id if such a definition exists at all
if (definitionRest.getRecoveryId()>0) {
AlertDefinition recoveryDef = alertDefinitionManager.getAlertDefinition(caller,definitionRest.getRecoveryId());
- if (recoveryDef!=null)
+ if (recoveryDef!=null) {
definition.setRecoveryId(definitionRest.getRecoveryId());
- else
+ }
+ else {
throw new StuffNotFoundException("Alert to recover with id " + definitionRest.getRecoveryId());
+ }
}
@@ -348,34 +352,24 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < vals.length ; i++) {
builder.append(vals[i].name());
- if (i < vals.length-1)
+ if (i < vals.length-1) {
builder.append(", ");
+ }
}
throw new BadArgumentException("dampening category","Allowed values are: " + builder.toString());
}
AlertDampening dampening = new AlertDampening(dampeningCategory);
- if (adr.getDampeningCount()!=null) {
- if (adr.getDampeningCount().contains(" ")) {
- String tmp = adr.getDampeningCount().trim();
- int num = Integer.parseInt(tmp.substring(0,tmp.indexOf(' ')));
- tmp = tmp.substring(tmp.lastIndexOf(' ')).trim();
- dampening.setValue(num);
- dampening.setValueUnits(AlertDampening.TimeUnits.valueOf(tmp.toUpperCase()));
- }
- else {
- dampening.setValue(Integer.parseInt(adr.getDampeningCount()));
- }
- }
- if (adr.getDampeningPeriod()!=null) {
- if (adr.getDampeningPeriod().contains(" ")) {
- String tmp = adr.getDampeningPeriod().trim();
- int num = Integer.parseInt(tmp.substring(0,tmp.indexOf(' ')));
- tmp = tmp.substring(tmp.lastIndexOf(' ')).trim();
- dampening.setPeriod(num);
- dampening.setPeriodUnits(AlertDampening.TimeUnits.valueOf(tmp.toUpperCase()));
- }
- else {
- dampening.setPeriod(Integer.parseInt(adr.getDampeningPeriod()));
+ if (adr.getDampeningCount()>-1) {
+ dampening.setValue(adr.getDampeningCount());
+ }
+ if (adr.getDampeningPeriod()>0) {
+ dampening.setPeriod(adr.getDampeningPeriod());
+ try {
+ if (adr.getDampeningUnit()!=null) {
+ dampening.setPeriodUnits(AlertDampening.TimeUnits.valueOf(adr.getDampeningUnit().toUpperCase()));
+ }
+ } catch (Exception e) {
+ throw new BadArgumentException("dampenign unit", "Allowed values are MINUTES,HOURS,DAYS, WEEKS");
}
}
@@ -439,8 +433,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
definition2 = entityManager.find(AlertDefinition.class,definitionId);
AlertCondition condition=null;
for (AlertCondition c: definition2.getConditions()) {
- if (c.getId() == conditionId)
+ if (c.getId() == conditionId) {
condition=c;
+ }
}
definition2.getConditions().remove(condition);
@@ -522,8 +517,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
@ApiParam("The id of the condition to retrieve") @PathParam("cid") int conditionId) {
AlertCondition condition = conditionMgr.getAlertConditionById(conditionId);
- if (condition==null)
+ if (condition==null) {
throw new StuffNotFoundException("No condition with id " + conditionId);
+ }
AlertConditionRest acr = conditionToConditionRest(condition);
return Response.ok(acr).build();
@@ -565,8 +561,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
AlertConditionRest result = conditionToConditionRest(createdCondition);
Response.ResponseBuilder builder;
- if (isCreate)
+ if (isCreate) {
builder = Response.created(uri);
+ }
else {
builder = Response.ok();
builder.location(uri);
@@ -583,8 +580,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
@ApiParam("The id of the notification definition to retrieve") @PathParam("nid") int notificationId) {
AlertNotification notification = notificationMgr.getAlertNotification(caller,notificationId);
- if (notification==null)
+ if (notification==null) {
throw new StuffNotFoundException("No notification with id " + notificationId);
+ }
AlertNotificationRest anr = notificationToNotificationRest(notification);
return Response.ok(anr).build();
@@ -618,8 +616,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
@ApiParam("The updated notification definition to use") AlertNotificationRest notificationRest) {
AlertNotification notification = notificationMgr.getAlertNotification(caller,notificationId);
- if (notification==null)
+ if (notification==null) {
throw new StuffNotFoundException("No notification with id " + notificationId);
+ }
AlertDefinition definition = alertDefinitionManager.getAlertDefinition(caller,notification.getAlertDefinition().getId());
@@ -634,8 +633,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
List<AlertNotification> notifications = definition.getAlertNotifications();
int newNotifId = 0;
for (AlertNotification n : notifications) {
- if (n.getSenderName().equals(notification.getSenderName()))
+ if (n.getSenderName().equals(notification.getSenderName())) {
newNotifId = n.getId();
+ }
}
AlertNotification result = notificationMgr.getAlertNotification(caller,newNotifId);
@@ -667,8 +667,9 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
// Now check if the definition exists as well
AlertDefinition definition = alertDefinitionManager.getAlertDefinition(caller,definitionId);
- if (definition==null)
+ if (definition==null) {
throw new StuffNotFoundException("AlertDefinition with id " + definitionId);
+ }
// definition and sender are valid, continue
int existingNotificationCount = definition.getAlertNotifications().size();
@@ -816,10 +817,13 @@ public class AlertDefinitionHandlerBean extends AbstractRestBean {
adr.setDampeningCategory(dampening.getCategory().name());
AlertDampening.TimeUnits units = dampening.getValueUnits();
String s = units != null ? " " + units.name() : "";
- adr.setDampeningCount(dampening.getValue() + s);
+ adr.setDampeningCount(dampening.getValue());
units = dampening.getPeriodUnits();
s = units != null ? " " + units.name() : "";
- adr.setDampeningPeriod(dampening.getPeriod() + s);
+ adr.setDampeningPeriod(dampening.getPeriod());
+ if (dampening.getPeriodUnits()!=null) {
+ adr.setDampeningUnit(dampening.getPeriodUnits().name());
+ }
if (def.getResource()!=null) {
adr.getLinks().add(createUILink(uriInfo,UILinkTemplate.RESOURCE_ALERT_DEF,def.getResource().getId(),adr.getId()));
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerBean.java
index 0a37a9d..4c80bd1 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/AlertHandlerBean.java
@@ -79,10 +79,8 @@ import org.rhq.enterprise.server.rest.domain.*;
@Interceptors(SetCallerInterceptor.class)
public class AlertHandlerBean extends AbstractRestBean {
-// private final Log log = LogFactory.getLog(AlertHandlerBean.class);
-
@EJB
- AlertManagerLocal alertManager;
+ private AlertManagerLocal alertManager;
@GZIP
@@ -107,10 +105,12 @@ public class AlertHandlerBean extends AbstractRestBean {
if (resourceId!=null && definitionId!=null) {
throw new BadArgumentException("At most one of 'resourceId' and 'definitionId' may be given");
}
- if (size==0)
+ if (size==0) {
throw new BadArgumentException("size","Must not be 0");
- if (page<1)
+ }
+ if (page<1) {
throw new BadArgumentException("page","Must be >=1");
+ }
AlertCriteria criteria = new AlertCriteria();
@@ -119,8 +119,9 @@ public class AlertHandlerBean extends AbstractRestBean {
pageControl.setPageNumber(page);
criteria.setPageControl(pageControl);
}
- else
+ else {
criteria.setPaging(page-1, size); // TODO implement linking to next page
+ }
if (since!=null) {
criteria.addFilterStartTime(since);
@@ -335,8 +336,9 @@ public class AlertHandlerBean extends AbstractRestBean {
AlertCriteria criteria = new AlertCriteria();
criteria.addFilterId(id);
List<Alert> alerts = alertManager.findAlertsByCriteria(caller,criteria);
- if (alerts.isEmpty())
+ if (alerts.isEmpty()) {
throw new StuffNotFoundException("Alert with id " + id);
+ }
return alerts.get(0);
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/CustomExceptionMapper.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/CustomExceptionMapper.java
index 07b2a1c..1099679 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/CustomExceptionMapper.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/CustomExceptionMapper.java
@@ -43,9 +43,9 @@ import org.rhq.enterprise.server.rest.domain.RHQErrorWrapper;
public class CustomExceptionMapper implements ExceptionMapper<Exception> {
@Context
- HttpHeaders httpHeaders;
+ private HttpHeaders httpHeaders;
- Log log = LogFactory.getLog(getClass().getName());
+ private Log log = LogFactory.getLog(getClass().getName());
@Override
public Response toResponse(Exception e) {
@@ -53,24 +53,25 @@ public class CustomExceptionMapper implements ExceptionMapper<Exception> {
Response.ResponseBuilder builder;
Response.Status status;
- if (e instanceof StuffNotFoundException)
+ if (e instanceof StuffNotFoundException) {
status =Response.Status.NOT_FOUND;
- else if (e instanceof ResourceNotFoundException)
+ } else if (e instanceof ResourceNotFoundException) {
status = Response.Status.NOT_FOUND;
- else if (e instanceof ResourceGroupNotFoundException)
+ } else if (e instanceof ResourceGroupNotFoundException) {
status = Response.Status.NOT_FOUND;
- else if (e instanceof ResourceTypeNotFoundException)
+ } else if (e instanceof ResourceTypeNotFoundException) {
status = Response.Status.NOT_FOUND;
- else if (e instanceof ParameterMissingException)
+ } else if (e instanceof ParameterMissingException) {
status = Response.Status.NOT_ACCEPTABLE;
- else if (e instanceof BadArgumentException)
+ } else if (e instanceof BadArgumentException) {
status = Response.Status.NOT_ACCEPTABLE;
- else if (e instanceof PermissionException)
+ } else if (e instanceof PermissionException) {
status = Response.Status.FORBIDDEN;
- else if (e instanceof EJBException && e.getCause()!=null && e.getCause() instanceof IllegalArgumentException)
+ } else if (e instanceof EJBException && e.getCause()!=null && e.getCause() instanceof IllegalArgumentException) {
status = Response.Status.NOT_ACCEPTABLE;
- else
+ } else {
status = Response.Status.SERVICE_UNAVAILABLE;
+ }
builder = Response.status(status);
String message = e.getMessage();
@@ -93,8 +94,9 @@ public class CustomExceptionMapper implements ExceptionMapper<Exception> {
log.debug(e.getMessage());
mediaType = MediaType.TEXT_PLAIN_TYPE;
}
- if (mediaType.getType().equals("text") && mediaType.getSubtype().equals("csv"))
+ if (mediaType.getType().equals("text") && mediaType.getSubtype().equals("csv")) {
mediaType = MediaType.TEXT_PLAIN_TYPE;
+ }
if (mediaType.equals(MediaType.TEXT_PLAIN_TYPE)) {
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerBean.java
index ccfed9f..8bc2cb9 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/OperationsHandlerBean.java
@@ -47,6 +47,8 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
+import com.wordnik.swagger.annotations.ApiError;
+import com.wordnik.swagger.annotations.ApiErrors;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
@@ -69,13 +71,17 @@ import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.domain.util.PageList;
import org.rhq.core.domain.util.PageOrdering;
+import org.rhq.core.domain.util.StringUtils;
+import org.rhq.enterprise.server.operation.OperationDefinitionNotFoundException;
import org.rhq.enterprise.server.operation.OperationManagerLocal;
import org.rhq.enterprise.server.resource.ResourceManagerLocal;
+import org.rhq.enterprise.server.resource.ResourceNotFoundException;
import org.rhq.enterprise.server.rest.domain.Link;
import org.rhq.enterprise.server.rest.domain.OperationDefinitionRest;
import org.rhq.enterprise.server.rest.domain.OperationHistoryRest;
import org.rhq.enterprise.server.rest.domain.OperationRest;
import org.rhq.enterprise.server.rest.domain.SimplePropDef;
+import org.rhq.enterprise.server.rest.helper.ConfigurationHelper;
/**
* Deal with operations
@@ -88,32 +94,31 @@ import org.rhq.enterprise.server.rest.domain.SimplePropDef;
public class OperationsHandlerBean extends AbstractRestBean {
@EJB
- OperationManagerLocal opsManager;
+ private OperationManagerLocal opsManager;
@EJB
- ResourceManagerLocal resourceManager;
+ private ResourceManagerLocal resourceManager;
@GET
@Path("definition/{id}")
@Cache(maxAge = 1200)
@ApiOperation("Retrieve a single operation definition by its id")
public Response getOperationDefinition(
- @ApiParam("Id of the definition to retrieve") @PathParam("id") int definitionId,
- @ApiParam("Id of a resource that supports this operation") @QueryParam("resourceId") Integer resourceId,
- @Context UriInfo uriInfo,
- @Context Request request,
- @Context HttpHeaders httpHeaders) {
-
-
+ @ApiParam("Id of the definition to retrieve") @PathParam("id") int definitionId,
+ @ApiParam("Id of a resource that supports this operation") @QueryParam("resourceId") Integer resourceId,
+ @Context UriInfo uriInfo,
+ @Context Request request) {
OperationDefinition def;
def = getFromCache(definitionId, OperationDefinition.class);
if (def==null) {
- def = opsManager.getOperationDefinition(caller,definitionId);
- if (def==null)
- throw new StuffNotFoundException("OperationDefinition with id " + definitionId);
- else
+ try {
+ def = opsManager.getOperationDefinition(caller,definitionId);
putToCache(definitionId,OperationDefinition.class,def);
+ }
+ catch (OperationDefinitionNotFoundException ode) {
+ throw new StuffNotFoundException("Operation definition with id " + definitionId);
+ }
}
EntityTag eTag = new EntityTag(Integer.toHexString(def.hashCode()));
@@ -145,43 +150,27 @@ public class OperationsHandlerBean extends AbstractRestBean {
}
- private void copyParamsForDefinition(OperationDefinition def, OperationDefinitionRest odr) {
- ConfigurationDefinition cd = def.getParametersConfigurationDefinition();
- if (cd==null)
- return;
-
- for (Map.Entry<String,PropertyDefinition> entry : cd.getPropertyDefinitions().entrySet()) {
- PropertyDefinition pd = entry.getValue();
- if (pd instanceof PropertyDefinitionSimple) {
- PropertyDefinitionSimple pds = (PropertyDefinitionSimple) pd;
- SimplePropDef prop = new SimplePropDef();
- prop.setName(pds.getName());
- prop.setRequired(pds.isRequired());
- prop.setType(pds.getType());
- prop.setDefaultValue(pds.getDefaultValue());
- odr.addParam(prop);
- }
- log.debug("copyParams: " + pd.getName() + " not yet supported");
- }
- }
-
@GZIP
@GET
@Path("definitions")
@Cache(maxAge = 1200)
@ApiOperation("List all operation definitions for a resource")
public Response getOperationDefinitions(
- @ApiParam(value = "Id of the resource",required = true) @QueryParam("resourceId") Integer resourceId,
- @Context UriInfo uriInfo,
- @Context Request request,
- @Context HttpHeaders httpHeaders) {
+ @ApiParam(value = "Id of the resource", required = true) @QueryParam("resourceId") Integer resourceId,
+ @Context UriInfo uriInfo,
+ @Context Request request) {
- if (resourceId == null)
+ if (resourceId == null) {
throw new ParameterMissingException("resourceId");
+ }
- Resource res =resourceManager.getResource(caller,resourceId);
- if(res==null)
+ Resource res;
+ try {
+ res = resourceManager.getResource(caller,resourceId);
+ }
+ catch (ResourceNotFoundException rnfe) {
throw new StuffNotFoundException("resource with id " + resourceId);
+ }
ResourceType resourceType = res.getResourceType();
@@ -226,16 +215,24 @@ public class OperationsHandlerBean extends AbstractRestBean {
@ApiParam(value = "Id of the resource", required = true) @QueryParam("resourceId") Integer resourceId,
@Context UriInfo uriInfo) {
- if (resourceId == null)
+ if (resourceId == null) {
throw new ParameterMissingException("resourceId");
+ }
- Resource res =resourceManager.getResource(caller,resourceId);
- if(res==null)
+ try {
+ // Check if the resource exists at all
+ resourceManager.getResource(caller,resourceId);
+ }
+ catch (ResourceNotFoundException rnfe) {
throw new StuffNotFoundException("resource with id " + resourceId);
+ }
- OperationDefinition opDef = opsManager.getOperationDefinition(caller,definitionId);
- if (opDef==null) {
+ OperationDefinition opDef;
+ try {
+ opDef = opsManager.getOperationDefinition(caller,definitionId);
+ }
+ catch (OperationDefinitionNotFoundException odnfe) {
throw new StuffNotFoundException("Operation definition with id " + definitionId);
}
OperationRest operationRest = new OperationRest(resourceId,definitionId);
@@ -266,9 +263,11 @@ public class OperationsHandlerBean extends AbstractRestBean {
@Path("{id}")
@ApiOperation("Return a (draft) operation")
public Response getOperation(@ApiParam("Id of the operation to retrieve") @PathParam("id") int operationId) {
+
OperationRest op = getFromCache(operationId,OperationRest.class);
- if (op==null)
+ if (op==null) {
throw new StuffNotFoundException("Operation with id " + operationId);
+ }
return Response.ok(op).build();
}
@@ -277,20 +276,40 @@ public class OperationsHandlerBean extends AbstractRestBean {
@Path("{id}")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@ApiOperation("Update a (draft) operation. If the state is set to 'ready', the operation will be scheduled")
+ @ApiErrors({
+ @ApiError(code = 404, reason = "No draft operation with the passed id exists"),
+ @ApiError(code = 406, reason = "Draft was set for scheduling, but parameters failed validation"),
+ @ApiError(code = 200, reason = "Update was successful, operation was scheduled if requested" )
+ }
+ )
public Response updateOperation(@ApiParam("Id of the operation to update") @PathParam("id") int operationId,
OperationRest operation, @Context UriInfo uriInfo) {
- if (!operation.isReadyToSubmit() && operation.getDefinitionId()>0 && !operation.getName().isEmpty()) {
- // TODO check all the required parameters for presence before allowing to submit
- operation.setReadyToSubmit(true);
+ OperationRest op = getFromCache(operationId,OperationRest.class);
+ if (op==null) {
+ throw new StuffNotFoundException("Operation with id " + operationId);
}
+
+ Configuration parameters = ConfigurationHelper.mapToConfiguration(operation.getParams());
+
if (operation.isReadyToSubmit()) {
- // todo check params
- // submit
+ OperationDefinition opDef = opsManager.getOperationDefinition(caller,operation.getDefinitionId());
- Configuration parameters = mapToConfiguration(operation.getParams());
+ // Validate parameters
+ ConfigurationDefinition parameterDefinition = opDef.getParametersConfigurationDefinition();
+ List<String> errorMessages = ConfigurationHelper.checkConfigurationWrtDefinition(parameters, parameterDefinition);
+ if (errorMessages.size()>0) {
+ // Configuration is not ok
+ operation.setReadyToSubmit(false);
+ throw new BadArgumentException("Validation of parameters failed", StringUtils.getListAsString(errorMessages,", "));
+ }
+ }
+
+ if (operation.isReadyToSubmit()) {
+
+ // submit
ResourceOperationSchedule sched = opsManager.scheduleResourceOperation(caller,operation.getResourceId(),operation.getName(),0,0,0,-1,
parameters,"Test");
JobId jobId = new JobId(sched.getJobName(),sched.getJobGroup());
@@ -304,12 +323,12 @@ public class OperationsHandlerBean extends AbstractRestBean {
else {
UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
uriBuilder.path("/operation/{id}");
- URI uri = uriBuilder.build(operation.getId());
+ URI uri = uriBuilder.build(operationId);
Link editLink = new Link("edit",uri.toString());
operation.addLink(editLink);
}
// Update item in cache
- putToCache(operation.getId(),OperationRest.class,operation);
+ putToCache(operationId,OperationRest.class,operation);
Response.ResponseBuilder builder = Response.ok(operation);
return builder.build();
}
@@ -381,8 +400,9 @@ public class OperationsHandlerBean extends AbstractRestBean {
@Context HttpHeaders httpHeaders) {
ResourceOperationHistoryCriteria criteria = new ResourceOperationHistoryCriteria();
- if (resourceId>0)
+ if (resourceId>0) {
criteria.addFilterResourceIds(resourceId);
+ }
criteria.addSortEndTime(PageOrdering.DESC);
@@ -424,30 +444,41 @@ public class OperationsHandlerBean extends AbstractRestBean {
}
-
+ /**
+ * Create a REST-object from the passed operation history
+ * @param history History object to convert
+ * @param uriInfo URI info of the incoming request, used to create links
+ * @return a populated OperationHistoryRest object
+ */
private OperationHistoryRest historyToHistoryRest(ResourceOperationHistory history, UriInfo uriInfo) {
String status;
- if (history.getStatus()==null)
+ if (history.getStatus()==null) {
status = " - no information yet -";
- else
+ }
+ else {
status = history.getStatus().getDisplayName();
+ }
OperationHistoryRest hist = new OperationHistoryRest();
hist.setStatus(status);
- if (history.getResource()!=null)
+ if (history.getResource()!=null) {
hist.setResourceName(history.getResource().getName());
+ }
hist.setOperationName(history.getOperationDefinition().getName());
hist.lastModified(history.getModifiedTime());
- if (history.getErrorMessage()!=null)
+ if (history.getErrorMessage()!=null) {
hist.setErrorMessage(history.getErrorMessage());
+ }
if (history.getResults()!=null) {
Configuration results = history.getResults();
for (Property p : results.getProperties()) {
String val;
- if (p instanceof PropertySimple)
+ if (p instanceof PropertySimple) {
val = ((PropertySimple)p).getStringValue();
- else
+ }
+ else {
val = p.toString();
+ }
hist.getResult().put(p.getName(),val);
}
}
@@ -465,4 +496,34 @@ public class OperationsHandlerBean extends AbstractRestBean {
return hist;
}
+ /**
+ * Copies the parameters of an OperationDefinition into to an object that can be
+ * returned to a REST-client, so that this knows which fields are to be filled in,
+ * of which type they are and which ones are required
+ * @param def OperationsDefinition to "copy"
+ * @param definitionRest The definition to fill in
+ */
+ private void copyParamsForDefinition(OperationDefinition def, OperationDefinitionRest definitionRest) {
+ ConfigurationDefinition cd = def.getParametersConfigurationDefinition();
+ if (cd==null) {
+ return;
+ }
+
+ for (Map.Entry<String,PropertyDefinition> entry : cd.getPropertyDefinitions().entrySet()) {
+ PropertyDefinition pd = entry.getValue();
+ if (pd instanceof PropertyDefinitionSimple) {
+ PropertyDefinitionSimple pds = (PropertyDefinitionSimple) pd;
+ SimplePropDef prop = new SimplePropDef();
+ prop.setName(pds.getName());
+ prop.setRequired(pds.isRequired());
+ prop.setType(pds.getType());
+ prop.setDefaultValue(pds.getDefaultValue());
+ definitionRest.addParam(prop);
+ }
+ log.debug("copyParams: " + pd.getName() + " not yet supported");
+ }
+ }
+
+
+
}
\ No newline at end of file
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ParameterMissingException.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ParameterMissingException.java
index 16fd62f..d3f3f50 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ParameterMissingException.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ParameterMissingException.java
@@ -1,9 +1,12 @@
package org.rhq.enterprise.server.rest;
+import javax.ejb.ApplicationException;
+
/**
* Exception thrown if (Query) Parameters are missing
* @author Heiko W. Rupp
*/
+@ApplicationException(rollback = false, inherited = true)
public class ParameterMissingException extends RuntimeException {
public ParameterMissingException(String what) {
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ReportsHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ReportsHandlerBean.java
index 1377be4..1b563da 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ReportsHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ReportsHandlerBean.java
@@ -76,25 +76,25 @@ import org.rhq.enterprise.server.rest.reporting.SuspectMetricLocal;
public class ReportsHandlerBean extends AbstractRestBean {
@EJB
- AlertDefinitionLocal alertDefinitionLocal;
+ private AlertDefinitionLocal alertDefinitionLocal;
@EJB
- ConfigurationHistoryLocal configurationHistoryLocal;
+ private ConfigurationHistoryLocal configurationHistoryLocal;
@EJB
- DriftComplianceLocal driftComplianceLocal;
+ private DriftComplianceLocal driftComplianceLocal;
@EJB
- InventorySummaryLocal inventorySummaryLocal;
+ private InventorySummaryLocal inventorySummaryLocal;
@EJB
- PlatformUtilizationLocal platformUtilizationLocal;
+ private PlatformUtilizationLocal platformUtilizationLocal;
@EJB
- RecentAlertLocal recentAlertLocal;
+ private RecentAlertLocal recentAlertLocal;
@EJB
- RecentDriftLocal recentDriftLocal;
+ private RecentDriftLocal recentDriftLocal;
@EJB
- RecentOperationsLocal recentOperationsLocal;
+ private RecentOperationsLocal recentOperationsLocal;
@EJB
- SuspectMetricLocal suspectMetricLocal;
+ private SuspectMetricLocal suspectMetricLocal;
- String[] reports = {
+ private String[] reports = {
"alertDefinitions",
"configurationHistory",
"driftCompliance",
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java
index 1c2b516..4e00625 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/ResourceHandlerBean.java
@@ -108,6 +108,7 @@ import org.rhq.enterprise.server.rest.domain.MetricSchedule;
import org.rhq.enterprise.server.rest.domain.ResourceWithChildren;
import org.rhq.enterprise.server.rest.domain.ResourceWithType;
import org.rhq.enterprise.server.rest.domain.StringValue;
+import org.rhq.enterprise.server.rest.helper.ConfigurationHelper;
/**
* Class that deals with getting data about resources
@@ -755,8 +756,8 @@ public class ResourceHandlerBean extends AbstractRestBean {
if (resType==null)
throw new StuffNotFoundException("ResourceType with name [" + typeName + "] and plugin [" + plugin + "]");
- Configuration pluginConfig = mapToConfiguration(request.getPluginConfig());
- Configuration deployConfig = mapToConfiguration(request.getResourceConfig());
+ Configuration pluginConfig = ConfigurationHelper.mapToConfiguration(request.getPluginConfig());
+ Configuration deployConfig = ConfigurationHelper.mapToConfiguration(request.getResourceConfig());
String packageName = DEFAULT_PACKAGE;
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RootHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RootHandlerBean.java
index 3aded78..612b3f7 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RootHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/RootHandlerBean.java
@@ -51,7 +51,7 @@ import org.rhq.enterprise.server.rest.domain.Link;
@Stateless
public class RootHandlerBean extends AbstractRestBean {
- String[] roots = { // rel, target
+ private String[] roots = { // rel, target
"platforms","resource/platforms",
"groups","group",
"dynaGroups","group/definitions",
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/SetCallerInterceptor.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/SetCallerInterceptor.java
index 3db8dc5..1da5411 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/SetCallerInterceptor.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/SetCallerInterceptor.java
@@ -52,10 +52,10 @@ import org.rhq.enterprise.server.auth.SubjectManagerLocal;
public class SetCallerInterceptor {
@Resource
- EJBContext ejbContext;
+ private EJBContext ejbContext;
@EJB
- SubjectManagerLocal subjectManager;
+ private SubjectManagerLocal subjectManager;
private SessionManager sessionManager = SessionManager.getInstance();
@@ -76,8 +76,9 @@ public class SetCallerInterceptor {
caller = subjectManager.getSubjectByName(p.getName());
}
- if (caller==null)
+ if (caller==null) {
throw new IllegalAccessException("No calling principal provided");
+ }
// Get Subject with a session
caller = sessionManager.put(caller);
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerBean.java
index 23bbd4b..a6c81b3 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/StatusHandlerBean.java
@@ -55,9 +55,9 @@ public class StatusHandlerBean extends AbstractRestBean {
@EJB
- SystemInfoManagerLocal infoMgr;
+ private SystemInfoManagerLocal infoMgr;
@EJB
- ServerManagerLocal serverManager;
+ private ServerManagerLocal serverManager;
@GZIP
@ApiOperation(value="Retrieve the current configured state of the server along with some runtime information." +
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerBean.java
index 9851425..cd57b67 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/UserHandlerBean.java
@@ -74,8 +74,6 @@ import org.rhq.enterprise.server.rest.domain.UserRest;
@Stateless
public class UserHandlerBean extends AbstractRestBean {
- // private final Log log = LogFactory.getLog(UserHandlerBean.class);
-
/**
* List of favorite {@link org.rhq.core.domain.resource.Resource} id's, delimited by '|' characters. Default is "".
*/
@@ -88,10 +86,10 @@ public class UserHandlerBean extends AbstractRestBean {
public static final String GROUP_HEALTH_GROUPS = ".dashContent.grouphealth.groups";
@EJB
- SubjectManagerLocal subjectManager;
+ private SubjectManagerLocal subjectManager;
@EJB
- ResourceManagerLocal resourceManager;
+ private ResourceManagerLocal resourceManager;
@GZIP
@GET
@@ -112,10 +110,12 @@ public class UserHandlerBean extends AbstractRestBean {
ResourceWithType rwt = fillRWT(res, uriInfo);
ret.add(rwt);
} catch (Exception e) {
- if (e instanceof ResourceNotFoundException)
+ if (e instanceof ResourceNotFoundException) {
log.debug("Favorite resource with id " + id + " not found - not returning to the user");
- else
+ }
+ else {
log.warn("Retrieving resource with id " + id + " failed: " + e.getLocalizedMessage());
+ }
}
}
Response.ResponseBuilder builder;
@@ -151,11 +151,12 @@ public class UserHandlerBean extends AbstractRestBean {
ResourceGroup res = resourceGroupManager.getResourceGroup(caller, id);
GroupRest rwt = fillGroup(res, uriInfo);
ret.add(rwt);
- } catch (Exception e) {
- if (e instanceof ResourceGroupNotFoundException)
- log.debug("Favorite group with id " + id + " not found - not returning to the user");
- else
- log.warn("Retrieving group with id " + id + " failed: " + e.getLocalizedMessage());
+ }
+ catch (ResourceGroupNotFoundException e) {
+ log.debug("Favorite group with id " + id + " not found - not returning to the user");
+ }
+ catch (Exception e) {
+ log.warn("Retrieving group with id " + id + " failed: " + e.getLocalizedMessage());
}
}
Response.ResponseBuilder builder;
@@ -222,8 +223,8 @@ public class UserHandlerBean extends AbstractRestBean {
@Path("favorites/group/{id}")
@ApiOperation(value = "Remove a group from favorites")
public void removeResourceGroupFromFavorites(@ApiParam(name = "id", value = "Id of the group")
- @PathParam("id")
- int id) {
+ @PathParam("id") int id) {
+
Set<Integer> favIds = getGroupIdsForFavorites();
if (favIds.contains(id)) {
favIds.remove(id);
@@ -242,8 +243,9 @@ public class UserHandlerBean extends AbstractRestBean {
HttpHeaders headers) {
Subject subject = subjectManager.getSubjectByName(loginName);
- if (subject == null)
+ if (subject == null) {
throw new StuffNotFoundException("User with login " + loginName);
+ }
EntityTag eTag = new EntityTag(Long.toOctalString(subject.hashCode()));
Response.ResponseBuilder builder = request.evaluatePreconditions(eTag);
@@ -273,7 +275,8 @@ public class UserHandlerBean extends AbstractRestBean {
PropertySimple prop = conf.getSimple(RESOURCE_HEALTH_RESOURCES);
if (prop == null) {
conf.put(new PropertySimple(RESOURCE_HEALTH_RESOURCES, builder.toString()));
- } else {
+ }
+ else {
prop.setStringValue(builder.toString());
}
caller.setUserConfiguration(conf);
@@ -290,7 +293,8 @@ public class UserHandlerBean extends AbstractRestBean {
PropertySimple prop = conf.getSimple(GROUP_HEALTH_GROUPS);
if (prop == null) {
conf.put(new PropertySimple(GROUP_HEALTH_GROUPS, builder.toString()));
- } else {
+ }
+ else {
prop.setStringValue(builder.toString());
}
caller.setUserConfiguration(conf);
@@ -308,13 +312,22 @@ public class UserHandlerBean extends AbstractRestBean {
private Set<Integer> getGroupIdsForFavorites() {
Configuration conf = caller.getUserConfiguration();
- if (conf==null)
+ if (conf==null) {
return new HashSet<Integer>();
+ }
String favsString = conf.getSimpleValue(GROUP_HEALTH_GROUPS, "");
Set<Integer> favIds = getIdsFromFavString(favsString);
return favIds;
}
+ /**
+ * Parse the String with favorites.
+ * The list of favorites is stored in the server as a list
+ * of ids separated by a pipe '|' character.
+ *
+ * @param favsString String as stored in for the user
+ * @return Set of ids of the favorites
+ */
private Set<Integer> getIdsFromFavString(String favsString) {
Set<Integer> favIds = new TreeSet<Integer>();
if (!favsString.isEmpty()) {
@@ -326,13 +339,21 @@ public class UserHandlerBean extends AbstractRestBean {
return favIds;
}
+ /**
+ * Create the String with favorites to store for the user
+ * The list of favorites is stored in the server as a list
+ * of ids separated by a pipe '|' character
+ * @param favIds Set of favorite ids
+ * @return String representation
+ */
private StringBuilder buildFavStringFromSet(Set<Integer> favIds) {
StringBuilder builder = new StringBuilder();
Iterator<Integer> iter = favIds.iterator();
while (iter.hasNext()) {
builder.append(iter.next());
- if (iter.hasNext())
+ if (iter.hasNext()) {
builder.append('|');
+ }
}
return builder;
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/domain/AlertDefinitionRest.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/domain/AlertDefinitionRest.java
index 2224732..f40d92c 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/domain/AlertDefinitionRest.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/domain/AlertDefinitionRest.java
@@ -43,8 +43,9 @@ public class AlertDefinitionRest {
List<AlertConditionRest> conditions = new ArrayList<AlertConditionRest>();
List<AlertNotificationRest> notifications = new ArrayList<AlertNotificationRest>();
String dampeningCategory;
- String dampeningCount;
- String dampeningPeriod;
+ int dampeningCount;
+ int dampeningPeriod;
+ String dampeningUnit;
List<Link> links = new ArrayList<Link>();
@SuppressWarnings("unused")
@@ -138,24 +139,33 @@ public class AlertDefinitionRest {
this.dampeningCategory = dampeningCategory;
}
- @ApiProperty(value = "Number of occurrences of an alert (in a given period)")
- public String getDampeningCount() {
+ @ApiProperty(value = "Number of occurrences of an alert (in a given period). Valid values are > -1")
+ public int getDampeningCount() {
return dampeningCount;
}
- public void setDampeningCount(String dampeningCount) {
+ public void setDampeningCount(int dampeningCount) {
this.dampeningCount = dampeningCount;
}
@ApiProperty( value = "Period to check events. Only applicable for PARTIAL_COUNT, DURATION_COUNT, INVERSE_COUNT")
- public String getDampeningPeriod() {
+ public int getDampeningPeriod() {
return dampeningPeriod;
}
- public void setDampeningPeriod(String dampeningPeriod) {
+ public void setDampeningPeriod(int dampeningPeriod) {
this.dampeningPeriod = dampeningPeriod;
}
+ @ApiProperty( value = "Unit of the dampening period.",allowableValues = "MINUTES, HOURS, DAYS, WEEKS" )
+ public String getDampeningUnit() {
+ return dampeningUnit;
+ }
+
+ public void setDampeningUnit(String dampeningUnit) {
+ this.dampeningUnit = dampeningUnit;
+ }
+
public List<Link> getLinks() {
return links;
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/helper/ConfigurationHelper.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/helper/ConfigurationHelper.java
new file mode 100644
index 0000000..073966d
--- /dev/null
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/helper/ConfigurationHelper.java
@@ -0,0 +1,432 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2013 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+
+package org.rhq.enterprise.server.rest.helper;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+import org.rhq.core.domain.configuration.definition.PropertySimpleType;
+
+/**
+ * Helper class to deal with configuration objects
+ * @author Heiko W. Rupp
+ */
+public class ConfigurationHelper {
+
+ /**
+ * Convert the passed map into a RHQ configuration object
+ * @param in Map with items to convert. Map.Entry.Key is the name of the property and Map.Entry.Value the value
+ * @return a new Configuration object
+ */
+ public static Configuration mapToConfiguration(Map<String, Object> in) {
+ Configuration config = new Configuration();
+ Set<String> mapKeys = in.keySet();
+ for (String mapKey : mapKeys) {
+ Object mapValue = in.get(mapKey);
+
+ if (mapValue instanceof Map) {
+ Map<String,Object> map = (Map<String, Object>) mapValue;
+ PropertyMap propertyMap = getPropertyMap(mapKey, map);
+ config.put(propertyMap);
+ }
+ else if (mapValue instanceof List) {
+ List<Object> objects = (List<Object>) mapValue;
+ PropertyList propertyList = getPropertyList(mapKey, objects);
+ config.put(propertyList);
+ }
+ else {
+ config.put(new PropertySimple(mapKey,mapValue));
+ }
+ }
+
+ return config;
+
+ }
+
+ public static Map<String,Object> configurationToMap(Configuration configuration, ConfigurationDefinition definition,
+ boolean strict) {
+
+ Map<String,Object> result = new HashMap<String, Object>();
+
+ if (configuration==null) {
+ return result;
+ }
+
+ if (configuration.getProperties().isEmpty()) {
+ return result;
+ }
+
+ for (Property property : configuration.getProperties()) {
+
+ String propertyName = property.getName();
+ PropertyDefinition propertyDefinition = definition.get(propertyName);
+ if (propertyDefinition==null) {
+ if (strict) {
+ throw new IllegalArgumentException("No definition for property " + propertyName + "found");
+ } else {
+ // no definition found and not strict, so skip the property
+ continue;
+ }
+ }
+
+ Object target = convertProperty(property, propertyDefinition, strict);
+ result.put(propertyName,target);
+ }
+
+ return result;
+ }
+
+ private static Object convertProperty(Property property, PropertyDefinition propertyDefinition, boolean strict) {
+ Object target;
+
+ if (property instanceof PropertyMap) {
+ PropertyMap propertyMap = (PropertyMap) property;
+ target = getInnerMap(propertyMap,(PropertyDefinitionMap) propertyDefinition, strict);
+ } else if (property instanceof PropertyList) {
+ PropertyList propertyList = (PropertyList) property;
+ target = getInnerList(propertyList, (PropertyDefinitionList)propertyDefinition, strict);
+ } else {
+ target= convertSimplePropertyValue((PropertySimple) property,
+ ((PropertyDefinitionSimple)propertyDefinition));
+ }
+ return target;
+ }
+
+ private static Map<String, Object> getInnerMap(PropertyMap propertyMap, PropertyDefinitionMap propertyDefinition,
+ boolean strict) {
+
+ Map<String, Property> map = propertyMap.getMap();
+ Map<String,Object> result = new HashMap<String, Object>(map.size());
+
+ Set<String> names = map.keySet();
+ for (String name : names ) {
+ Property property = map.get(name);
+ PropertyDefinition definition = propertyDefinition.get(name);
+
+ Object target = convertProperty(property,definition, strict);
+ result.put(name,target);
+ }
+
+ return result;
+ }
+
+ private static List<Object> getInnerList(PropertyList propertyList, PropertyDefinitionList definition,
+ boolean strict) {
+
+ List<Object> result = new ArrayList<Object>(propertyList.getList().size());
+
+ if (definition==null) {
+ if (strict) {
+ throw new IllegalArgumentException("No Definition exists for " + propertyList.getName());
+ } else {
+ return result;
+ }
+ }
+
+
+ PropertyDefinition memberDefinition = definition.getMemberDefinition();
+ for (Property property : propertyList.getList()) {
+ Object target = convertProperty(property,memberDefinition, strict);
+ result.add(target);
+ }
+
+ return result;
+ }
+
+ private static PropertyList getPropertyList(String propertyName, List<Object> objects) {
+ PropertyList propertyList = new PropertyList(propertyName);
+
+ Property target;
+ for (Object o : objects) {
+ if (o instanceof List) {
+ // Not sure if we actually support that at all inside RHQ
+ List list = (List) o;
+ target = getPropertyList(propertyName,list); // TODO propertyName?
+ } else if (o instanceof Map) {
+ Map map = (Map) o;
+ target = getPropertyMap(propertyName,map); // TODO propertyName?
+ } else {
+ target = new PropertySimple(propertyName,o);
+ }
+ propertyList.add(target);
+ }
+ return propertyList;
+ }
+
+ private static PropertyMap getPropertyMap(String propertyName, Map<String, Object> map) {
+ PropertyMap propertyMap = new PropertyMap(propertyName);
+ Set<String> keys = map.keySet();
+ for (String key : keys) {
+ Object value = map.get(key);
+ Property target;
+ if (value instanceof Map) {
+ target = getPropertyMap(key, (Map)value);
+ } else if (value instanceof List) {
+ target = getPropertyList(key, (List)value);
+ } else {
+ target = new PropertySimple(key,value);
+ }
+ propertyMap.put(target);
+ }
+ return propertyMap;
+ }
+
+ /**
+ * Convert the passed simple property into an object of a matching type. The
+ * type is determined with the help of the passed definition
+ * @param property Property to convert
+ * @param definition Definition of the Property
+ * @return Object with the correct type
+ */
+ public static Object convertSimplePropertyValue(PropertySimple property, PropertyDefinitionSimple definition) {
+
+ if (definition==null) {
+ throw new IllegalArgumentException("No definition provided");
+ }
+
+ if (property==null) {
+ return null;
+ }
+
+ PropertySimpleType type = definition.getType();
+ String val = property.getStringValue();
+
+ Object ret;
+
+ switch (type) {
+ case STRING:
+ ret= val;
+ break;
+ case INTEGER:
+ ret= Integer.valueOf(val);
+ break;
+ case BOOLEAN:
+ ret= Boolean.valueOf(val);
+ break;
+ case LONG:
+ ret= Long.valueOf(val);
+ break;
+ case FLOAT:
+ ret= Float.valueOf(val);
+ break;
+ case DOUBLE:
+ ret= Double.valueOf(val);
+ break;
+ default:
+ ret= val;
+ }
+ return ret;
+ }
+
+
+ /**
+ * Check that the passed configuration is valid wrt the passed definition
+ * @param configuration A Configuration to check
+ * @param definition A Definition to check the Configuration against
+ * @return List of validation failure messages. List is empty if no errors were found.
+ */
+ public static List<String> checkConfigurationWrtDefinition(Configuration configuration,
+ ConfigurationDefinition definition) {
+
+ List<String> messages = new ArrayList<String>();
+
+ if (configuration==null) {
+ messages.add("Configuration is null");
+
+ }
+
+ if (definition==null) {
+ messages.add("Definition is null");
+ }
+
+ if (configuration==null || definition==null) {
+ return messages;
+ }
+
+ // Basic validation is done, now have a look at the properties
+
+ for (PropertyDefinition propDef : definition.getPropertyDefinitions().values()) {
+ String name = propDef.getName();
+ Property property = configuration.get(name);
+
+ checkProperty(messages, propDef, property);
+ }
+
+
+ return messages;
+ }
+
+ /**
+ * Recursively check the passed property against the passed property definition
+ * @param messages Validation error messages are added here
+ * @param propertyDefinition The definition to check against
+ * @param property The property to check
+ */
+ private static void checkProperty(List<String> messages, PropertyDefinition propertyDefinition,
+ Property property) {
+
+ String name = propertyDefinition.getName();
+
+ // If a property is required and not present we can bail out early
+ if (propertyDefinition.isRequired() && property ==null) {
+ messages.add("Required property [" + name + "] not found");
+ return;
+ }
+
+ // If a property is not required and is null, it is fine either
+ if (!propertyDefinition.isRequired() && property==null) {
+ return;
+ }
+
+ // Check if the property and definition are of the same kind (simple, map, list)
+ boolean good = checkIfCompatible(propertyDefinition, property,messages);
+ // We only need to do this dance if the kinds are matching
+ if (good) {
+ if (property instanceof PropertySimple) {
+ checkDataTypeOfSimpleProperty((PropertyDefinitionSimple) propertyDefinition, (PropertySimple) property,
+ messages);
+ } else if (property instanceof PropertyList) {
+ PropertyList propertyList = (PropertyList) property;
+ PropertyDefinitionList propertyDefinitionList = (PropertyDefinitionList) propertyDefinition;
+ for (Property prop : propertyList.getList()) {
+ checkProperty(messages, propertyDefinitionList.getMemberDefinition(), prop);
+ }
+ } else if (property instanceof PropertyMap) {
+ PropertyMap propertyMap = (PropertyMap) property;
+ PropertyDefinitionMap propertyDefinitionMap = (PropertyDefinitionMap) propertyDefinition;
+ for (Map.Entry<String,Property> entry : propertyMap.getMap().entrySet()) {
+ Property prop = entry.getValue();
+ PropertyDefinition definition = propertyDefinitionMap.get(name);
+ checkProperty(messages,definition,prop);
+ }
+ }
+ }
+ }
+
+ /**
+ * Check that for a Property that is defined with one of the non-string data types, the
+ * stored value is actually valid according to this data type.
+ * This also checks if a property is required, but its value is actually null.
+ *
+ * @param propDef Definition of the property, that contains the data type
+ * @param property The property to check
+ * @param messages Validation issues are added to this list.
+ */
+ private static void checkDataTypeOfSimpleProperty(PropertyDefinitionSimple propDef, PropertySimple property,
+ List<String> messages) {
+
+ String prefix = "Property [" + property.getName() + "] is ";
+ String val = property.getStringValue();
+
+ // If a property is not required and its value is null, we can just return
+ if (!propDef.isRequired() && property.getStringValue()==null) {
+ return;
+ }
+
+ // If a property is required and its value is null, we can just return
+ if (propDef.isRequired() && property.getStringValue()==null) {
+ messages.add(prefix + "required but was 'null'");
+ return;
+ }
+
+
+ switch (propDef.getType()) {
+ case DOUBLE:
+ try {
+ Double.parseDouble(property.getStringValue());
+ } catch (NumberFormatException nfe ) {
+ messages.add(prefix + "no double : " + val);
+ }
+ break;
+ case FLOAT:
+ float f;
+ try {
+ f = Float.parseFloat(property.getStringValue());
+ } catch (NumberFormatException nfe ) {
+ messages.add(prefix + "no float : " + val);
+ break;
+ }
+ if (f < Float.MIN_VALUE || f > Float.MAX_VALUE) {
+ messages.add(prefix + "no valid float : " + val);
+ }
+ break;
+ case INTEGER:
+ try {
+ Integer.parseInt(property.getStringValue());
+ } catch (NumberFormatException nfe ) {
+ messages.add(prefix + "no integer : " + val);
+ }
+ break;
+ case LONG:
+ try {
+ Long.parseLong(property.getStringValue());
+ } catch (NumberFormatException nfe ) {
+ messages.add(prefix + "no long : " + val);
+ }
+ break;
+ case BOOLEAN:
+ String s = val.toLowerCase();
+ if (!(s.equals("true") || s.equals("false"))) {
+ messages.add(prefix + "no boolean : " + val);
+ }
+ break;
+ default:
+ // Strings and long strings and directories and files
+ }
+ }
+
+ /**
+ * Check if the Kind of Definition and Property match. I.e. if a PropertyMap corresponds to a PropertyDefinitionMap
+ * @param propDef PropertyDefinition to match
+ * @param property Property to match with the definition
+ * @param messages List of messages to add validation errors to.
+ * @return true if the kinds are matching
+ */
+ private static boolean checkIfCompatible(final PropertyDefinition propDef, final Property property,
+ final List<String> messages) {
+
+ boolean good = false ;
+ if (propDef instanceof PropertyDefinitionSimple && property instanceof PropertySimple) {
+ good = true;
+ } else if (propDef instanceof PropertyDefinitionMap && property instanceof PropertyMap) {
+ good = true;
+ } else if (propDef instanceof PropertyDefinitionList && property instanceof PropertyList) {
+ good = true;
+ }
+ if (!good) {
+ String name = propDef.getName();
+ messages.add("The type of property for [" + name + "] does not match the definition");
+ }
+ return good;
+ }
+}
diff --git a/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/ConfigurationHelperTest.java b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/ConfigurationHelperTest.java
new file mode 100644
index 0000000..7e20630
--- /dev/null
+++ b/modules/enterprise/server/jar/src/test/java/org/rhq/enterprise/server/configuration/ConfigurationHelperTest.java
@@ -0,0 +1,756 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2013 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+package org.rhq.enterprise.server.configuration;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.testng.annotations.Test;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionList;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
+import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
+import org.rhq.core.domain.configuration.definition.PropertySimpleType;
+import org.rhq.core.domain.util.StringUtils;
+import org.rhq.enterprise.server.rest.helper.ConfigurationHelper;
+
+/**
+ * Test the ConfigurationHelper class
+ * @author Heiko W. Rupp
+ */
+public class ConfigurationHelperTest {
+
+ @Test
+ public void testConvertSimpleMap() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+ map.put("Answer",42);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2;
+
+ PropertySimple hello = config.getSimple("Hello");
+ assert hello !=null;
+ assert hello.getStringValue().equals("World");
+
+ PropertySimple qu = config.getSimple("Answer");
+ assert qu!=null;
+ Integer value = qu.getIntegerValue();
+ assert value !=null;
+ assert value ==42;
+ }
+
+ @Test
+ public void testConvertWithNestedMap() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(3);
+ map.put("Hello","World");
+ map.put("Answer",42);
+ Map<String,Object> inner = new HashMap<String, Object>(1);
+ inner.put("Foo","Bar");
+ map.put("Inner",inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==3 : "Expected 3 props, got " + properties.size();
+
+ Property prop = config.get("Inner");
+ assert prop!=null;
+ assert prop instanceof PropertyMap : "Inner is no map";
+
+ PropertyMap pm = (PropertyMap) prop;
+ Map<String, Property> innerMap = pm.getMap();
+ assert innerMap.size()==1;
+
+ assert inner.containsKey("Foo");
+
+ }
+
+ @Test
+ public void testConvertListOfMap() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+ List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
+ map.put("list",list);
+
+ Map<String,Object> inner = new HashMap<String, Object>(1);
+ inner.put("Foo","Bar");
+ list.add(inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2 : "Expected 2 props, got " + properties.size();
+
+ Property prop = config.get("Inner");
+ assert prop==null;
+
+ prop = config.get("list");
+ assert prop instanceof PropertyList : "list is no list";
+
+ PropertyList pl = (PropertyList) prop;
+ List<Property> propertyList = pl.getList();
+ assert propertyList.size()==1;
+ PropertyMap innerMapProperty = (PropertyMap) propertyList.get(0);
+
+ Map<String, Property> propertyMap = innerMapProperty.getMap();
+ assert propertyMap.size()==1;
+ Map<String,Property> innerMap = propertyMap;
+
+ assert innerMap.containsKey("Foo");
+ Property property = innerMapProperty.get("Foo");
+ assert property != null;
+ assert property instanceof PropertySimple;
+ PropertySimple ps = (PropertySimple) property;
+ assert ps.getStringValue().equals("Bar");
+
+ }
+
+ @Test
+ public void testConvertWithListOfSimple() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+ map.put("Answer",42);
+ List<String> inner = new ArrayList<String>(2);
+ inner.add("Foo");
+ inner.add("Bar");
+ map.put("Inner", inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==3 : "Expected 3 props, got " + properties.size();
+
+ Property prop = config.get("Inner");
+ assert prop!=null;
+ assert prop instanceof PropertyList : "Inner is no list";
+
+ PropertyList plist = (PropertyList) prop;
+ List<Property> propertyList = plist.getList();
+ assert propertyList.size()==2;
+ for (Property innerProp : propertyList) {
+ assert innerProp instanceof PropertySimple;
+ PropertySimple ps = (PropertySimple) innerProp;
+ assert ps.getName().equals("Inner");
+ assert ps.getStringValue().equals("Foo") || ps.getStringValue().equals("Bar");
+ }
+
+ }
+
+ @Test
+ public void testConvertAndValidateBoolean() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>();
+ map.put("bool1","true");
+ map.put("bool2","TruE");
+ map.put("bool3","fAlSe");
+ map.put("bool4", "false");
+ map.put("bool5", 42);
+ map.put("bool6", "Hugo");
+ map.put("bool7",null);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==7 : "Expected 7 props but got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla","For testing");
+ definition.put(new PropertyDefinitionSimple("bool1","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool2","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool3","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool4","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool5","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool6","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool7","A boolean",true, PropertySimpleType.BOOLEAN));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==3 : "Expected 3 errors, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n ");
+
+ }
+
+ @Test
+ public void testConvertAndValidateMissingRequired() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(1);
+ map.put("bool1","true");
+ // required 2nd entry is missing
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==1 : "Expected 1 props but got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla","For testing");
+ definition.put(new PropertyDefinitionSimple("bool1","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("bool2","A boolean",true, PropertySimpleType.BOOLEAN));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==1 : "Expected 1 error, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n ");
+
+ }
+
+ @Test
+ public void testConvertAndValidateNotRequiredButNull() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(1);
+ map.put("bool1","true");
+ map.put("optional",null);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2 : "Expected 2 props but got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla","For testing");
+ definition.put(new PropertyDefinitionSimple("bool1","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("optional","null string",false, PropertySimpleType.STRING));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==0 : "Expected 0 error, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n ");
+
+ }
+
+ @Test
+ public void testConvertAndValidateMismatchingKind() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(1);
+ map.put("bool1","true");
+ map.put("optional",null);
+ Map<String,Object> inner = new HashMap<String, Object>(1);
+ inner.put("Foo","Bar");
+ map.put("Inner",inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==3 : "Expected 3 props but got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla","For testing");
+ definition.put(new PropertyDefinitionSimple("bool1","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("optional","null string",false, PropertySimpleType.STRING));
+ // We define Inner as a simple property, but the user supplied a map
+ definition.put(new PropertyDefinitionSimple("Inner","null string",false, PropertySimpleType.STRING));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==1 : "Expected 1 error, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n ");
+
+ }
+
+ @Test
+ public void testConvertAndValidateMismatchingKind2() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(1);
+ map.put("bool1","true");
+ map.put("optional",null);
+ map.put("Inner","Frobnitz");
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==3 : "Expected 3 props but got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla","For testing");
+ definition.put(new PropertyDefinitionSimple("bool1","A boolean",true, PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("optional","null string",false, PropertySimpleType.STRING));
+ // We define Inner as a list property, but the user supplied a simple one
+ definition.put(new PropertyDefinitionList("Inner","Bla",true,
+ new PropertyDefinitionSimple("Inner","fasel",true,PropertySimpleType.STRING)));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==1 : "Expected 1 error, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n ");
+
+ }
+
+ @Test
+ public void testConvertAndValidateNumeric() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("float1",1.1f);
+ map.put("float2",Double.MAX_VALUE);
+ map.put("float3",null);
+ map.put("float4","abc");
+
+ map.put("double1",1.1d);
+ map.put("double2",null);
+ map.put("double3","hugo");
+
+ map.put("int1",42);
+ map.put("int2",Long.MAX_VALUE);
+ map.put("int3",null);
+ map.put("int4","abc");
+
+ map.put("long1",-5);
+ map.put("long2",null);
+ map.put("long3","Frobnitz");
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==14 : "Expected 14 props but got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla","For testing");
+ definition.put(new PropertyDefinitionSimple("float1","A float",true, PropertySimpleType.FLOAT));
+ definition.put(new PropertyDefinitionSimple("float2","A float",true, PropertySimpleType.FLOAT));
+ definition.put(new PropertyDefinitionSimple("float3","A float",true, PropertySimpleType.FLOAT));
+ definition.put(new PropertyDefinitionSimple("float4","A float",true, PropertySimpleType.FLOAT));
+
+ definition.put(new PropertyDefinitionSimple("double1","A double",true, PropertySimpleType.DOUBLE));
+ definition.put(new PropertyDefinitionSimple("double2","A double",true, PropertySimpleType.DOUBLE));
+ definition.put(new PropertyDefinitionSimple("double3","A double",true, PropertySimpleType.DOUBLE));
+
+ definition.put(new PropertyDefinitionSimple("int1","An int",true, PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("int2","An int",true, PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("int3","An int",true, PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("int4","An int",true, PropertySimpleType.INTEGER));
+
+ definition.put(new PropertyDefinitionSimple("long1","A long",true, PropertySimpleType.LONG));
+ definition.put(new PropertyDefinitionSimple("long2","A long",true, PropertySimpleType.LONG));
+ definition.put(new PropertyDefinitionSimple("long3","A long",true, PropertySimpleType.LONG));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==10 : "Expected 10 errors, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n");
+
+ }
+
+ @Test
+ public void testValidateNullConfiguration() throws Exception {
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(null,new ConfigurationDefinition("bla",null));
+ assert errors != null;
+ assert errors.size()==1;
+
+ }
+
+ @Test
+ public void testValidateNullDefinition() throws Exception {
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(new Configuration(),null);
+ assert errors != null;
+ assert errors.size()==1;
+
+ }
+
+ @Test
+ public void testConvertAndValidateSimpleMap() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+ map.put("Answer",42);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("Hello",null,true,PropertySimpleType.STRING));
+ definition.put(new PropertyDefinitionSimple("Answer",null,true,PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("Optional",null,false,PropertySimpleType.INTEGER));
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2;
+
+ PropertySimple hello = config.getSimple("Hello");
+ assert hello !=null;
+ assert hello.getStringValue().equals("World");
+
+ PropertySimple qu = config.getSimple("Answer");
+ assert qu!=null;
+ Integer integerValue = qu.getIntegerValue();
+ assert integerValue !=null;
+ assert integerValue ==42;
+ }
+
+ @Test
+ public void testConvertValidateNonRequiredNotPresent() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==0 : "Expected 0 props, got " + properties.size();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("Answer",null,false,PropertySimpleType.INTEGER));
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==0 : "Expected 0 errors, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n");
+
+ }
+
+ @Test
+ public void testConvertAndValidateListOfMap() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+ List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
+ map.put("list",list);
+
+ Map<String,Object> inner = new HashMap<String, Object>(1);
+ inner.put("Foo","Bar");
+ list.add(inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2 : "Expected 2 props, got " + properties.size();
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("Hello",null,true,PropertySimpleType.STRING));
+ definition.put(new PropertyDefinitionSimple("Answer",null,false,PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionList("list",null,true,
+ new PropertyDefinitionMap("list",null,true,
+ new PropertyDefinitionSimple("list",null,true,PropertySimpleType.STRING))));
+ definition.put(new PropertyDefinitionSimple("aString",null,false,PropertySimpleType.INTEGER));
+
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==0 : "Expected 0 errors, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n");
+
+ }
+
+ @Test
+ public void testConvertAndValidateMapOfMap() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+ Map<String,Map<String,Object>> list = new HashMap<String, Map<String, Object>>();
+ map.put("list",list);
+
+ Map<String,Object> inner = new HashMap<String, Object>(1);
+ inner.put("Foo","Bar");
+ list.put("outer", inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2 : "Expected 2 props, got " + properties.size();
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("Hello",null,true,PropertySimpleType.STRING));
+ definition.put(new PropertyDefinitionMap("list",null,true,
+ new PropertyDefinitionMap("list",null,true,
+ new PropertyDefinitionSimple("list",null,true,PropertySimpleType.STRING))));
+
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==0 : "Expected 0 errors, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n");
+
+ }
+
+ @Test
+ public void testConvertAndValidateMapWithListOfSimple() throws Exception {
+
+ Map<String,Object> map = new HashMap<String, Object>(2);
+ map.put("Hello","World");
+
+ Map<String,List<String>> list = new HashMap<String, List<String>>();
+ map.put("list",list);
+
+ List<String> inner = new ArrayList<String>();
+ inner.add("Foo");
+ inner.add("Bar");
+ list.put("outer", inner);
+
+ Configuration config = ConfigurationHelper.mapToConfiguration(map);
+
+ assert config!=null;
+ Collection<Property> properties = config.getProperties();
+ assert properties.size()==2 : "Expected 2 props, got " + properties.size();
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("Hello",null,true,PropertySimpleType.STRING));
+ definition.put(new PropertyDefinitionMap("list",null,true,
+ new PropertyDefinitionList("list",null,true,
+ new PropertyDefinitionSimple("list",null,true,PropertySimpleType.STRING))));
+
+
+ List<String> errors = ConfigurationHelper.checkConfigurationWrtDefinition(config,definition);
+
+ assert errors!=null;
+ assert errors.size()==0 : "Expected 0 errors, but got " + errors.size() + "\n" + StringUtils.getListAsString(errors,",\n");
+
+ }
+
+ @Test
+ public void testConfigToMapSimple() throws Exception {
+
+ Configuration config = new Configuration();
+ config.put(new PropertySimple("number",42));
+ config.put(new PropertySimple("string","Hello"));
+ config.put(new PropertySimple("bool",true));
+ config.put(new PropertySimple("float",1.1f));
+ config.put(new PropertySimple("double",2.3d));
+ config.put(new PropertySimple("long",Long.MAX_VALUE));
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("number",null,false,PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING));
+ definition.put(new PropertyDefinitionSimple("bool",null,false,PropertySimpleType.BOOLEAN));
+ definition.put(new PropertyDefinitionSimple("float",null,false,PropertySimpleType.FLOAT));
+ definition.put(new PropertyDefinitionSimple("double",null,false,PropertySimpleType.DOUBLE));
+ definition.put(new PropertyDefinitionSimple("long",null,false,PropertySimpleType.LONG));
+
+ Map<String,Object> map = ConfigurationHelper.configurationToMap(config,definition, true);
+
+ assert map != null;
+ assert map.entrySet().size()==6;
+
+ assert map.containsKey("number");
+ assert map.containsKey("string");
+
+ assert map.get("number") != null;
+ assert (Integer)map.get("number") == 42;
+
+ assert map.get("string") != null;
+ assert map.get("string").equals("Hello");
+
+ assert (Boolean)map.get("bool") == true;
+
+ assert map.get("float") != null;
+ assert (Float)map.get("float") ==1.1f;
+
+ assert map.get("double") != null;
+ assert (Double) map.get("double") ==2.3d;
+
+ assert map.get("long") != null;
+ assert (Long)map.get("long") == Long.MAX_VALUE;
+
+ }
+
+ @Test
+ public void testEmptyConfigToMap() throws Exception {
+
+ Configuration config = new Configuration();
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("number",null,false,PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING));
+
+ Map<String,Object> map = ConfigurationHelper.configurationToMap(config,definition, true);
+
+ assert map != null;
+ assert map.entrySet().size()==0;
+
+
+ }
+
+ @Test
+ public void testNullConfigToMap() throws Exception {
+
+ Configuration config = null;
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionSimple("number",null,false,PropertySimpleType.INTEGER));
+ definition.put(new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING));
+
+ Map<String,Object> map = ConfigurationHelper.configurationToMap(config,definition, true);
+
+ assert map != null;
+ assert map.entrySet().size()==0;
+
+ }
+
+ @Test
+ public void testConfigToMapComplexList() throws Exception {
+
+ Configuration config = new Configuration();
+ PropertyList propertyList = new PropertyList("aList");
+ propertyList.add(new PropertySimple("string", "Hello"));
+ propertyList.add(new PropertySimple("string", "World"));
+ config.put(propertyList);
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionList("aList",null,false,
+ new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING)));
+
+ Map<String,Object> map = ConfigurationHelper.configurationToMap(config,definition, true);
+
+ assert map != null;
+ assert map.entrySet().size()==1;
+
+ assert map.containsKey("aList");
+
+ }
+
+ @Test
+ public void testConfigToMapComplexMap() throws Exception {
+
+ Configuration config = new Configuration();
+ PropertyMap propertyMap = new PropertyMap("aMap");
+ config.put(propertyMap);
+ PropertyList propertyList = new PropertyList("aList");
+ propertyList.add(new PropertySimple("string", "Hello"));
+ propertyList.add(new PropertySimple("string", "World"));
+ propertyMap.put(propertyList);
+
+ propertyMap.put(new PropertySimple("aString","Frobnitz"));
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionMap("aMap",null,false,
+ new PropertyDefinitionList("aList",null,false,
+ new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING)),
+ new PropertyDefinitionSimple("aString",null,false,PropertySimpleType.STRING)));
+
+ Map<String,Object> map = ConfigurationHelper.configurationToMap(config,definition, true);
+
+ assert map != null;
+ assert map.entrySet().size()==1;
+
+ assert map.containsKey("aMap");
+ assert map.get("aMap") instanceof Map;
+ Map<String,Object> innerMap = (Map<String, Object>) map.get("aMap");
+
+ assert innerMap.containsKey("aString");
+ assert innerMap.containsKey("aList");
+
+ }
+
+ @Test
+ public void testConfigToMapComplexMapWithBadSetupStrict() throws Exception {
+
+ Configuration config = new Configuration();
+ PropertyMap propertyMap = new PropertyMap("aMap");
+ config.put(propertyMap);
+ PropertyList propertyList = new PropertyList("aList");
+ propertyList.add(new PropertySimple("string", "Hello"));
+ propertyList.add(new PropertySimple("string", "World"));
+ propertyMap.put(propertyList);
+
+ propertyMap.put(new PropertySimple("aString","Frobnitz"));
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionMap("aMap",null,false,
+ new PropertyDefinitionList("aBla",null,false,
+ new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING)),
+ new PropertyDefinitionSimple("aFoo",null,false,PropertySimpleType.STRING)));
+
+ try {
+ ConfigurationHelper.configurationToMap(config,definition, true);
+ assert false;
+ } catch (IllegalArgumentException iae ) {
+ System.out.println("Yep, caught the error");
+ }
+
+
+ }
+
+ @Test
+ public void testConfigToMapComplexMapWithBadSetupLenient() throws Exception {
+
+ Configuration config = new Configuration();
+ PropertyMap propertyMap = new PropertyMap("aMap");
+ config.put(propertyMap);
+ PropertyList propertyList = new PropertyList("aList");
+ propertyList.add(new PropertySimple("string", "Hello"));
+ propertyList.add(new PropertySimple("string", "World"));
+ propertyMap.put(propertyList);
+
+ propertyMap.put(new PropertySimple("aString","Frobnitz"));
+
+
+ ConfigurationDefinition definition = new ConfigurationDefinition("bla",null);
+ definition.put(new PropertyDefinitionMap("aMap",null,false,
+ new PropertyDefinitionList("aBla",null,false,
+ new PropertyDefinitionSimple("string",null,false,PropertySimpleType.STRING)),
+ new PropertyDefinitionSimple("aFoo",null,false,PropertySimpleType.STRING)));
+
+ Map<String,Object> map = ConfigurationHelper.configurationToMap(config,definition, false);
+
+ assert map != null;
+ assert map.entrySet().size()==1;
+
+ assert map.containsKey("aMap");
+
+ }
+
+ @Test
+ public void testConvertSingleValueNoProperty() throws Exception {
+
+ Object o = ConfigurationHelper.convertSimplePropertyValue(null,new PropertyDefinitionSimple("dummy",null,false,PropertySimpleType.STRING));
+
+ assert o == null;
+
+ }
+
+ @Test
+ public void testConvertSingleValueNoDefinition() throws Exception {
+
+ try {
+ ConfigurationHelper.convertSimplePropertyValue(new PropertySimple("foo","bar"),null);
+ assert false;
+ }
+ catch (IllegalArgumentException iae) {
+ System.out.println("Yep, good");
+ }
+
+ }
+}
diff --git a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/AlertTest.java b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/AlertTest.java
index 3d9f735..fca0f50 100644
--- a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/AlertTest.java
+++ b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/AlertTest.java
@@ -266,8 +266,8 @@ public class AlertTest extends AbstractBase {
.expect()
.statusCode(201)
.body("dampeningCategory",is("NONE"))
- .body("dampeningCount",is("0"))
- .body("dampeningPeriod",is("0"))
+ .body("dampeningCount",is(0))
+ .body("dampeningPeriod",is(0))
.when()
.post("/alert/definitions")
.as(AlertDefinition.class);
@@ -369,8 +369,8 @@ public class AlertTest extends AbstractBase {
alertDefinition.setEnabled(false);
alertDefinition.setPriority("LOW");
alertDefinition.setDampeningCategory("PARTIAL_COUNT");
- alertDefinition.setDampeningCount("3");
- alertDefinition.setDampeningPeriod("5");
+ alertDefinition.setDampeningCount(3);
+ alertDefinition.setDampeningPeriod(5);
AlertDefinition result =
given()
@@ -381,8 +381,8 @@ public class AlertTest extends AbstractBase {
.expect()
.statusCode(201)
.body("dampeningCategory",is("PARTIAL_COUNT"))
- .body("dampeningCount",is("3"))
- .body("dampeningPeriod",is("5"))
+ .body("dampeningCount",is(3))
+ .body("dampeningPeriod",is(5))
.when()
.post("/alert/definitions")
.as(AlertDefinition.class);
@@ -404,8 +404,9 @@ public class AlertTest extends AbstractBase {
alertDefinition.setEnabled(false);
alertDefinition.setPriority("LOW");
alertDefinition.setDampeningCategory("DURATION_COUNT");
- alertDefinition.setDampeningCount("1");
- alertDefinition.setDampeningPeriod("3 minutes");
+ alertDefinition.setDampeningCount(1);
+ alertDefinition.setDampeningPeriod(3);
+ alertDefinition.setDampeningUnit("minutes");
AlertDefinition result =
given()
@@ -416,8 +417,9 @@ public class AlertTest extends AbstractBase {
.expect()
.statusCode(201)
.body("dampeningCategory",is("DURATION_COUNT"))
- .body("dampeningCount", is("1"))
- .body("dampeningPeriod", is("3 MINUTES"))
+ .body("dampeningCount", is(1))
+ .body("dampeningPeriod", is(3))
+ .body("dampeningUnit", is("MINUTES"))
.when()
.post("/alert/definitions")
.as(AlertDefinition.class);
diff --git a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/OperationsTest.java b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/OperationsTest.java
index 713a755..e6aea1f 100644
--- a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/OperationsTest.java
+++ b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/OperationsTest.java
@@ -61,8 +61,9 @@ public class OperationsTest extends AbstractBase {
definitionId = -1;
List<Map<String,Object>> list = r.as(List.class);
for (Map<String,Object> map : list) {
- if (map.get("name").equals("discovery"))
+ if (map.get("name").equals("discovery")) {
definitionId = (Integer) map.get("id");
+ }
}
assert definitionId !=-1 : "No discovery operation found";
@@ -85,6 +86,92 @@ public class OperationsTest extends AbstractBase {
}
@Test
+ public void testGetDefinitionByUnknownId() throws Exception {
+
+ // Now retrieve that definition by id
+
+ given()
+ .header(acceptJson)
+ .pathParam("did",-42)
+ .expect()
+ .statusCode(404)
+ .when()
+ .get("/operation/definition/{did}");
+
+ }
+
+ @Test
+ public void testGetDefinitionsForUnknownResource() throws Exception {
+
+ // Now retrieve that definition by id
+
+ given()
+ .header(acceptJson)
+ .queryParam("resourceId",42)
+ .expect()
+ .statusCode(404)
+ .when()
+ .get("/operation/definitions");
+ }
+
+ @Test
+ public void testGetDefinitionsForMissingResourceId() throws Exception {
+
+ // Now retrieve that definition by id
+
+ given()
+ .header(acceptJson)
+ .expect()
+ .statusCode(406)
+ .when()
+ .get("/operation/definitions");
+ }
+
+ @Test
+ public void testCreateScheduleByUnknownDefinitionId() throws Exception {
+
+ // Now retrieve that definition by id
+
+ given()
+ .header(acceptJson)
+ .pathParam("did",-42)
+ .expect()
+ .statusCode(406)
+ .when()
+ .post("/operation/definition/{did}");
+
+ }
+
+ @Test
+ public void testCreateScheduleForUnknownResource() throws Exception {
+
+ // Now retrieve that definition by id
+
+ given()
+ .header(acceptJson)
+ .queryParam("resourceId", 42)
+ .pathParam("definitionId", definitionId)
+ .expect()
+ .statusCode(404)
+ .when()
+ .post("/operation/definition/{definitionId}");
+ }
+
+ @Test
+ public void testCreateScheduleForMissingResourceId() throws Exception {
+
+ // Now retrieve that definition by id
+
+ given()
+ .header(acceptJson)
+ .pathParam("definitionId", definitionId)
+ .expect()
+ .statusCode(406)
+ .when()
+ .post("/operation/definition/{definitionId}");
+ }
+
+ @Test
public void testCreateDraftOperation() throws Exception {
Operation draft =
@@ -196,8 +283,9 @@ public class OperationsTest extends AbstractBase {
String history = null;
List<Link> links = scheduled.getLinks();
for (Link link : links) {
- if (link.getRel().equals("history"))
- history = (String) link.getHref();
+ if (link.getRel().equals("history")) {
+ history = link.getHref();
+ }
}
assert history != null;
@@ -272,4 +360,98 @@ public class OperationsTest extends AbstractBase {
}
}
+ @Test
+ public void testOpsScheduleMissingRequiredParam() throws Exception {
+
+ int platformId = findIdOfARealPlatform();
+
+ Operation draft =
+ given()
+ .header(acceptJson)
+ .pathParam("definitionId",definitionId)
+ .queryParam("resourceId",platformId)
+ .expect()
+ .statusCode(200)
+ .log().ifError()
+ .when()
+ .post("/operation/definition/{definitionId}")
+ .as(Operation.class);
+
+ assert draft != null;
+ assert draft.getDefinitionId() == definitionId;
+
+ int draftId = draft.getId();
+
+ // explicitly remove the param from the draft for
+ // the test
+ Map<String, Object> params = draft.getParams();
+ if (params.containsKey("detailedDiscovery")) {
+ params.remove("detailedDiscovery");
+ }
+
+ // Update to put the new version in the server
+ // We don't want to submit, so the server does not
+ // validate and we should get a 200 back
+ draft.setReadyToSubmit(false);
+ given()
+ .contentType(ContentType.JSON)
+ .pathParam("id",draftId)
+ .body(draft)
+ .expect()
+ .statusCode(200)
+ .log().ifError()
+ .when()
+ .put("/operation/{id}");
+
+
+ // update to schedule, lacking the required param
+ draft.setReadyToSubmit(true);
+
+ given()
+ .contentType(ContentType.JSON)
+ .pathParam("id",draftId)
+ .body(draft)
+ .expect()
+ .statusCode(406)
+ .log().ifError()
+ .when()
+ .put("/operation/{id}");
+ }
+
+ @Test
+ public void testOpsScheduleRequiredParamWrongDataType() throws Exception {
+
+ int platformId = findIdOfARealPlatform();
+
+ Operation draft =
+ given()
+ .header(acceptJson)
+ .pathParam("definitionId",definitionId)
+ .queryParam("resourceId",platformId)
+ .expect()
+ .statusCode(200)
+ .log().ifError()
+ .when()
+ .post("/operation/definition/{definitionId}")
+ .as(Operation.class);
+
+ assert draft != null;
+ assert draft.getDefinitionId() == definitionId;
+
+ int draftId = draft.getId();
+
+ draft.getParams().put("detailedDiscovery", 42);
+ draft.setReadyToSubmit(true);
+
+ // update to schedule
+ given()
+ .contentType(ContentType.JSON)
+ .pathParam("id",draftId)
+ .body(draft)
+ .expect()
+ .statusCode(406)
+ .log().ifError()
+ .when()
+ .put("/operation/{id}");
+ }
}
diff --git a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/RootURITest.java b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/RootURITest.java
index 5922770..d6da534 100644
--- a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/RootURITest.java
+++ b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/RootURITest.java
@@ -50,7 +50,7 @@ public class RootURITest extends AbstractBase {
.expect().statusCode(200)
.when().get("/");
- given().header("Accept","application/json")
+ given().header("Accept","application/xml")
.expect().statusCode(200)
.when().get("/index");
diff --git a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/d/AlertDefinition.java b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/d/AlertDefinition.java
index 5049a98..b870443 100644
--- a/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/d/AlertDefinition.java
+++ b/modules/integration-tests/rest-api/src/test/java/org/rhq/modules/integrationTests/restApi/d/AlertDefinition.java
@@ -41,8 +41,9 @@ public class AlertDefinition {
List<AlertCondition> conditions = new ArrayList<AlertCondition>();
List<AlertNotification> notifications = new ArrayList<AlertNotification>();
String dampeningCategory = "NONE";
- String dampeningCount;
- String dampeningPeriod;
+ int dampeningCount;
+ int dampeningPeriod;
+ String dampeningUnit;
List<Link> links;
@@ -121,22 +122,30 @@ public class AlertDefinition {
this.dampeningCategory = dampeningCategory;
}
- public String getDampeningCount() {
+ public int getDampeningCount() {
return dampeningCount;
}
- public void setDampeningCount(String dampeningCount) {
+ public void setDampeningCount(int dampeningCount) {
this.dampeningCount = dampeningCount;
}
- public String getDampeningPeriod() {
+ public int getDampeningPeriod() {
return dampeningPeriod;
}
- public void setDampeningPeriod(String dampeningPeriod) {
+ public void setDampeningPeriod(int dampeningPeriod) {
this.dampeningPeriod = dampeningPeriod;
}
+ public String getDampeningUnit() {
+ return dampeningUnit;
+ }
+
+ public void setDampeningUnit(String dampeningUnit) {
+ this.dampeningUnit = dampeningUnit;
+ }
+
public List<Link> getLinks() {
return links;
}
commit d72ac1e6bba8cbeb054a7cbfc8d7df026a09a5fc
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 8 09:17:22 2013 +0200
Add another email for Thomas
diff --git a/.mailmap b/.mailmap
index 384ec04..ac0fdc9 100644
--- a/.mailmap
+++ b/.mailmap
@@ -75,5 +75,6 @@ Test JON User <test_jon(a)jon01.qa.atl2.redhat.com>
Todd B Sanders <tsanders(a)dhcp231-67.rdu.redhat.com>
Torben Jäger <torben(a)jit-central.com>
Thomas Segismont <tsegismo(a)redhat.com> Thomas SEGISMONT <tsegismo(a)redhat.com>
+Thomas Segismont <tsegismo(a)redhat.com> Thomas Segismont <tsegismont(a)gmail.com>
Thomas Segismont <tsegismo(a)redhat.com>
hudson auto <wnstb(a)yahoo.com>
11 years, 1 month
[rhq] modules/enterprise
by mike thompson
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java | 210 ++++------
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java | 2
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/MetricD3GraphView.java | 34 +
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java | 18
4 files changed, 145 insertions(+), 119 deletions(-)
New commits:
commit bbe5654f0755eac835b78351a8ef71a7e3398037
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Tue May 7 16:58:43 2013 -0700
[BZ 960646] - RFE Redesigned Availability Chart - Add disabled state cross hatch SVG pattern. Pixel tweeks.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java
index 76c8f69..4e6a0ce 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java
@@ -18,6 +18,9 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.common.charttype;
+import java.util.Date;
+import java.util.List;
+
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.measurement.MeasurementUnits;
import org.rhq.core.domain.resource.group.composite.ResourceGroupAvailability;
@@ -27,9 +30,6 @@ import org.rhq.enterprise.gui.coregui.client.Messages;
import org.rhq.enterprise.gui.coregui.client.util.Log;
import org.rhq.enterprise.gui.coregui.client.util.MeasurementConverterClient;
-import java.util.Date;
-import java.util.List;
-
/**
* Contains the javascript chart definition for an implementation of the d3 availability chart. This implementation is
* just a line that changes color based on availability type: up=green, down=red, orange=disabled, unknown=grey,
@@ -66,7 +66,7 @@ public class AvailabilityOverUnderGraphType {
// loop through the avail intervals
for (Availability availability : availabilityList) {
sb.append("{ \"availType\":\"" + availability.getAvailabilityType() + "\", ");
- sb.append(" \"availTypeMessage\":\"" + availability.getAvailabilityType()+ "\", ");
+ sb.append(" \"availTypeMessage\":\"" + availability.getAvailabilityType() + "\", ");
sb.append(" \"availStart\":" + availability.getStartTime() + ", ");
// last record will be null
long endTime = availability.getEndTime() != null ? availability.getEndTime() : (new Date()).getTime();
@@ -84,8 +84,9 @@ public class AvailabilityOverUnderGraphType {
// loop through the group avail down intervals
for (ResourceGroupAvailability groupAvailability : groupAvailabilityList) {
// allows substitution for situations like WARN=MIXED for easier terminology
- String availabilityTypeMessage = (groupAvailability.getGroupAvailabilityType().equals(ResourceGroupComposite.GroupAvailabilityType.WARN))
- ? MSG.chart_hover_availability_type_warn() : groupAvailability.getGroupAvailabilityType().name();
+ String availabilityTypeMessage = (groupAvailability.getGroupAvailabilityType()
+ .equals(ResourceGroupComposite.GroupAvailabilityType.WARN)) ? MSG
+ .chart_hover_availability_type_warn() : groupAvailability.getGroupAvailabilityType().name();
sb.append("{ \"availType\":\"" + groupAvailability.getGroupAvailabilityType() + "\", ");
sb.append(" \"availTypeMessage\":\"" + availabilityTypeMessage + "\", ");
@@ -139,7 +140,6 @@ public class AvailabilityOverUnderGraphType {
barOffset = 10,
width = 750 - margin.left - margin.right + barOffset,
height = 40 - margin.top - margin.bottom,
- pixelsOffHeight = 0,
svg;
@@ -161,65 +161,65 @@ public class AvailabilityOverUnderGraphType {
.domain([0, 4]),
xAxis = $wnd.d3.svg.axis()
- .scale(timeScale)
- .ticks(12)
- .tickSize(10, 0, 0)
- .orient("bottom"),
-
- calcBarY = function(d) {
- var ABOVE = -10,
- BELOW = 0,
- STRADDLE = -5,
- offset;
-
- if (d.availType === 'DOWN') {
- offset = BELOW;
- }
- else if (d.availType === 'DISABLED') {
- offset = STRADDLE;
- }
- else if (d.availType === 'UNKNOWN') {
- offset = STRADDLE;
- }
- else if (d.availType === 'UP') {
- offset = ABOVE;
- }
- else if (d.availType === 'WARN') {
- offset = STRADDLE;
- }
- else if (d.availType === 'EMPTY') {
- offset = STRADDLE;
- }
- return yScale(0) + offset;
-
- },
-
- calcBarFill = function(d) {
- if (d.availType === 'DOWN') {
- return "#FF1919"; // red
- }
- else if (d.availType === 'DISABLED') {
- return "#FF9933"; // orange
- }
- else if (d.availType === 'UNKNOWN') {
- return "#CCC"; // gray
- }
- else if (d.availType === 'UP') {
- return "#198C19"; // green
- }
- else if (d.availType === 'WARN') {
- return "#FFA500"; // yellow
- }
- else if (d.availType === 'EMPTY') {
- return "#CCC"; // gray
- }
- else {
- // should not ever happen, but...
- console.warn("AvailabilityType not valid.");
- return "#000"; //black
- }
- },
- svg = $wnd.d3.select(availChartContext.chartSelection).append("g")
+ .scale(timeScale)
+ .ticks(12)
+ .tickSize(13, 0, 0)
+ .orient("bottom"),
+
+ calcBarY = function (d) {
+ var ABOVE = -10,
+ BELOW = 0,
+ STRADDLE = -5,
+ offset;
+
+ if (d.availType === 'DOWN') {
+ offset = BELOW;
+ }
+ else if (d.availType === 'DISABLED') {
+ offset = STRADDLE;
+ }
+ else if (d.availType === 'UNKNOWN') {
+ offset = STRADDLE;
+ }
+ else if (d.availType === 'UP') {
+ offset = ABOVE;
+ }
+ else if (d.availType === 'WARN') {
+ offset = STRADDLE;
+ }
+ else if (d.availType === 'EMPTY') {
+ offset = STRADDLE;
+ }
+ return yScale(0) + offset;
+
+ },
+
+ calcBarFill = function (d) {
+ if (d.availType === 'DOWN') {
+ return "#FF1919"; // red
+ }
+ else if (d.availType === 'DISABLED') {
+ return "url(#diagonalHatchFill)"; // grey diagonal hatches
+ }
+ else if (d.availType === 'UNKNOWN') {
+ return "#CCC"; // gray
+ }
+ else if (d.availType === 'UP') {
+ return "#198C19"; // green
+ }
+ else if (d.availType === 'WARN') {
+ return "#FFA500"; // orange
+ }
+ else if (d.availType === 'EMPTY') {
+ return "#CCC"; // gray
+ }
+ else {
+ // should not ever happen, but...
+ console.warn("AvailabilityType not valid.");
+ return "#000"; //black
+ }
+ },
+ svg = $wnd.d3.select(availChartContext.chartSelection).append("g")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
@@ -234,11 +234,9 @@ public class AvailabilityOverUnderGraphType {
})
.attr("y", function (d) {
return calcBarY(d);
-
})
.attr("height", function (d) {
return 10;
-
})
.attr("width", function (d) {
return timeScale(+d.availEnd) - timeScale(+d.availStart);
@@ -250,43 +248,43 @@ public class AvailabilityOverUnderGraphType {
// create x-axis
svg.append("g")
- .attr("class", "x axis")
- .attr("stroke", "#50505a")
- .attr("stroke-width", "0.5")
- .attr("transform", "translate(0," + height + ")")
- .attr("letter-spacing", "3")
- .style("text-anchor", "end")
- .call(xAxis);
+ .attr("class", "x axis")
+ .attr("fill", "#50505a")
+ .attr("stroke-width", "0.5")
+ .attr("transform", "translate(0," + height + ")")
+ .attr("letter-spacing", "3")
+ .style("text-anchor", "end")
+ .call(xAxis);
svg.append("text")
- .attr("class", "availabilityLabel")
- .attr("x", -40)
- .attr("y", 10)
- .style("font-size", "12px")
- .style("font-family", "Arial, Verdana, sans-serif;")
- .style("font-weight", "bold")
- .attr("fill", "#003168")
- .text("Availability");
+ .attr("class", "availabilityLabel")
+ .attr("x", -40)
+ .attr("y", 10)
+ .style("font-size", "12px")
+ .style("font-family", "Arial, Verdana, sans-serif;")
+ .style("font-weight", "bold")
+ .attr("fill", "#003168")
+ .text("Availability");
svg.append("text")
- .attr("class", "upLabel")
- .attr("x", -5)
- .attr("y", 28)
- .style("font-family", "Arial, Verdana, sans-serif;")
- .style("font-size", "9px")
- .attr("fill", "#50505a")
- .style("text-anchor", "end")
- .text("UP");
+ .attr("class", "upLabel")
+ .attr("x", -5)
+ .attr("y", 28)
+ .style("font-family", "Arial, Verdana, sans-serif;")
+ .style("font-size", "9px")
+ .attr("fill", "#50505a")
+ .style("text-anchor", "end")
+ .text("UP");
svg.append("text")
- .attr("class", "downLabel")
- .attr("x", -5)
- .attr("y", 39)
- .style("font-family", "Arial, Verdana, sans-serif;")
- .style("font-size", "9px")
- .attr("fill", "#50505a")
- .style("text-anchor", "end")
- .text("DOWN");
+ .attr("class", "downLabel")
+ .attr("x", -5)
+ .attr("y", 39)
+ .style("font-family", "Arial, Verdana, sans-serif;")
+ .style("font-size", "9px")
+ .attr("fill", "#50505a")
+ .style("text-anchor", "end")
+ .text("DOWN");
}
@@ -306,19 +304,15 @@ public class AvailabilityOverUnderGraphType {
}
function formatHovers(d) {
- var hoverString,
- timeFormatter = $wnd.d3.time.format(availChartContext.chartHoverTimeFormat),
+ var timeFormatter = $wnd.d3.time.format(availChartContext.chartHoverTimeFormat),
dateFormatter = $wnd.d3.time.format(availChartContext.chartHoverDateFormat),
- availStart = new Date(+d.availStart),
- availEnd = new Date(+d.availEnd);
+ availStart = new Date(+d.availStart);
- hoverString =
- '<div class="chartHoverEnclosingDiv">' +
+ return '<div class="chartHoverEnclosingDiv">' +
'<div class="chartHoverAlignLeft"><span >' + availChartContext.hoverBarAvailabilityLabel + ': </span><span style="width:50px;">' + d.availTypeMessage + '</span></div>' +
- '<div class="chartHoverAlignLeft"><span>'+ dateFormatter(availStart) + ' ' + timeFormatter(availStart) + '</span></div>' +
+ '<div class="chartHoverAlignLeft"><span>' + dateFormatter(availStart) + ' ' + timeFormatter(availStart) + '</span></div>' +
'<div class="chartHoverAlignLeft"><span >' + availChartContext.hoverBarLabel + ': </span><span style="width:50px;">' + d.availDuration + '</span></div>' +
'</div>';
- return hoverString;
}
@@ -341,7 +335,7 @@ public class AvailabilityOverUnderGraphType {
availabilityGraph.draw(availChartContext);
}
- }-*/;
+ }-*/;
public String getChartId() {
return String.valueOf(entityId);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java
index 7df45d1..b876c74 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java
@@ -634,7 +634,7 @@ public abstract class AbstractActivityView extends EnhancedVLayout implements Re
setIsModal(true);
setShowModalMask(true);
setWidth(950);
- setHeight(350);
+ setHeight(370);
setShowResizer(true);
setCanDragResize(true);
centerInPage();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/MetricD3GraphView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/MetricD3GraphView.java
index b590e86..f8887bf 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/MetricD3GraphView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/MetricD3GraphView.java
@@ -67,6 +67,31 @@ public class MetricD3GraphView extends EnhancedVLayout {
+ " width=\"6\" height=\"3\">"
+ " <path d=\"M 0 0 6 0\" style=\"stroke:#2E9EC2; fill:none;\"/>"
+ " </pattern>"
+ + "<pattern id=\"diagonalHatchFill\" patternUnits=\"userSpaceOnUse\" x=\"0\" y=\"0\" width=\"105\" height=\"105\">"
+ + "<g style=\"fill:none; stroke:black; stroke-width:1\">"
+ + "<circle cx=\"0\" cy=\"0\" r=\"1000\" fill=\"grey\"/>"
+ + "<path d=\"M0 90 l15,15\"/>"
+ + "<path d=\"M0 75 l30,30\"/>"
+ + "<path d=\"M0 60 l45,45\"/>"
+ + "<path d=\"M0 45 l60,60\"/>"
+ + "<path d=\"M0 30 l75,75\"/>"
+ + "<path d=\"M0 15 l90,90\"/>"
+ + "<path d=\"M0 0 l105,105\"/>"
+ + "<path d=\"M15 0 l90,90\"/>"
+ + "<path d=\"M30 0 l75,75\"/>"
+ + "<path d=\"M45 0 l60,60\"/>"
+ + "<path d=\"M60 0 l45,45\"/>"
+ + "<path d=\"M75 0 l30,30\"/>"
+ + "<path d=\"M90 0 l15,15\"/>"
+ + "</g>"
+ + "</pattern>"
+ + "<pattern id=\"diagonalHatch\" patternUnits=\"userSpaceOnUse\" x=\"0\" y=\"0\" width=\"105\" height=\"105\">"
+ + "<g style=\"fill:none; stroke:black; stroke-width:1\">" + "<path d=\"M0 90 l15,15\"/>"
+ + "<path d=\"M0 75 l30,30\"/>" + "<path d=\"M0 60 l45,45\"/>" + "<path d=\"M0 45 l60,60\"/>"
+ + "<path d=\"M0 30 l75,75\"/>" + "<path d=\"M0 15 l90,90\"/>" + "<path d=\"M0 0 l105,105\"/>"
+ + "<path d=\"M15 0 l90,90\"/>" + "<path d=\"M30 0 l75,75\"/>" + "<path d=\"M45 0 l60,60\"/>"
+ + "<path d=\"M60 0 l45,45\"/>" + "<path d=\"M75 0 l30,30\"/>" + "<path d=\"M90 0 l15,15\"/>" + "</g>"
+ + "</pattern>"
+ " <pattern id=\"downStripes\" patternUnits=\"userSpaceOnUse\" x=\"0\" y=\"0\""
+ " width=\"6\" height=\"3\">"
+ " <path d=\"M 0 0 6 0\" style=\"stroke:#ff8a9a; fill:none;\"/>"
@@ -101,9 +126,9 @@ public class MetricD3GraphView extends EnhancedVLayout {
StringBuilder divAndSvgDefs = new StringBuilder();
divAndSvgDefs
.append("<div id=\""
- + getFullChartId()
- + "\" ><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" style=\"height:"
- + getChartHeight() + "px;\">");
+ + getFullChartId()
+ + "\" ><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" style=\"height:"
+ + getChartHeight() + "px;\">");
divAndSvgDefs.append(getSvgDefs());
divAndSvgDefs.append("</svg></div>");
@@ -133,14 +158,11 @@ public class MetricD3GraphView extends EnhancedVLayout {
graph.drawJsniChart();
}
-
public String getFullChartId() {
return "rChart-" + graph.getMetricGraphData().getChartId();
}
-
-
public Integer getChartHeight() {
return graph.getMetricGraphData().getChartHeight();
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java
index d06bab2..ca8b117 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java
@@ -25,7 +25,6 @@ import com.smartgwt.client.widgets.HTMLFlow;
import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.resource.group.composite.ResourceGroupAvailability;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityGraph;
-import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityLineGraphType;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType;
import org.rhq.enterprise.gui.coregui.client.util.Log;
import org.rhq.enterprise.gui.coregui.client.util.enhanced.EnhancedVLayout;
@@ -43,7 +42,7 @@ public class AvailabilityD3Graph extends EnhancedVLayout implements Availability
public AvailabilityD3Graph(AvailabilityOverUnderGraphType graphType) {
super();
this.availabilityGraphType = graphType;
- setHeight(70);
+ setHeight(65);
setWidth100();
}
@@ -83,15 +82,26 @@ public class AvailabilityD3Graph extends EnhancedVLayout implements Availability
StringBuilder divAndSvgDefs = new StringBuilder();
divAndSvgDefs.append("<div id=\"availChart-" + availabilityGraphType.getChartId()
- + "\" ><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style=\"height:110px;\">");
+ + "\" ><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style=\"height:65px;\">");
+ divAndSvgDefs.append(getSvgDefs());
divAndSvgDefs.append("</svg></div>");
HTMLFlow graph = new HTMLFlow(divAndSvgDefs.toString());
graph.setWidth100();
- graph.setHeight(25);
+ graph.setHeight(65);
addMember(graph);
}
+ /**
+ * Svg definitions for patterns and gradients to use on SVG shapes.
+ * @return xml String
+ */
+ private static String getSvgDefs() {
+ return " <defs>"+
+ "<pattern id=\"diagonalHatch\" patternUnits=\"userSpaceOnUse\" width=\"4\" height=\"4\"> <path d=\"M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2\" /> </pattern>"
+ + "</defs>";
+ }
+
@Override
public void destroy() {
super.destroy();
11 years, 1 month
[rhq] Branch 'feature/cassandra-backend' - modules/common modules/core modules/enterprise modules/helpers
by snegrea
modules/common/cassandra-ccm/cassandra-ccm-arquillian/src/main/java/org/rhq/cassandra/ccm/arquillian/CCMSuiteDeploymentExtension.java | 4
modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java | 26 +
modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java | 132 ----------
modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java | 109 +++++---
modules/common/cassandra-ccm/cassandra-ccm-maven-plugin/src/main/java/org/rhq/cassandra/ccm/maven/DeployMojo.java | 4
modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java | 11
modules/common/cassandra-schema/src/main/java/org/rhq/cassandra/schema/SchemaManager.java | 16 -
modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java | 7
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/CassandraClusterHeartBeatJob.java | 8
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java | 8
modules/helpers/metrics-simulator/pom.xml | 10
modules/helpers/metrics-simulator/src/main/java/org/rhq/metrics/simulator/Simulator.java | 25 -
12 files changed, 147 insertions(+), 213 deletions(-)
New commits:
commit 5c472c8c754ca2767a646485fc55a6f331c24dea
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Tue May 7 21:57:14 2013 -0500
Remove CassandraNode entity local to ccm modules in favor of the domain StorageNode entity.
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-arquillian/src/main/java/org/rhq/cassandra/ccm/arquillian/CCMSuiteDeploymentExtension.java b/modules/common/cassandra-ccm/cassandra-ccm-arquillian/src/main/java/org/rhq/cassandra/ccm/arquillian/CCMSuiteDeploymentExtension.java
index b7073ae..0f297ca 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-arquillian/src/main/java/org/rhq/cassandra/ccm/arquillian/CCMSuiteDeploymentExtension.java
+++ b/modules/common/cassandra-ccm/cassandra-ccm-arquillian/src/main/java/org/rhq/cassandra/ccm/arquillian/CCMSuiteDeploymentExtension.java
@@ -56,11 +56,11 @@ import org.jboss.arquillian.test.spi.event.suite.AfterClass;
import org.jboss.arquillian.test.spi.event.suite.BeforeClass;
import org.rhq.cassandra.CassandraClusterManager;
-import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.ClusterInitService;
import org.rhq.cassandra.DeploymentOptions;
import org.rhq.cassandra.DeploymentOptionsFactory;
import org.rhq.cassandra.schema.SchemaManager;
+import org.rhq.core.domain.cloud.StorageNode;
/**
* @author John Sanda
@@ -109,7 +109,7 @@ public class CCMSuiteDeploymentExtension implements LoadableExtension {
ManagerStarted event, ArquillianDescriptor descriptor) {
deploymentClass = getDeploymentClass(descriptor);
- List<CassandraNode> nodes = ccm.createCluster();
+ List<StorageNode> nodes = ccm.createCluster();
ccm.startCluster(false);
ClusterInitService clusterInitService = new ClusterInitService();
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java
index b33cc27..9a25532 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java
+++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java
@@ -41,6 +41,7 @@ import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.core.pluginapi.util.ProcessExecutionUtility;
import org.rhq.core.system.OperatingSystemType;
import org.rhq.core.system.ProcessExecution;
@@ -82,7 +83,7 @@ public class CassandraClusterManager {
}
}
- public List<CassandraNode> createCluster() {
+ public List<StorageNode> createCluster() {
if (log.isDebugEnabled()) {
log.debug("Installing embedded " + deploymentOptions.getNumNodes() + " node cluster to " +
deploymentOptions.getClusterDir());
@@ -100,7 +101,7 @@ public class CassandraClusterManager {
}
FileUtil.purge(clusterDir, false);
- List<CassandraNode> nodes = new ArrayList<CassandraNode>(deploymentOptions.getNumNodes());
+ List<StorageNode> nodes = new ArrayList<StorageNode>(deploymentOptions.getNumNodes());
String seeds = collectionToString(calculateLocalIPAddresses(deploymentOptions.getNumNodes()));
for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) {
@@ -127,8 +128,12 @@ public class CassandraClusterManager {
deployer.applyConfigChanges();
deployer.updateFilePerms();
- nodes.add(new CassandraNode(address, deploymentOptions.getJmxPort() + i,
- nodeOptions.getNativeTransportPort()));
+ StorageNode storageNode = new StorageNode();
+ storageNode.setAddress(address);
+ storageNode.setJmxPort(deploymentOptions.getJmxPort() + i);
+ storageNode.setCqlPort(nodeOptions.getNativeTransportPort());
+ nodes.add(storageNode);
+
installedNodeDirs.add(basedir);
} catch (Exception e) {
log.error("Failed to install node at " + basedir);
@@ -155,11 +160,14 @@ public class CassandraClusterManager {
return "127.0.0." + i;
}
- private List<CassandraNode> calculateNodes() {
- List<CassandraNode> nodes = new ArrayList<CassandraNode>(deploymentOptions.getNumNodes());
+ private List<StorageNode> calculateNodes() {
+ List<StorageNode> nodes = new ArrayList<StorageNode>(deploymentOptions.getNumNodes());
for (int i = 0; i < deploymentOptions.getNumNodes(); ++i) {
- nodes.add(new CassandraNode(getLocalIPAddress(i + 1), deploymentOptions.getJmxPort() + i,
- deploymentOptions.getNativeTransportPort()));
+ StorageNode storageNode = new StorageNode();
+ storageNode.setAddress(getLocalIPAddress(i + 1));
+ storageNode.setJmxPort(deploymentOptions.getJmxPort() + i);
+ storageNode.setCqlPort(deploymentOptions.getNativeTransportPort());
+ nodes.add(storageNode);
}
return nodes;
}
@@ -172,7 +180,7 @@ public class CassandraClusterManager {
startCluster(getNodeIds());
if (waitForClusterToStart) {
- List<CassandraNode> nodes = calculateNodes();
+ List<StorageNode> nodes = calculateNodes();
ClusterInitService clusterInitService = new ClusterInitService();
clusterInitService.waitForClusterToStart(nodes, nodes.size(), 20);
}
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java
deleted file mode 100644
index 88b4a65..0000000
--- a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- *
- * * RHQ Management Platform
- * * Copyright (C) 2005-2012 Red Hat, Inc.
- * * All rights reserved.
- * *
- * * This program is free software; you can redistribute it and/or modify
- * * it under the terms of the GNU General Public License, version 2, as
- * * published by the Free Software Foundation, and/or the GNU Lesser
- * * General Public License, version 2.1, also as published by the Free
- * * Software Foundation.
- * *
- * * This program is distributed in the hope that it will be useful,
- * * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * * GNU General Public License and the GNU Lesser General Public License
- * * for more details.
- * *
- * * You should have received a copy of the GNU General Public License
- * * and the GNU Lesser General Public License along with this program;
- * * if not, write to the Free Software Foundation, Inc.,
- * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- */
-
-package org.rhq.cassandra;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.management.MBeanServerConnection;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorFactory;
-import javax.management.remote.JMXServiceURL;
-import javax.naming.Context;
-
-import org.rhq.cassandra.installer.RMIContextFactory;
-
-/**
- * @author John Sanda
- * @author Jirka Kremser
- */
-public class CassandraNode {
-
- private String hostName;
-
- private int jmxPort;
-
- private int nativeTransportPort;
-
- private static final String JMX_CONNECTION_STRING = "service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi";
-
- public CassandraNode(String hostName, int jmxPort, int nativeTransportPort) {
- this.hostName = hostName;
- this.jmxPort = jmxPort;
- this.nativeTransportPort = nativeTransportPort;
- }
-
- public String getHostName() {
- return hostName;
- }
-
- public int getJmxPort() {
- return jmxPort;
- }
-
- public int getNativeTransportPort() {
- return nativeTransportPort;
- }
-
- public boolean isNativeTransportRunning() throws Exception {
- Boolean nativeTransportRunning = false;
- String url = String.format(JMX_CONNECTION_STRING, getHostName(), getJmxPort());
- JMXServiceURL serviceURL = new JMXServiceURL(url);
- Map<String, String> env = new HashMap<String, String>();
- // see https://issues.jboss.org/browse/AS7-2138
- env.put(Context.INITIAL_CONTEXT_FACTORY, RMIContextFactory.class.getName());
- JMXConnector connector = null;
-
- try {
- connector = JMXConnectorFactory.connect(serviceURL, env);
- MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
- ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
- nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService, "NativeTransportRunning");
- } finally {
- if (connector != null) {
- connector.close();
- }
- }
- return nativeTransportRunning;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- CassandraNode that = (CassandraNode) o;
-
- if (jmxPort != that.jmxPort) return false;
- if (nativeTransportPort != that.nativeTransportPort) return false;
- if (!hostName.equals(that.hostName)) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((hostName == null) ? 0 : hostName.hashCode());
- result = prime * result + jmxPort;
- result = prime * result + nativeTransportPort;
- return result;
- }
-
- @Override
- public String toString() {
- return "CassandraNode[hostName: " + hostName + ", jmxPort: " + jmxPort + ", nativeTransportPort: " +
- nativeTransportPort + "]";
- }
-
- public static CassandraNode parseNode(String s) {
- String[] params = s.split("\\|");
- if (params.length != 3) {
- throw new IllegalArgumentException(
- "Expected string of the form, hostname|jmxPort|nativeTransportPort but got: " + s);
- }
- return new CassandraNode(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]));
- }
-}
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java
index 5851e58..0b38fb0 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java
+++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/ClusterInitService.java
@@ -26,13 +26,22 @@
package org.rhq.cassandra;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
+import javax.management.MBeanServerConnection;
+import javax.management.ObjectName;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+import javax.naming.Context;
+
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
@@ -45,6 +54,9 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.rhq.cassandra.installer.RMIContextFactory;
+import org.rhq.core.domain.cloud.StorageNode;
+
/**
* This class provides operations to ensure a cluster is initialized and in a consistent
* state. It does not offer functionality for initializing a cluster but rather to make
@@ -54,20 +66,20 @@ import org.apache.commons.logging.LogFactory;
* @author Jirka Kremser
*/
public final class ClusterInitService {
-
+
private final Log log = LogFactory.getLog(ClusterInitService.class);
-
- private Session initRhqSession(List<CassandraNode> hosts) {
- return initSession(hosts, "rhq", "rhqadmin", "rhqadmin");
+
+ private Session initRhqSession(List<StorageNode> storageNodes) {
+ return initSession(storageNodes, "rhq", "rhqadmin", "rhqadmin");
}
-
- private Session initSession(List<CassandraNode> hosts, String keySpace, String username, String password) {
+
+ private Session initSession(List<StorageNode> hosts, String keySpace, String username, String password) {
if (hosts == null) {
throw new IllegalArgumentException("No cassandra nodes were provided.");
}
String[] addresses = new String[hosts.size()];
for (int i = 0; i < hosts.size(); i++) {
- addresses[i] = hosts.get(i).getHostName();
+ addresses[i] = hosts.get(i).getAddress();
}
Cluster cluster = Cluster.builder().addContactPoints(addresses).withoutMetrics()
.withAuthInfoProvider(new SimpleAuthInfoProvider().add("username", username).add("password", password))
@@ -75,14 +87,14 @@ public final class ClusterInitService {
Session session = cluster.connect(keySpace);
return session;
}
-
- public boolean ping(List<CassandraNode> hosts, int numHosts) {
+
+ public boolean ping(List<StorageNode> storageNodes, int numHosts) {
int connections = 0;
long sleep = 100;
- for (CassandraNode host : hosts) {
+ for (StorageNode host : storageNodes) {
try {
- boolean isNativeTransportRunning = host.isNativeTransportRunning();
+ boolean isNativeTransportRunning = this.isNativeTransportRunning(host);
if (isNativeTransportRunning) {
++connections;
}
@@ -113,8 +125,8 @@ public final class ClusterInitService {
*
* @param hosts The cluster nodes to which a connection should be made
*/
- public void waitForClusterToStart(List<CassandraNode> hosts) {
- waitForClusterToStart(hosts, hosts.size(), 10);
+ public void waitForClusterToStart(List<StorageNode> storageNodes) {
+ waitForClusterToStart(storageNodes, storageNodes.size(), 10);
}
/**
@@ -136,11 +148,10 @@ public final class ClusterInitService {
* @param retries The number of times to retry connecting. A runtime exception will be
* thrown when the number of failed connections exceeds this value.
*/
- public void waitForClusterToStart(List<CassandraNode> hosts, int numHosts, int retries) {
- waitForClusterToStart(hosts, numHosts, 250, retries, 1);
+ public void waitForClusterToStart(List<StorageNode> storageNodes, int numHosts, int retries) {
+ waitForClusterToStart(storageNodes, numHosts, 250, retries, 1);
}
-
-
+
/**
* This method attempts to establish a Thrift RPC connection to each host for the
* number specified. In other words, if there are four hosts and <code>numHosts</code>
@@ -162,7 +173,8 @@ public final class ClusterInitService {
* thrown when the number of failed connections exceeds this value.
* @param initialWait The amount of seconds before first try.
*/
- public void waitForClusterToStart(List<CassandraNode> hosts, int numHosts, long delay, int retries, int initialWait) {
+ public void waitForClusterToStart(List<StorageNode> storageNodes, int numHosts, long delay, int retries,
+ int initialWait) {
if (initialWait > 0) {
try {
if (log.isDebugEnabled()) {
@@ -172,21 +184,21 @@ public final class ClusterInitService {
} catch (InterruptedException e) {
}
}
-
+
int connections = 0;
int failedConnections = 0;
- Queue<CassandraNode> queue = new LinkedList<CassandraNode>(hosts);
- CassandraNode host = queue.poll();
+ Queue<StorageNode> queue = new LinkedList<StorageNode>(storageNodes);
+ StorageNode storageNode = queue.poll();
- while (host != null) {
+ while (storageNode != null) {
if (failedConnections >= retries) {
throw new RuntimeException("Unable to verify that cluster nodes have started after "
+ failedConnections + " failed attempts");
}
try {
- boolean isNativeTransportRunning = host.isNativeTransportRunning();
+ boolean isNativeTransportRunning = this.isNativeTransportRunning(storageNode);
if (log.isDebugEnabled() && isNativeTransportRunning) {
- log.debug("Successfully connected to cassandra node [" + host + "]");
+ log.debug("Successfully connected to cassandra node [" + storageNode + "]");
}
if (isNativeTransportRunning) {
++connections;
@@ -204,9 +216,9 @@ public final class ClusterInitService {
}
} catch (Exception e) {
++failedConnections;
- queue.offer(host);
+ queue.offer(storageNode);
if (log.isDebugEnabled()) {
- log.debug("Unable to open JMX connection to cassandra node [" + host + "].", e);
+ log.debug("Unable to open JMX connection to cassandra node [" + storageNode + "].", e);
} else if (log.isInfoEnabled()) {
log.debug("Unable to open connection to cassandra node.");
}
@@ -215,10 +227,10 @@ public final class ClusterInitService {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
- host = queue.poll();
+ storageNode = queue.poll();
}
}
-
+
/**
* Waits for the cluster to reach schema agreement. During cluster initialization
* before and while schema changes propagate throughout the cluster, there could be
@@ -227,20 +239,23 @@ public final class ClusterInitService {
*
* @param hosts The cluster nodes
*/
- public void waitForSchemaAgreement(List<CassandraNode> hosts) {
- if (hosts == null) return;
+ public void waitForSchemaAgreement(List<StorageNode> storageNodes) {
+ if (storageNodes == null) {
+ return;
+ }
+
long sleep = 100L;
boolean schemaInAgreement = false;
while (!schemaInAgreement) {
Set<UUID> schemaVersions = new HashSet<UUID>();
try {
- for (CassandraNode host : hosts) {
+ for (StorageNode host : storageNodes) {
UUID otherSchchemaVersion = getSchemaVersionForNode(host);
schemaVersions.add(otherSchchemaVersion);
}
} catch (NoHostAvailableException e) {
- throw new RuntimeException("Unable to get schema versions from " + hosts.get(0), e);
+ throw new RuntimeException("Unable to get schema versions from " + storageNodes.get(0), e);
}
if (schemaVersions.size() > 1) {
if (log.isInfoEnabled()) {
@@ -261,7 +276,7 @@ public final class ClusterInitService {
} else {
if (log.isInfoEnabled()) {
log.info("Schema agreement has not been reached. Unable to get the schema version from cassandra nodes ["
- + hosts + "]");
+ + storageNodes + "]");
}
try {
Thread.sleep(sleep);
@@ -272,11 +287,33 @@ public final class ClusterInitService {
}
}
-
- private UUID getSchemaVersionForNode(CassandraNode node) {
+
+ public boolean isNativeTransportRunning(StorageNode storageNode) throws Exception {
+ Boolean nativeTransportRunning = false;
+ String url = storageNode.getJMXConnectionURL();
+ JMXServiceURL serviceURL = new JMXServiceURL(url);
+ Map<String, String> env = new HashMap<String, String>();
+ // see https://issues.jboss.org/browse/AS7-2138
+ env.put(Context.INITIAL_CONTEXT_FACTORY, RMIContextFactory.class.getName());
+ JMXConnector connector = null;
+
+ try {
+ connector = JMXConnectorFactory.connect(serviceURL, env);
+ MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
+ ObjectName storageService = new ObjectName("org.apache.cassandra.db:type=StorageService");
+ nativeTransportRunning = (Boolean) serverConnection.getAttribute(storageService, "NativeTransportRunning");
+ } finally {
+ if (connector != null) {
+ connector.close();
+ }
+ }
+ return nativeTransportRunning;
+ }
+
+ private UUID getSchemaVersionForNode(StorageNode storageNode) {
Session session = null;
try {
- session = initRhqSession(Arrays.asList(node));
+ session = initRhqSession(Arrays.asList(storageNode));
PreparedStatement statement = session.prepare("SELECT schema_version from system.local");
BoundStatement boundStatement = statement.bind();
ResultSet rs = session.execute(boundStatement);
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-maven-plugin/src/main/java/org/rhq/cassandra/ccm/maven/DeployMojo.java b/modules/common/cassandra-ccm/cassandra-ccm-maven-plugin/src/main/java/org/rhq/cassandra/ccm/maven/DeployMojo.java
index 24621ed..5cdff36 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-maven-plugin/src/main/java/org/rhq/cassandra/ccm/maven/DeployMojo.java
+++ b/modules/common/cassandra-ccm/cassandra-ccm-maven-plugin/src/main/java/org/rhq/cassandra/ccm/maven/DeployMojo.java
@@ -35,10 +35,10 @@ import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.rhq.cassandra.CassandraClusterManager;
-import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.DeploymentOptions;
import org.rhq.cassandra.DeploymentOptionsFactory;
import org.rhq.cassandra.schema.SchemaManager;
+import org.rhq.core.domain.cloud.StorageNode;
/**
* @author John Sanda
@@ -63,7 +63,7 @@ public class DeployMojo extends AbstractMojo {
long start = System.currentTimeMillis();
getLog().info("Creating " + numNodes + " cluster in " + clusterDir);
- List<CassandraNode> nodes = ccm.createCluster();
+ List<StorageNode> nodes = ccm.createCluster();
getLog().info("Starting cluster nodes");
ccm.startCluster();
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java
index 684c2d5..93897ab 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java
+++ b/modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java/org/rhq/cassandra/CCMTestNGListener.java
@@ -36,6 +36,7 @@ import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
import org.rhq.cassandra.schema.SchemaManager;
+import org.rhq.core.domain.cloud.StorageNode;
/**
* @author John Sanda
@@ -95,12 +96,14 @@ public class CCMTestNGListener implements IInvokedMethodListener {
// consistency and failover. If we start doing that at some point, then
// we cannot initialize ccm here.
ccm = new CassandraClusterManager(deploymentOptions);
- List<CassandraNode> nodes = ccm.createCluster();
+ ClusterInitService clusterInitService = new ClusterInitService();
+
+ List<StorageNode> nodes = ccm.createCluster();
if (System.getProperty("rhq.cassandra.cluster.skip-shutdown") == null) {
- for (CassandraNode node : nodes) {
+ for (StorageNode node : nodes) {
try {
- if (node.isNativeTransportRunning()) {
+ if (clusterInitService.isNativeTransportRunning(node)) {
throw new RuntimeException("A cluster is already running on the same ports.");
}
} catch (Exception e) {
@@ -110,7 +113,7 @@ public class CCMTestNGListener implements IInvokedMethodListener {
}
ccm.startCluster(false);
- ClusterInitService clusterInitService = new ClusterInitService ();
+
clusterInitService.waitForClusterToStart(nodes, nodes.size(), 1500, 20, 2);
SchemaManager schemaManager = new SchemaManager(annotation.username(), annotation.password(), nodes);
diff --git a/modules/common/cassandra-schema/src/main/java/org/rhq/cassandra/schema/SchemaManager.java b/modules/common/cassandra-schema/src/main/java/org/rhq/cassandra/schema/SchemaManager.java
index 87becb1..bd2cdd7 100644
--- a/modules/common/cassandra-schema/src/main/java/org/rhq/cassandra/schema/SchemaManager.java
+++ b/modules/common/cassandra-schema/src/main/java/org/rhq/cassandra/schema/SchemaManager.java
@@ -38,8 +38,8 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.util.ClusterBuilder;
+import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.core.util.StringUtil;
/**
@@ -57,7 +57,7 @@ public class SchemaManager {
private String password;
- private List<CassandraNode> nodes = new ArrayList<CassandraNode>();
+ private List<StorageNode> nodes = new ArrayList<StorageNode>();
public SchemaManager(String username, String password, String... nodes) {
try {
@@ -65,8 +65,10 @@ public class SchemaManager {
this.password = password;
for (String node : nodes) {
- CassandraNode cassandraNode = CassandraNode.parseNode(node);
- this.nodes.add(cassandraNode);
+ StorageNode storageNode = new StorageNode();
+ storageNode.parseNodeInformation(node);
+
+ this.nodes.add(storageNode);
}
initCluster();
@@ -75,7 +77,7 @@ public class SchemaManager {
}
}
- public SchemaManager(String username, String password, List<CassandraNode> nodes) {
+ public SchemaManager(String username, String password, List<StorageNode> nodes) {
try {
this.username = username;
this.password = password;
@@ -90,7 +92,7 @@ public class SchemaManager {
private void initCluster() throws NoHostAvailableException {
String[] hostNames = new String[nodes.size()];
for (int i = 0; i < hostNames.length; ++i) {
- hostNames[i] = nodes.get(i).getHostName();
+ hostNames[i] = nodes.get(i).getAddress();
}
if (log.isDebugEnabled()) {
@@ -103,7 +105,7 @@ public class SchemaManager {
authInfoProvider.add("username", username).add("password", password);
Cluster cluster = new ClusterBuilder().addContactPoints(hostNames).withAuthInfoProvider(authInfoProvider)
- .withPort(nodes.get(0).getNativeTransportPort()).build();
+ .withPort(nodes.get(0).getCqlPort()).build();
session = cluster.connect("system");
}
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
index 4a29838..d5274ec 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
@@ -72,6 +72,8 @@ public class StorageNode implements Serializable {
public static final String QUERY_DELETE_BY_ID = "StorageNode.deleteById";
public static final String QUERY_FIND_ALL_NORMAL = "StorageNode.findAllNormalCloudMembers";
+ private static final String JMX_CONNECTION_STRING = "service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi";
+
@Column(name = "ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "RHQ_STORAGE_NODE_ID_SEQ")
@Id
@@ -188,6 +190,11 @@ public class StorageNode implements Serializable {
}
}
+ public String getJMXConnectionURL() {
+ String[] split = JMX_CONNECTION_STRING.split("%s");
+ return split[0] + this.address + split[1] + this.jmxPort + split[2];
+ }
+
@Override
public String toString() {
return "StorageNode [id=" + id + ", address=" + address + ", jmxPort=" + jmxPort + ", cqlPort=" + cqlPort
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/CassandraClusterHeartBeatJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/CassandraClusterHeartBeatJob.java
index e8a8c8d..6b19f0b 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/CassandraClusterHeartBeatJob.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/CassandraClusterHeartBeatJob.java
@@ -38,10 +38,10 @@ import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
-import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.ClusterInitService;
import org.rhq.core.domain.cloud.Server;
import org.rhq.core.domain.cloud.Server.OperationMode;
+import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.enterprise.server.auth.SubjectManagerLocal;
import org.rhq.enterprise.server.cloud.TopologyManagerLocal;
import org.rhq.enterprise.server.cloud.instance.ServerManagerLocal;
@@ -65,10 +65,12 @@ public class CassandraClusterHeartBeatJob implements Job {
JobDataMap dataMap = context.getMergedJobDataMap();
String hosts = (String) dataMap.get(KEY_CASSANDRA_HOSTS);
int timeout = Integer.parseInt((String) dataMap.get(KEY_CONNECTION_TIMEOUT));
- List<CassandraNode> cassandraHosts = new ArrayList<CassandraNode>();
+ List<StorageNode> cassandraHosts = new ArrayList<StorageNode>();
for (String s : hosts.split(",")) {
- cassandraHosts.add(CassandraNode.parseNode(s));
+ StorageNode storageNode = new StorageNode();
+ storageNode.parseNodeInformation(s);
+ cassandraHosts.add(storageNode);
}
boolean pingable = clusterInitService.ping(cassandraHosts, 1);
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
index 5e2505e..2cc0978 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
@@ -38,7 +38,6 @@ import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SimpleAuthInfoProvider;
-import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.util.ClusterBuilder;
import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.core.domain.cloud.StorageNode.OperationMode;
@@ -82,9 +81,10 @@ public class SessionManagerBean {
String[] seeds = seedProp.split(",");
String[] hostNames = new String[seeds.length];
for (int i = 0; i < seeds.length; ++i) {
- CassandraNode node = CassandraNode.parseNode(seeds[i]);
- port = node.getNativeTransportPort();
- hostNames[i] = node.getHostName();
+ StorageNode node = new StorageNode();
+ node.parseNodeInformation(seeds[i]);
+ port = node.getCqlPort();
+ hostNames[i] = node.getAddress();
}
if (port == -1) {
diff --git a/modules/helpers/metrics-simulator/pom.xml b/modules/helpers/metrics-simulator/pom.xml
index f5d2fcd..96f1307 100644
--- a/modules/helpers/metrics-simulator/pom.xml
+++ b/modules/helpers/metrics-simulator/pom.xml
@@ -5,7 +5,7 @@
<groupId>org.rhq.helpers</groupId>
<version>4.7.0-SNAPSHOT</version>
</parent>
-
+
<modelVersion>4.0.0</modelVersion>
<artifactId>rhq-metrics-simulator</artifactId>
<name>RHQ Metrics Simulator</name>
@@ -16,7 +16,13 @@
<artifactId>rhq-cassandra-schema</artifactId>
<version>${project.version}</version>
</dependency>
-
+
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-core-domain</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
<dependency>
<groupId>org.rhq</groupId>
<artifactId>rhq-server-metrics</artifactId>
diff --git a/modules/helpers/metrics-simulator/src/main/java/org/rhq/metrics/simulator/Simulator.java b/modules/helpers/metrics-simulator/src/main/java/org/rhq/metrics/simulator/Simulator.java
index 1cb5f31..d3085ad 100644
--- a/modules/helpers/metrics-simulator/src/main/java/org/rhq/metrics/simulator/Simulator.java
+++ b/modules/helpers/metrics-simulator/src/main/java/org/rhq/metrics/simulator/Simulator.java
@@ -47,13 +47,14 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.Minutes;
+
import org.rhq.cassandra.CassandraClusterManager;
-import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.ClusterInitService;
import org.rhq.cassandra.DeploymentOptions;
import org.rhq.cassandra.DeploymentOptionsFactory;
import org.rhq.cassandra.schema.SchemaManager;
import org.rhq.cassandra.util.ClusterBuilder;
+import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.metrics.simulator.plan.ClusterConfig;
import org.rhq.metrics.simulator.plan.ScheduleGroup;
import org.rhq.metrics.simulator.plan.SimulationPlan;
@@ -83,7 +84,7 @@ public class Simulator implements ShutdownManager {
}
});
- List<CassandraNode> nodes = initCluster(plan);
+ List<StorageNode> nodes = initCluster(plan);
createSchema(nodes);
@@ -168,9 +169,9 @@ public class Simulator implements ShutdownManager {
log.info("Shut down complete");
}
- private List<CassandraNode> initCluster(SimulationPlan plan) {
+ private List<StorageNode> initCluster(SimulationPlan plan) {
try {
- List<CassandraNode> nodes = deployCluster(plan.getClusterConfig());
+ List<StorageNode> nodes = deployCluster(plan.getClusterConfig());
waitForClusterToInitialize(nodes);
return nodes;
} catch (Exception e) {
@@ -178,7 +179,7 @@ public class Simulator implements ShutdownManager {
}
}
- private List<CassandraNode> deployCluster(ClusterConfig clusterConfig) throws IOException {
+ private List<StorageNode> deployCluster(ClusterConfig clusterConfig) throws IOException {
File clusterDir = new File(clusterConfig.getClusterDir(), "cassandra");
log.info("Deploying cluster to " + clusterDir);
clusterDir.mkdirs();
@@ -196,7 +197,7 @@ public class Simulator implements ShutdownManager {
deploymentOptions.load();
ccm = new CassandraClusterManager(deploymentOptions);
- List<CassandraNode> nodes = ccm.createCluster();
+ List<StorageNode> nodes = ccm.createCluster();
ccm.startCluster(false);
return nodes;
@@ -207,13 +208,13 @@ public class Simulator implements ShutdownManager {
ccm.shutdownCluster();
}
- private void waitForClusterToInitialize(List<CassandraNode> nodes) {
+ private void waitForClusterToInitialize(List<StorageNode> nodes) {
log.info("Waiting for cluster to initialize");
ClusterInitService clusterInitService = new ClusterInitService();
clusterInitService.waitForClusterToStart(nodes, nodes.size(), 1500, 20, 2);
}
- private void createSchema(List<CassandraNode> nodes) {
+ private void createSchema(List<StorageNode> nodes) {
try {
log.info("Creating schema");
SchemaManager schemaManager = new SchemaManager("rhqadmin", "rhqadmin", nodes);
@@ -224,7 +225,7 @@ public class Simulator implements ShutdownManager {
}
}
- private Session createSession(List<CassandraNode> nodes) throws NoHostAvailableException {
+ private Session createSession(List<StorageNode> nodes) throws NoHostAvailableException {
try {
SimpleAuthInfoProvider authInfoProvider = new SimpleAuthInfoProvider();
authInfoProvider.add("username", "rhqadmin").add("password", "rhqadmin");
@@ -244,7 +245,7 @@ public class Simulator implements ShutdownManager {
}
}
- private Session createSession(List<CassandraNode> nodes, ProtocolOptions.Compression compression)
+ private Session createSession(List<StorageNode> nodes, ProtocolOptions.Compression compression)
throws NoHostAvailableException {
try {
log.debug("Creating session using " + compression.name() + " compression");
@@ -276,10 +277,10 @@ public class Simulator implements ShutdownManager {
return cluster.connect("rhq");
}
- private String[] getHostNames(List<CassandraNode> nodes) {
+ private String[] getHostNames(List<StorageNode> nodes) {
String[] hostnames = new String[nodes.size()];
for (int i = 0; i < hostnames.length; ++i) {
- hostnames[i] = nodes.get(i).getHostName();
+ hostnames[i] = nodes.get(i).getAddress();
}
return hostnames;
}
11 years, 1 month
[rhq] 2 commits - .gitignore modules/enterprise
by mike thompson
.gitignore | 2
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java | 381 ++++++++++
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/StackedBarMetricGraphImpl.java | 6
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/D3GroupGraphListView.java | 3
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/D3GraphListView.java | 3
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java | 9
6 files changed, 395 insertions(+), 9 deletions(-)
New commits:
commit ee5255b684d733fa01989930676f5d0e7e17d51e
Author: mtho11 <mikecthompson(a)gmail.com>
Date: Mon May 6 14:23:28 2013 -0700
[BZ 960646] - RFE Redesigned Availability Charts.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java
new file mode 100644
index 0000000..76c8f69
--- /dev/null
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/AvailabilityOverUnderGraphType.java
@@ -0,0 +1,381 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.enterprise.gui.coregui.client.inventory.common.charttype;
+
+import org.rhq.core.domain.measurement.Availability;
+import org.rhq.core.domain.measurement.MeasurementUnits;
+import org.rhq.core.domain.resource.group.composite.ResourceGroupAvailability;
+import org.rhq.core.domain.resource.group.composite.ResourceGroupComposite;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.Messages;
+import org.rhq.enterprise.gui.coregui.client.util.Log;
+import org.rhq.enterprise.gui.coregui.client.util.MeasurementConverterClient;
+
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Contains the javascript chart definition for an implementation of the d3 availability chart. This implementation is
+ * just a line that changes color based on availability type: up=green, down=red, orange=disabled, unknown=grey,
+ * empty=grey, warn=yellow. This version of the availability graph shows continuous intervals.
+ *
+ * @author Mike Thompson
+ */
+public class AvailabilityOverUnderGraphType {
+
+ private static Messages MSG = CoreGUI.getMessages();
+ private List<Availability> availabilityList;
+ private List<ResourceGroupAvailability> groupAvailabilityList;
+ private Integer entityId;
+
+ /**
+ * General constructor for stacked bar graph when you have all the data needed to produce the graph. (This is true
+ * for all cases but the dashboard portlet).
+ */
+ public AvailabilityOverUnderGraphType(Integer entityId) {
+ this.entityId = entityId;
+ }
+
+ public void setAvailabilityList(List<Availability> availabilityList) {
+ this.availabilityList = availabilityList;
+ }
+
+ public void setGroupAvailabilityList(List<ResourceGroupAvailability> groupAvailabilityList) {
+ this.groupAvailabilityList = groupAvailabilityList;
+ }
+
+ public String getAvailabilityJson() {
+ StringBuilder sb = new StringBuilder("[");
+ if (null != availabilityList) {
+ // loop through the avail intervals
+ for (Availability availability : availabilityList) {
+ sb.append("{ \"availType\":\"" + availability.getAvailabilityType() + "\", ");
+ sb.append(" \"availTypeMessage\":\"" + availability.getAvailabilityType()+ "\", ");
+ sb.append(" \"availStart\":" + availability.getStartTime() + ", ");
+ // last record will be null
+ long endTime = availability.getEndTime() != null ? availability.getEndTime() : (new Date()).getTime();
+ sb.append(" \"availEnd\":" + endTime + ", ");
+
+ long availDuration = endTime - availability.getStartTime();
+ String availDurationString = MeasurementConverterClient.format((double) availDuration,
+ MeasurementUnits.MILLISECONDS, true);
+ sb.append(" \"availDuration\": \"" + availDurationString + "\" },");
+
+ }
+ sb.setLength(sb.length() - 1);
+
+ } else if (null != groupAvailabilityList) {
+ // loop through the group avail down intervals
+ for (ResourceGroupAvailability groupAvailability : groupAvailabilityList) {
+ // allows substitution for situations like WARN=MIXED for easier terminology
+ String availabilityTypeMessage = (groupAvailability.getGroupAvailabilityType().equals(ResourceGroupComposite.GroupAvailabilityType.WARN))
+ ? MSG.chart_hover_availability_type_warn() : groupAvailability.getGroupAvailabilityType().name();
+
+ sb.append("{ \"availType\":\"" + groupAvailability.getGroupAvailabilityType() + "\", ");
+ sb.append(" \"availTypeMessage\":\"" + availabilityTypeMessage + "\", ");
+ sb.append(" \"availStart\":" + groupAvailability.getStartTime() + ", ");
+ // last record will be null
+ long endTime = groupAvailability.getEndTime() != null ? groupAvailability.getEndTime() : (new Date())
+ .getTime();
+ sb.append(" \"availEnd\":" + endTime + ", ");
+
+ long availDuration = endTime - groupAvailability.getStartTime();
+ String availDurationString = MeasurementConverterClient.format((double) availDuration,
+ MeasurementUnits.MILLISECONDS, true);
+ sb.append(" \"availDuration\": \"" + availDurationString + "\" },");
+
+ }
+ sb.setLength(sb.length() - 1);
+ }
+
+ sb.append("]");
+ Log.debug(sb.toString());
+ return sb.toString();
+ }
+
+ /**
+ * The magic JSNI to draw the charts with d3.
+ */
+ public native void drawJsniChart() /*-{
+ console.log("Draw Enhanced Availability chart");
+
+ var global = this,
+ // tidy up all of our interactions with java (via JSNI) thru AvailChartContext class
+ // NOTE: rhq.js has the javascript object constructors in it.
+ availChartContext = new $wnd.AvailChartContext(global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartId()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getAvailabilityJson()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartDateLabel()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartTimeLabel()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartHoverStartLabel()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartHoverEndLabel()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartHoverBarLabel()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartHoverAvailabilityLabel()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartHoverTimeFormat()(),
+ global.@org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType::getChartHoverDateFormat()()
+ );
+
+
+ var availabilityGraph = function () {
+ "use strict";
+ // privates
+
+ var margin = {top: 5, right: 5, bottom: 5, left: 40},
+ barOffset = 10,
+ width = 750 - margin.left - margin.right + barOffset,
+ height = 40 - margin.top - margin.bottom,
+ pixelsOffHeight = 0,
+ svg;
+
+
+ function drawBars(availChartContext) {
+ var xAxisMin = $wnd.d3.min(availChartContext.data, function (d) {
+ return +d.availStart;
+ }),
+ xAxisMax = $wnd.d3.max(availChartContext.data, function (d) {
+ return +d.availEnd;
+ }),
+
+ timeScale = $wnd.d3.time.scale()
+ .range([0, width])
+ .domain([xAxisMin, xAxisMax]),
+
+ yScale = $wnd.d3.scale.linear()
+ .clamp(true)
+ .rangeRound([height, 0])
+ .domain([0, 4]),
+
+ xAxis = $wnd.d3.svg.axis()
+ .scale(timeScale)
+ .ticks(12)
+ .tickSize(10, 0, 0)
+ .orient("bottom"),
+
+ calcBarY = function(d) {
+ var ABOVE = -10,
+ BELOW = 0,
+ STRADDLE = -5,
+ offset;
+
+ if (d.availType === 'DOWN') {
+ offset = BELOW;
+ }
+ else if (d.availType === 'DISABLED') {
+ offset = STRADDLE;
+ }
+ else if (d.availType === 'UNKNOWN') {
+ offset = STRADDLE;
+ }
+ else if (d.availType === 'UP') {
+ offset = ABOVE;
+ }
+ else if (d.availType === 'WARN') {
+ offset = STRADDLE;
+ }
+ else if (d.availType === 'EMPTY') {
+ offset = STRADDLE;
+ }
+ return yScale(0) + offset;
+
+ },
+
+ calcBarFill = function(d) {
+ if (d.availType === 'DOWN') {
+ return "#FF1919"; // red
+ }
+ else if (d.availType === 'DISABLED') {
+ return "#FF9933"; // orange
+ }
+ else if (d.availType === 'UNKNOWN') {
+ return "#CCC"; // gray
+ }
+ else if (d.availType === 'UP') {
+ return "#198C19"; // green
+ }
+ else if (d.availType === 'WARN') {
+ return "#FFA500"; // yellow
+ }
+ else if (d.availType === 'EMPTY') {
+ return "#CCC"; // gray
+ }
+ else {
+ // should not ever happen, but...
+ console.warn("AvailabilityType not valid.");
+ return "#000"; //black
+ }
+ },
+ svg = $wnd.d3.select(availChartContext.chartSelection).append("g")
+ .attr("width", width + margin.left + margin.right)
+ .attr("height", height + margin.top + margin.bottom)
+ .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
+
+
+ svg.selectAll("rect.availBars")
+ .data(availChartContext.data)
+ .enter().append("rect")
+ .attr("class", "availBars")
+ .attr("x", function (d) {
+ return timeScale(+d.availStart);
+ })
+ .attr("y", function (d) {
+ return calcBarY(d);
+
+ })
+ .attr("height", function (d) {
+ return 10;
+
+ })
+ .attr("width", function (d) {
+ return timeScale(+d.availEnd) - timeScale(+d.availStart);
+ })
+ .attr("opacity", ".9")
+ .attr("fill", function (d) {
+ return calcBarFill(d);
+ });
+
+ // create x-axis
+ svg.append("g")
+ .attr("class", "x axis")
+ .attr("stroke", "#50505a")
+ .attr("stroke-width", "0.5")
+ .attr("transform", "translate(0," + height + ")")
+ .attr("letter-spacing", "3")
+ .style("text-anchor", "end")
+ .call(xAxis);
+
+ svg.append("text")
+ .attr("class", "availabilityLabel")
+ .attr("x", -40)
+ .attr("y", 10)
+ .style("font-size", "12px")
+ .style("font-family", "Arial, Verdana, sans-serif;")
+ .style("font-weight", "bold")
+ .attr("fill", "#003168")
+ .text("Availability");
+
+ svg.append("text")
+ .attr("class", "upLabel")
+ .attr("x", -5)
+ .attr("y", 28)
+ .style("font-family", "Arial, Verdana, sans-serif;")
+ .style("font-size", "9px")
+ .attr("fill", "#50505a")
+ .style("text-anchor", "end")
+ .text("UP");
+
+ svg.append("text")
+ .attr("class", "downLabel")
+ .attr("x", -5)
+ .attr("y", 39)
+ .style("font-family", "Arial, Verdana, sans-serif;")
+ .style("font-size", "9px")
+ .attr("fill", "#50505a")
+ .style("text-anchor", "end")
+ .text("DOWN");
+
+ }
+
+ function createHovers() {
+ $wnd.jQuery('svg rect.availBars').tipsy({
+ gravity: 's',
+ html: true,
+ trigger: 'hover',
+ title: function () {
+ var d = this.__data__;
+ return formatHovers(d);
+ },
+ show: function (e, el) {
+ el.css({ 'z-index': '990000'})
+ }
+ });
+ }
+
+ function formatHovers(d) {
+ var hoverString,
+ timeFormatter = $wnd.d3.time.format(availChartContext.chartHoverTimeFormat),
+ dateFormatter = $wnd.d3.time.format(availChartContext.chartHoverDateFormat),
+ availStart = new Date(+d.availStart),
+ availEnd = new Date(+d.availEnd);
+
+ hoverString =
+ '<div class="chartHoverEnclosingDiv">' +
+ '<div class="chartHoverAlignLeft"><span >' + availChartContext.hoverBarAvailabilityLabel + ': </span><span style="width:50px;">' + d.availTypeMessage + '</span></div>' +
+ '<div class="chartHoverAlignLeft"><span>'+ dateFormatter(availStart) + ' ' + timeFormatter(availStart) + '</span></div>' +
+ '<div class="chartHoverAlignLeft"><span >' + availChartContext.hoverBarLabel + ': </span><span style="width:50px;">' + d.availDuration + '</span></div>' +
+ '</div>';
+ return hoverString;
+
+ }
+
+ return {
+ // Public API
+ draw: function (chartContext) {
+ "use strict";
+ console.info("AvailabilityChart");
+ //console.time("availabilityChart");
+ drawBars(availChartContext);
+ createHovers();
+ //console.timeEnd("availabilityChart");
+ }
+ }; // end public closure
+
+
+ }();
+
+ if (availChartContext.data !== undefined && availChartContext.data.length > 0) {
+ availabilityGraph.draw(availChartContext);
+ }
+
+ }-*/;
+
+ public String getChartId() {
+ return String.valueOf(entityId);
+ }
+
+ public String getChartTimeLabel() {
+ return MSG.chart_time_label();
+ }
+
+ public String getChartDateLabel() {
+ return MSG.chart_date_label();
+ }
+
+ public String getChartHoverAvailabilityLabel() {
+ return MSG.chart_hover_availability_label();
+ }
+
+ public String getChartHoverStartLabel() {
+ return MSG.chart_hover_start_label();
+ }
+
+ public String getChartHoverEndLabel() {
+ return MSG.chart_hover_end_label();
+ }
+
+ public String getChartHoverBarLabel() {
+ return MSG.chart_hover_bar_label();
+ }
+
+ public String getChartHoverTimeFormat() {
+ return MSG.chart_hover_time_format();
+ }
+
+ public String getChartHoverDateFormat() {
+ return MSG.chart_hover_date_format();
+ }
+}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/StackedBarMetricGraphImpl.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/StackedBarMetricGraphImpl.java
index d9a4205..15f400d 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/StackedBarMetricGraphImpl.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/charttype/StackedBarMetricGraphImpl.java
@@ -234,8 +234,10 @@ public class StackedBarMetricGraphImpl extends AbstractGraph {
chart.append("g").append("rect")
.attr("class", "rightSidePanel")
.attr("x", xLabel - 10)
- .attr("y", margin.top + 60)
- .attr("height", 100)
+ .attr("y", margin.top + 70)
+ .attr("rx", 10)
+ .attr("ry", 10)
+ .attr("height", 80)
.attr("width", 135)
.attr("opacity", "0.3")
.attr("fill", "#E8E8E8");
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/D3GroupGraphListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/D3GroupGraphListView.java
index 786701b..7691c5f 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/D3GroupGraphListView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/D3GroupGraphListView.java
@@ -42,6 +42,7 @@ import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
import org.rhq.enterprise.gui.coregui.client.inventory.AutoRefresh;
import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractD3GraphListView;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityLineGraphType;
+import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.MetricGraphData;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.StackedBarMetricGraphImpl;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.MetricD3GraphView;
@@ -74,7 +75,7 @@ public final class D3GroupGraphListView extends AbstractD3GraphListView implemen
addMember(measurementRangeEditor);
if (showAvailabilityGraph) {
- availabilityGraph = new AvailabilityD3Graph(new AvailabilityLineGraphType(resourceGroup.getId()));
+ availabilityGraph = new AvailabilityD3Graph(new AvailabilityOverUnderGraphType(resourceGroup.getId()));
// first step in 2 step to create d3 chart
// create a placeholder for avail graph
availabilityGraph.createGraphMarker();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/D3GraphListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/D3GraphListView.java
index 26f3626..58d3050 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/D3GraphListView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/D3GraphListView.java
@@ -47,6 +47,7 @@ import org.rhq.enterprise.gui.coregui.client.components.measurement.UserPreferen
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractD3GraphListView;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityLineGraphType;
+import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.MetricGraphData;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.StackedBarMetricGraphImpl;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.avail.AvailabilityD3Graph;
@@ -130,7 +131,7 @@ public class D3GraphListView extends AbstractD3GraphListView {
addMember(measurementRangeEditor);
if (showAvailabilityGraph) {
- availabilityGraph = new AvailabilityD3Graph(new AvailabilityLineGraphType(resource.getId()));
+ availabilityGraph = new AvailabilityD3Graph(new AvailabilityOverUnderGraphType(resource.getId()));
// first step in 2 step to create d3 chart
// create a placeholder for avail graph
availabilityGraph.createGraphMarker();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java
index d03fefe..d06bab2 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/avail/AvailabilityD3Graph.java
@@ -26,6 +26,7 @@ import org.rhq.core.domain.measurement.Availability;
import org.rhq.core.domain.resource.group.composite.ResourceGroupAvailability;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityGraph;
import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityLineGraphType;
+import org.rhq.enterprise.gui.coregui.client.inventory.common.charttype.AvailabilityOverUnderGraphType;
import org.rhq.enterprise.gui.coregui.client.util.Log;
import org.rhq.enterprise.gui.coregui.client.util.enhanced.EnhancedVLayout;
@@ -37,12 +38,12 @@ import org.rhq.enterprise.gui.coregui.client.util.enhanced.EnhancedVLayout;
*/
public class AvailabilityD3Graph extends EnhancedVLayout implements AvailabilityGraph {
- protected AvailabilityLineGraphType availabilityGraphType;
+ protected AvailabilityOverUnderGraphType availabilityGraphType;
- public AvailabilityD3Graph(AvailabilityLineGraphType graphType) {
+ public AvailabilityD3Graph(AvailabilityOverUnderGraphType graphType) {
super();
this.availabilityGraphType = graphType;
- setHeight(25);
+ setHeight(70);
setWidth100();
}
@@ -82,7 +83,7 @@ public class AvailabilityD3Graph extends EnhancedVLayout implements Availability
StringBuilder divAndSvgDefs = new StringBuilder();
divAndSvgDefs.append("<div id=\"availChart-" + availabilityGraphType.getChartId()
- + "\" ><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style=\"height:20px;\">");
+ + "\" ><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" style=\"height:110px;\">");
divAndSvgDefs.append("</svg></div>");
HTMLFlow graph = new HTMLFlow(divAndSvgDefs.toString());
graph.setWidth100();
commit 85215f76e7ec578a7cad3a13e983c6cbffa0650f
Author: mtho11 <mikecthompson(a)gmail.com>
Date: Wed Apr 24 16:16:15 2013 -0700
Trivial: add *.DS_Store files to .gitignore
diff --git a/.gitignore b/.gitignore
index 92b2176..3bd9232 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,7 +12,6 @@ modules/enterprise/gui/coregui/build/classes/
modules/enterprise/gui/content_http-war/build/classes/
#created by rhq-enterprise-server's unit tests
modules/enterprise/server/jar/transaction.log
-
.idea/
.metadata/
*cache.html
@@ -27,6 +26,7 @@ modules/enterprise/server/jar/transaction.log
.*.jsfdia
.wtpmodules
*~
+*.DS_Store
#these are created by the python script engine during the tests
cachedir/
11 years, 1 month
[rhq] Branch 'feature/cassandra-backend' - 2 commits - modules/enterprise
by snegrea
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java | 2 ++
modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/migrator/DataMigratorRunner.java | 9 +++++++--
2 files changed, 9 insertions(+), 2 deletions(-)
New commits:
commit eb55bd2b67b1d071f4d8ff511890d8e0ca44b99e
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Tue May 7 16:24:49 2013 -0500
Add more default timeout properties to the list of properties used to unitialize the entity manager.
diff --git a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/migrator/DataMigratorRunner.java b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/migrator/DataMigratorRunner.java
index 620145a..b002099 100644
--- a/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/migrator/DataMigratorRunner.java
+++ b/modules/enterprise/server/server-metrics/src/main/java/org/rhq/server/metrics/migrator/DataMigratorRunner.java
@@ -71,8 +71,11 @@ import org.rhq.server.metrics.migrator.DataMigrator.DatabaseType;
@SuppressWarnings({ "static-access", "deprecation" })
public class DataMigratorRunner {
+ private static final int SQL_TIMEOUT = 40000;
+
private final Log log = LogFactory.getLog(DataMigratorRunner.class);
+
//Cassandra
private Option cassandraUserOption = OptionBuilder.withLongOpt("cassandra-user").hasArg().withType(String.class)
.withDescription("Cassandra user (default: rhqadmin)").create();
@@ -84,7 +87,7 @@ public class DataMigratorRunner {
private Option cassandraPortOption = OptionBuilder.withLongOpt("cassandra-port").hasArg().withType(Integer.class)
.withDescription("Cassandra native binary protocol port (default: 9142)").create();
private Option cassandraCompressionOption = OptionBuilder.withLongOpt("cassandra-compression").hasOptionalArg()
- .withType(String.class).withDescription("Enable compression for communication with Cassandra (default: true)")
+ .withType(Boolean.class).withDescription("Enable compression for communication with Cassandra (default: true)")
.create();
//SQL
@@ -574,9 +577,10 @@ public class DataMigratorRunner {
private EntityManager createEntityManager() throws Exception {
Properties properties = new Properties();
properties.put("javax.persistence.provider", "org.hibernate.ejb.HibernatePersistence");
- properties.put("javax.persistence.query.timeout", 400000);
properties.put("hibernate.connection.username", (String) configuration.get(sqlUserOption));
properties.put("hibernate.connection.password", (String) configuration.get(sqlPasswordOption));
+ properties.put("javax.persistence.query.timeout", SQL_TIMEOUT);
+ properties.put("hibernate.c3p0.timeout", SQL_TIMEOUT);
if ("oracle".equals(configuration.get(sqlServerType))) {
String driverClassName = "oracle.jdbc.driver.OracleDriver";
@@ -595,6 +599,7 @@ public class DataMigratorRunner {
properties.put("hibernate.connection.url", "jdbc:oracle:thin:@" + (String) configuration.get(sqlHostOption)
+ ":" + (String) configuration.get(sqlPortOption) + ":" + (String) configuration.get(sqlDBOption));
properties.put("hibernate.default_schema", (String) configuration.get(sqlDBOption));
+ properties.put("hibernate.connection.oracle.jdbc.ReadTimeout", SQL_TIMEOUT);
} else {
String driverClassName = "org.postgresql.Driver";
commit 9ec096003b8e944bc2183cbfa2835e3d8e1bc66c
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Tue May 7 16:17:15 2013 -0500
Default to normal operation mode for now to satisfy entity requirements.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
index 07c907f..5e2505e 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
@@ -41,6 +41,7 @@ import com.datastax.driver.core.SimpleAuthInfoProvider;
import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.util.ClusterBuilder;
import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.cloud.StorageNode.OperationMode;
import org.rhq.enterprise.server.cloud.StorageNodeManagerLocal;
import org.rhq.server.metrics.CQLException;
import org.rhq.server.metrics.MetricsConfiguration;
@@ -123,6 +124,7 @@ public class SessionManagerBean {
for (int i = 0; i < seeds.length; ++i) {
StorageNode discoveredStorageNode = new StorageNode();
discoveredStorageNode.parseNodeInformation(seeds[i]);
+ discoveredStorageNode.setOperationMode(OperationMode.NORMAL);
if (storageNodeMap.containsKey(discoveredStorageNode.getAddress())) {
StorageNode existingStorageNode = storageNodeMap.get(discoveredStorageNode.getAddress());
11 years, 1 month
[rhq] Branch 'feature/cassandra-backend' - modules/enterprise
by John Sanda
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
New commits:
commit fce897dc68d9d65a2ba9a2eacf43dd85ec8d9da0
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue May 7 14:24:43 2013 -0400
fixing ejb reference
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
index 474a51f..07c907f 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
@@ -41,7 +41,7 @@ import com.datastax.driver.core.SimpleAuthInfoProvider;
import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.util.ClusterBuilder;
import org.rhq.core.domain.cloud.StorageNode;
-import org.rhq.enterprise.server.cloud.StorageNodeManagerBean;
+import org.rhq.enterprise.server.cloud.StorageNodeManagerLocal;
import org.rhq.server.metrics.CQLException;
import org.rhq.server.metrics.MetricsConfiguration;
@@ -56,7 +56,7 @@ public class SessionManagerBean {
private MetricsConfiguration metricsConfiguration = new MetricsConfiguration();
@EJB
- private StorageNodeManagerBean storageNodeManager;
+ private StorageNodeManagerLocal storageNodeManager;
@PostConstruct
private void createSession() {
11 years, 1 month
[rhq] Branch 'feature/cassandra-backend' - modules/enterprise
by Jiri Kremser
modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBeanTest.java | 112 ++++++++++
modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/TopologyManagerBeanTest.java | 63 -----
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java | 17 +
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java | 49 ++++
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerBean.java | 7
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerLocal.java | 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java | 6
7 files changed, 183 insertions(+), 73 deletions(-)
New commits:
commit 32a8611d55bad1a62d34604e7d7905c472f2166f
Author: Jirka Kremser <jkremser(a)redhat.com>
Date: Tue May 7 14:35:13 2013 +0200
Adding local interface for StorageNodeManager, moving the criteria finder from TopologyManager to StorageNodeManager, following the same file structure for itests
diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBeanTest.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBeanTest.java
new file mode 100644
index 0000000..7418f71
--- /dev/null
+++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBeanTest.java
@@ -0,0 +1,112 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2013 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.enterprise.server.cloud;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.testng.annotations.Test;
+
+import org.rhq.core.domain.auth.Subject;
+import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.criteria.StorageNodeCriteria;
+import org.rhq.core.domain.util.PageList;
+import org.rhq.core.domain.util.PageOrdering;
+import org.rhq.enterprise.server.test.AbstractEJB3Test;
+import org.rhq.enterprise.server.test.TransactionCallback;
+import org.rhq.enterprise.server.util.LookupUtil;
+
+/**
+ * @author Jirka Kremser
+ */
+@Test
+public class StorageNodeManagerBeanTest extends AbstractEJB3Test {
+
+ private StorageNodeManagerLocal nodeManager;
+ private Subject overlord;
+
+ @Override
+ protected void beforeMethod() throws Exception {
+ nodeManager = LookupUtil.getStorageNodeManager();
+ overlord = LookupUtil.getSubjectManager().getOverlord();
+ }
+
+ @Test(groups = "integration.ejb3")
+ public void testStorageNodeCriteriaFinder() throws Exception {
+
+ final int storageNodeCount = 42;
+ executeInTransaction(new TransactionCallback() {
+
+ public void execute() throws Exception {
+ // verify that all storage nodes objects are actually parsed.
+ final Set<String> nodeAddresses = new HashSet<String>(storageNodeCount);
+
+ final String prefix = "storage_node";
+ StorageNode lastOne = null, firstOne = null;
+ for (int i = 0; i < storageNodeCount; i++) {
+ String address = prefix + String.format(" %03d", i + 1) + ".domain.com";
+ StorageNode node = new StorageNode();
+ node.setAddress(address);
+ node.setOperationMode(StorageNode.OperationMode.NORMAL);
+ node.setJmxPort(7299 + i);
+ node.setCqlPort(9142 + i);
+ if (i == 0) {
+ firstOne = node;
+ } else if (i == storageNodeCount - 1) {
+ lastOne = node;
+ }
+
+ em.persist(node);
+ nodeAddresses.add(address);
+ em.flush();
+ }
+ em.flush();
+
+ assertTrue("The number of created storage nodes should be " + storageNodeCount + ". Was: "
+ + nodeAddresses.size(), storageNodeCount == nodeAddresses.size());
+
+ StorageNodeCriteria criteria = new StorageNodeCriteria();
+ criteria.addFilterAddress(prefix);
+ criteria.addSortAddress(PageOrdering.DESC); // use DESC just to make sure sorting on name is different than insert order
+ PageList<StorageNode> list = nodeManager.findStorageNodesByCriteria(overlord, criteria);
+
+ assertTrue("The number of found storage nodes should be " + storageNodeCount + ". Was: " + list.size(),
+ storageNodeCount == list.size());
+
+ assertTrue("The first storage node [" + firstOne + "] should be same as the last one in the list [ "
+ + list.get(list.size() - 1) + "]", firstOne.equals(list.get(list.size() - 1)));
+
+ assertTrue("The last storage node [" + lastOne + "] should be same as the first one in the list [ "
+ + list.get(0) + "]", lastOne.equals(list.get(0)));
+
+ String prevAddress = null;
+ for (StorageNode s : list) {
+ assert null == prevAddress || s.getAddress().compareTo(prevAddress) < 0 : "Results should be sorted by address DESC, something is out of order";
+ prevAddress = s.getAddress();
+ nodeAddresses.remove(s.getAddress());
+ }
+
+ // test that entire list was parsed
+ assertTrue("Expected resourceNames to be empty. Still " + nodeAddresses.size() + " name(s).",
+ nodeAddresses.size() == 0);
+ }
+ });
+ }
+}
diff --git a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/TopologyManagerBeanTest.java b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/TopologyManagerBeanTest.java
index f091e8d..2d8a193 100644
--- a/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/TopologyManagerBeanTest.java
+++ b/modules/enterprise/server/itests-2/src/test/java/org/rhq/enterprise/server/cloud/TopologyManagerBeanTest.java
@@ -548,67 +548,4 @@ public class TopologyManagerBeanTest extends AbstractEJB3Test {
}
});
}
-
-
- @Test(groups = "integration.ejb3")
- public void testStorageNodeCriteriaFinder() throws Exception {
-
- final int storageNodeCount = 42;
- executeInTransaction(new TransactionCallback() {
-
- public void execute() throws Exception {
- // verify that all storage nodes objects are actually parsed.
- final Set<String> nodeAddresses = new HashSet<String>(storageNodeCount);
-
- final String prefix = "storage_node";
- StorageNode lastOne = null, firstOne = null;
- for (int i = 0; i < storageNodeCount; i++) {
- String address = prefix + String.format(" %03d", i + 1) + ".domain.com";
- StorageNode node = new StorageNode();
- node.setAddress(address);
- node.setOperationMode(StorageNode.OperationMode.NORMAL);
- node.setJmxPort(7299 + i);
- node.setCqlPort(9142 + i);
- if(i == 0) {
- firstOne = node;
- } else if (i == storageNodeCount - 1) {
- lastOne = node;
- }
-
- em.persist(node);
- nodeAddresses.add(address);
- em.flush();
- }
- em.flush();
-
- assertTrue("The number of created storage nodes should be " + storageNodeCount + ". Was: " + nodeAddresses.size(),
- storageNodeCount == nodeAddresses.size());
-
- StorageNodeCriteria criteria = new StorageNodeCriteria();
- criteria.addFilterAddress(prefix);
- criteria.addSortAddress(PageOrdering.DESC); // use DESC just to make sure sorting on name is different than insert order
- PageList<StorageNode> list = topologyManager.findStorageNodesByCriteria(overlord, criteria);
-
- assertTrue("The number of found storage nodes should be " + storageNodeCount + ". Was: " + list.size(),
- storageNodeCount == list.size());
-
- assertTrue("The first storage node [" + firstOne + "] should be same as the last one in the list [ " + list.get(list.size() - 1) + "]",
- firstOne.equals(list.get(list.size() - 1)));
-
- assertTrue("The last storage node [" + lastOne + "] should be same as the first one in the list [ " + list.get(0) + "]",
- lastOne.equals(list.get(0)));
-
- String prevAddress = null;
- for (StorageNode s : list) {
- assert null == prevAddress || s.getAddress().compareTo(prevAddress) < 0 : "Results should be sorted by address DESC, something is out of order";
- prevAddress = s.getAddress();
- nodeAddresses.remove(s.getAddress());
- }
-
- // test that entire list was parsed
- assertTrue("Expected resourceNames to be empty. Still " + nodeAddresses.size() + " name(s).",
- nodeAddresses.size() == 0);
- }
- });
- }
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
index caaa182..5b2479a 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
@@ -34,11 +34,18 @@ import javax.persistence.Query;
import org.jetbrains.annotations.Nullable;
+import org.rhq.core.domain.auth.Subject;
+import org.rhq.core.domain.authz.Permission;
import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.criteria.StorageNodeCriteria;
+import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.server.RHQConstants;
+import org.rhq.enterprise.server.authz.RequiredPermission;
+import org.rhq.enterprise.server.util.CriteriaQueryGenerator;
+import org.rhq.enterprise.server.util.CriteriaQueryRunner;
@Stateless
-public class StorageNodeManagerBean {
+public class StorageNodeManagerBean implements StorageNodeManagerLocal {
@PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME)
private EntityManager entityManager;
@@ -55,4 +62,12 @@ public class StorageNodeManagerBean {
entityManager.persist(storageNode);
}
}
+
+ @RequiredPermission(Permission.MANAGE_SETTINGS)
+ public PageList<StorageNode> findStorageNodesByCriteria(Subject subject, StorageNodeCriteria criteria) {
+ CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria);
+ CriteriaQueryRunner<StorageNode> runner = new CriteriaQueryRunner<StorageNode>(criteria, generator,
+ entityManager);
+ return runner.execute();
+ }
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java
new file mode 100644
index 0000000..e13bc22
--- /dev/null
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java
@@ -0,0 +1,49 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.enterprise.server.cloud;
+
+import java.util.Collection;
+import java.util.List;
+
+import javax.ejb.Local;
+
+import org.rhq.core.domain.auth.Subject;
+import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.criteria.StorageNodeCriteria;
+import org.rhq.core.domain.util.PageList;
+
+@Local
+public interface StorageNodeManagerLocal {
+
+
+ List<StorageNode> getStorageNodes();
+
+ void updateStorageNodeList(Collection<StorageNode> storageNodes);
+
+ /**
+ * Fetches the list of StorageNode entities based on provided criteria.
+ *
+ * the subject needs to have MANAGE_SETTINGS permissions.
+ *
+ * @param subject caller
+ * @param criteria the criteria
+ * @return list of nodes
+ */
+ PageList<StorageNode> findStorageNodesByCriteria(Subject subject, StorageNodeCriteria criteria);
+}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerBean.java
index faa44d7..98aa9e6 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerBean.java
@@ -315,11 +315,4 @@ public class TopologyManagerBean implements TopologyManagerLocal {
CriteriaQueryRunner<Server> runner = new CriteriaQueryRunner<Server>(criteria, generator, entityManager);
return runner.execute();
}
-
- @RequiredPermission(Permission.MANAGE_SETTINGS)
- public PageList<StorageNode> findStorageNodesByCriteria(Subject subject, StorageNodeCriteria criteria) {
- CriteriaQueryGenerator generator = new CriteriaQueryGenerator(subject, criteria);
- CriteriaQueryRunner<StorageNode> runner = new CriteriaQueryRunner<StorageNode>(criteria, generator, entityManager);
- return runner.execute();
- }
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerLocal.java
index 3d66d30..7d5f76a 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/TopologyManagerLocal.java
@@ -154,6 +154,4 @@ public interface TopologyManagerLocal {
* @return list of servers
*/
PageList<Server> findServersByCriteria(Subject subject, ServerCriteria criteria);
-
- PageList<StorageNode> findStorageNodesByCriteria(Subject subject, StorageNodeCriteria criteria);
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java
index 46d9333..7b60e13 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/util/LookupUtil.java
@@ -68,6 +68,8 @@ import org.rhq.enterprise.server.cloud.PartitionEventManagerBean;
import org.rhq.enterprise.server.cloud.PartitionEventManagerLocal;
import org.rhq.enterprise.server.cloud.StatusManagerBean;
import org.rhq.enterprise.server.cloud.StatusManagerLocal;
+import org.rhq.enterprise.server.cloud.StorageNodeManagerBean;
+import org.rhq.enterprise.server.cloud.StorageNodeManagerLocal;
import org.rhq.enterprise.server.cloud.TopologyManagerBean;
import org.rhq.enterprise.server.cloud.TopologyManagerLocal;
import org.rhq.enterprise.server.cloud.instance.CacheConsistencyManagerBean;
@@ -480,6 +482,10 @@ public final class LookupUtil {
public static TopologyManagerLocal getTopologyManager() {
return lookupLocal(TopologyManagerBean.class);
}
+
+ public static StorageNodeManagerLocal getStorageNodeManager() {
+ return lookupLocal(StorageNodeManagerBean.class);
+ }
public static ClusterManagerLocal getClusterManager() {
return lookupLocal(ClusterManagerBean.class);
11 years, 1 month
[rhq] modules/plugins
by Thomas Segismont
modules/plugins/jboss-as-7/pom.xml | 1
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 16 ++
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/DeploymentTest.java | 74 ++++++++++
3 files changed, 91 insertions(+)
New commits:
commit f875212be4a8cfaf0905e2fd376a579197b83148
Author: Thomas Segismont <tsegismo(a)redhat.com>
Date: Tue May 7 14:25:34 2013 +0200
Bug 865629 - (PRODMGT-245) Add more metrics to AS7 plugin
Added missing metrics
Added integration test
diff --git a/modules/plugins/jboss-as-7/pom.xml b/modules/plugins/jboss-as-7/pom.xml
index cfe756d..5f538b7 100644
--- a/modules/plugins/jboss-as-7/pom.xml
+++ b/modules/plugins/jboss-as-7/pom.xml
@@ -615,6 +615,7 @@
<include>org/rhq/modules/plugins/jbossas7/itest/**/*Test.java</include>
<!--<include>org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java</include>-->
<!--<include>org/rhq/modules/plugins/jbossas7/itest/standalone/InterruptibleOperationsTest.java</include>-->
+ <!--<include>org/rhq/modules/plugins/jbossas7/itest/standalone/DeploymentTest.java</include>-->
<!--<include>org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java</include>-->
<!--<include>org/rhq/modules/plugins/jbossas7/itest/domain/SecurityModuleOptionsTest.java</include>-->
<!--<include>org/rhq/modules/plugins/jbossas7/itest/nonpc/ManagementConnectionPersistenceTest.java</include>-->
diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
index 45f4e05..742c4d5 100644
--- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
@@ -8864,6 +8864,22 @@
<metric property="responseTime"
dataType="calltime" defaultOn="false" units="milliseconds" destinationType="URL"
description="the minimum, maximum, and average response times for requests serviced by this webapp"/>
+ <metric property="active-sessions" displayName="Currently Active Sessions"
+ description="The number of sessions that are currently active"/>
+ <metric property="duplicated-session-ids" displayName="Duplicated Session Ids"
+ description="The number of duplicated session identifiers"/>
+ <metric property="expired-sessions" measurementType="trendsup" displayName="Expired Sessions"
+ description="The number of expired sessions"/>
+ <metric property="max-active-sessions" displayName="Maximum Active Sessions"
+ description="The maximum number of sessions that have been active"/>
+ <metric property="rejected-sessions" measurementType="trendsup" displayName="Rejected Sessions"
+ description="The number of sessions rejected"/>
+ <metric property="session-avg-alive-time" units="milliseconds" displayName="Average Session Alive Time"
+ description="The average alive time of sessions"/>
+ <metric property="session-max-alive-time" units="milliseconds" displayName="Max Session Alive Time"
+ description="The maximum alive time of sessions"/>
+ <metric property="sessions-created" measurementType="trendsup" displayName="Created Sessions"
+ description="The number of sessions created"/>
</service>
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/DeploymentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/DeploymentTest.java
index 6f84e34..5b552bc 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/DeploymentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/DeploymentTest.java
@@ -19,6 +19,11 @@
package org.rhq.modules.plugins.jbossas7.itest.standalone;
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.rhq.core.domain.util.ResourceTypeUtility.getMeasurementDefinitions;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -27,6 +32,8 @@ import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashSet;
import java.util.Set;
import org.mockito.Mockito;
@@ -47,8 +54,18 @@ import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.domain.content.PackageDetailsKey;
import org.rhq.core.domain.content.transfer.DeployPackagesResponse;
import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
+import org.rhq.core.domain.measurement.DataType;
+import org.rhq.core.domain.measurement.MeasurementDataNumeric;
+import org.rhq.core.domain.measurement.MeasurementDataTrait;
+import org.rhq.core.domain.measurement.MeasurementDefinition;
+import org.rhq.core.domain.measurement.MeasurementReport;
+import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
import org.rhq.core.domain.resource.CreateResourceStatus;
import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.util.MeasurementDefinitionFilter;
+import org.rhq.core.pc.inventory.ResourceContainer;
+import org.rhq.core.pc.util.FacetLockType;
+import org.rhq.core.pluginapi.measurement.MeasurementFacet;
import org.rhq.modules.plugins.jbossas7.StandaloneASComponent;
import org.rhq.modules.plugins.jbossas7.itest.AbstractJBossAS7PluginTest;
import org.rhq.test.arquillian.DiscoveredResources;
@@ -101,6 +118,9 @@ public class DeploymentTest extends AbstractJBossAS7PluginTest {
@DiscoveredResources(plugin = PLUGIN_NAME, resourceType = "Deployment")
private Set<Resource> deploymentResources;
+ @DiscoveredResources(plugin = PLUGIN_NAME, resourceType = "Web Runtime")
+ private Set<Resource> webRuntimeResources;
+
private static TestDeployments DEPLOYMENT_TO_SERVE = TestDeployments.DEPLOYMENT_1;
private static long copyStreamAndReturnCount(InputStream in, OutputStream out) throws IOException {
@@ -242,6 +262,60 @@ public class DeploymentTest extends AbstractJBossAS7PluginTest {
}
@Test(priority = 15)
+ @RunDiscovery
+ public void testWebRuntimeMetricsHaveNonNullValues() throws Exception {
+ assertTrue(webRuntimeResources != null && !webRuntimeResources.isEmpty(),
+ "Web Runtime resource should have been discovered");
+ assertEquals(webRuntimeResources.size(), 1, "Found more than one Web Runtime resource: " + webRuntimeResources);
+
+ Resource webRuntimeResource = webRuntimeResources.iterator().next();
+ ResourceContainer webRuntimeResourceContainer = pluginContainer.getInventoryManager().getResourceContainer(
+ webRuntimeResource);
+ MeasurementFacet measurementFacet = webRuntimeResourceContainer.createResourceComponentProxy(
+ MeasurementFacet.class, FacetLockType.READ, SECONDS.toMillis(5), false, false);
+ MeasurementReport report = new MeasurementReport();
+ Set<MeasurementScheduleRequest> measurementScheduleRequests = getMeasurementScheduleRequests(webRuntimeResource);
+ measurementFacet.getValues(report, measurementScheduleRequests);
+ assertEquals(report.getCallTimeData().size(), 0, "No calltime data was requested");
+ assertTrue(
+ report.getNumericData().size() + report.getTraitData().size() == measurementScheduleRequests.size(),
+ "Some requested measurements are missing: "
+ + getMissingMeasurements(measurementScheduleRequests, report.getNumericData(), report.getTraitData()));
+ }
+
+ private Set<String> getMissingMeasurements(Set<MeasurementScheduleRequest> measurementScheduleRequests,
+ Set<MeasurementDataNumeric> numericData, Set<MeasurementDataTrait> traitData) {
+ Set<String> missingMeasurements = new HashSet<String>();
+ for (MeasurementScheduleRequest measurementScheduleRequest : measurementScheduleRequests) {
+ missingMeasurements.add(measurementScheduleRequest.getName());
+ }
+ for (MeasurementDataNumeric measurementDataNumeric : numericData) {
+ missingMeasurements.remove(measurementDataNumeric.getName());
+ }
+ for (MeasurementDataTrait measurementDataTrait : traitData) {
+ missingMeasurements.remove(measurementDataTrait.getName());
+ }
+ return missingMeasurements;
+ }
+
+ private Set<MeasurementScheduleRequest> getMeasurementScheduleRequests(Resource webRuntimeResource) {
+ Set<MeasurementDefinition> measurementDefinitions = getMeasurementDefinitions(
+ webRuntimeResource.getResourceType(), new MeasurementDefinitionFilter() {
+ private final Set<DataType> acceptableDataTypes = EnumSet.of(DataType.MEASUREMENT, DataType.TRAIT);
+
+ public boolean accept(MeasurementDefinition measurementDefinition) {
+ return acceptableDataTypes.contains(measurementDefinition.getDataType());
+ }
+ });
+ Set<MeasurementScheduleRequest> measurementScheduleRequests = new HashSet<MeasurementScheduleRequest>();
+ for (MeasurementDefinition measurementDefinition : measurementDefinitions) {
+ measurementScheduleRequests.add(new MeasurementScheduleRequest(-1, measurementDefinition.getName(), -1,
+ true, measurementDefinition.getDataType(), measurementDefinition.getRawNumericType()));
+ }
+ return measurementScheduleRequests;
+ }
+
+ @Test(priority = 16)
public void testUndeploy() throws Exception {
Resource deployment = deploymentResources.iterator().next();
DeleteResourceRequest request = new DeleteResourceRequest(0, deployment.getId());
11 years, 1 month
[rhq] Branch 'feature/cassandra-backend' - .classpath modules/common modules/core modules/enterprise
by snegrea
.classpath | 1
modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java | 8 -
modules/common/pom.xml | 3
modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java | 19 ++-
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java | 51 ++++++++
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java | 58 ++++++++++
6 files changed, 131 insertions(+), 9 deletions(-)
New commits:
commit b0ea13c410d3d345c4626428331490fe3aaf6f73
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Mon May 6 23:42:09 2013 -0500
First attempt to populate storage node entities.
diff --git a/.classpath b/.classpath
index cc7cab4..2e6f36f 100644
--- a/.classpath
+++ b/.classpath
@@ -213,6 +213,7 @@
<classpathentry kind="src" path="modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java"/>
<classpathentry kind="src" path="modules/common/cassandra-ccm/cassandra-ccm-testng/src/main/java"/>
<classpathentry kind="src" path="modules/common/cassandra-ccm/cassandra-ccm-testng/src/test/java"/>
+ <classpathentry kind="src" path="modules/common/cassandra-jmx/src/main/java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry exported="true" kind="var" path="M2_REPO/org/apache/httpcomponents/httpclient/4.2.3/httpclient-4.2.3.jar" sourcepath="M2_REPO/org/apache/httpcomponents/httpclient/4.2.3/httpclient-4.2.3-sources.jar"/>
<classpathentry exported="true" kind="var" path="M2_REPO/org/apache/httpcomponents/httpcore/4.2.2/httpcore-4.2.2.jar" sourcepath="M2_REPO/org/apache/httpcomponents/httpcore/4.2.2/httpcore-4.2.2-sources.jar"/>
diff --git a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java
index ca41db1..88b4a65 100644
--- a/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java
+++ b/modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraNode.java
@@ -37,7 +37,6 @@ import javax.naming.Context;
import org.rhq.cassandra.installer.RMIContextFactory;
-
/**
* @author John Sanda
* @author Jirka Kremser
@@ -49,7 +48,7 @@ public class CassandraNode {
private int jmxPort;
private int nativeTransportPort;
-
+
private static final String JMX_CONNECTION_STRING = "service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi";
public CassandraNode(String hostName, int jmxPort, int nativeTransportPort) {
@@ -69,7 +68,7 @@ public class CassandraNode {
public int getNativeTransportPort() {
return nativeTransportPort;
}
-
+
public boolean isNativeTransportRunning() throws Exception {
Boolean nativeTransportRunning = false;
String url = String.format(JMX_CONNECTION_STRING, getHostName(), getJmxPort());
@@ -125,7 +124,8 @@ public class CassandraNode {
public static CassandraNode parseNode(String s) {
String[] params = s.split("\\|");
if (params.length != 3) {
- throw new IllegalArgumentException("Expected string of the form, hostname|jmxPort|nativeTransportPort");
+ throw new IllegalArgumentException(
+ "Expected string of the form, hostname|jmxPort|nativeTransportPort but got: " + s);
}
return new CassandraNode(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]));
}
diff --git a/modules/common/pom.xml b/modules/common/pom.xml
index 7d0cf1c..5f0b85d 100644
--- a/modules/common/pom.xml
+++ b/modules/common/pom.xml
@@ -28,9 +28,10 @@
<module>jboss-as</module>
<module>filetemplate-bundle</module>
<module>ant-bundle</module>
- <module>drift</module>
+ <module>drift</module>
<module>jboss-as-dmr-client</module>
<module>cassandra-util</module>
+ <module>cassandra-jmx</module>
<module>cassandra-schema</module>
<module>cassandra-ccm</module>
<module>cassandra-installer</module>
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
index 79b3ece..4a29838 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java
@@ -44,7 +44,7 @@ import org.rhq.core.domain.resource.Resource;
/**
* An RHQ Storage Node (Cassandra)
- *
+ *
* @author Jay Shaughnessy
*/
@Entity(name = "StorageNode")
@@ -221,9 +221,9 @@ public class StorageNode implements Serializable {
final StorageNode other = (StorageNode) obj;
- if (ctime != other.ctime) {
- return false;
- }
+ //if (ctime != other.ctime) {
+ // return false;
+ //}
if (address == null) {
if (other.address != null) {
@@ -236,4 +236,15 @@ public class StorageNode implements Serializable {
return true;
}
+ public void parseNodeInformation(String s) {
+ String[] params = s.split("\\|");
+ if (params.length != 3) {
+ throw new IllegalArgumentException("Expected string of the form, hostname|jmxPort|nativeTransportPort");
+ }
+
+ this.setAddress(params[0]);
+ this.setJmxPort(Integer.parseInt(params[1]));
+ this.setCqlPort(Integer.parseInt(params[2]));
+ }
+
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
index 3dbe0bf..474a51f 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cassandra/SessionManagerBean.java
@@ -25,7 +25,13 @@
package org.rhq.enterprise.server.cassandra;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import javax.annotation.PostConstruct;
+import javax.ejb.EJB;
import javax.ejb.Singleton;
import com.datastax.driver.core.Cluster;
@@ -34,6 +40,8 @@ import com.datastax.driver.core.SimpleAuthInfoProvider;
import org.rhq.cassandra.CassandraNode;
import org.rhq.cassandra.util.ClusterBuilder;
+import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.enterprise.server.cloud.StorageNodeManagerBean;
import org.rhq.server.metrics.CQLException;
import org.rhq.server.metrics.MetricsConfiguration;
@@ -47,9 +55,14 @@ public class SessionManagerBean {
private MetricsConfiguration metricsConfiguration = new MetricsConfiguration();
+ @EJB
+ private StorageNodeManagerBean storageNodeManager;
+
@PostConstruct
private void createSession() {
try {
+ this.createStorageNodeEntities();
+
String username = System.getProperty("rhq.cassandra.username");
if (username == null) {
throw new CQLException("The rhq.cassandra.username property is null. Cannot create session.");
@@ -89,6 +102,44 @@ public class SessionManagerBean {
}
}
+ private void createStorageNodeEntities() {
+ try {
+ String seedProp = System.getProperty("rhq.cassandra.seeds");
+ if (seedProp == null) {
+ throw new CQLException("The rhq.cassandra.seeds property is null. Cannot create session.");
+ }
+
+ List<StorageNode> storageNodes = storageNodeManager.getStorageNodes();
+ if (storageNodes == null) {
+ storageNodes = new ArrayList<StorageNode>();
+ }
+
+ Map<String, StorageNode> storageNodeMap = new HashMap<String, StorageNode>();
+ for (StorageNode storageNode : storageNodes) {
+ storageNodeMap.put(storageNode.getAddress(), storageNode);
+ }
+
+ String[] seeds = seedProp.split(",");
+ for (int i = 0; i < seeds.length; ++i) {
+ StorageNode discoveredStorageNode = new StorageNode();
+ discoveredStorageNode.parseNodeInformation(seeds[i]);
+
+ if (storageNodeMap.containsKey(discoveredStorageNode.getAddress())) {
+ StorageNode existingStorageNode = storageNodeMap.get(discoveredStorageNode.getAddress());
+ existingStorageNode.setJmxPort(discoveredStorageNode.getJmxPort());
+ existingStorageNode.setCqlPort(discoveredStorageNode.getCqlPort());
+ }
+ else {
+ storageNodeMap.put(discoveredStorageNode.getAddress(), discoveredStorageNode);
+ }
+ }
+
+ storageNodeManager.updateStorageNodeList(storageNodeMap.values());
+ } catch (Exception e) {
+ throw new CQLException("Unable to create session", e);
+ }
+ }
+
public Session getSession() {
return session;
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
new file mode 100644
index 0000000..caaa182
--- /dev/null
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java
@@ -0,0 +1,58 @@
+/*
+ *
+ * RHQ Management Platform
+ * Copyright (C) 2005-2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, version 2, as
+ * published by the Free Software Foundation, and/or the GNU Lesser
+ * General Public License, version 2.1, also as published by the Free
+ * Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License and the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * and the GNU Lesser General Public License along with this program;
+ * if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ */
+package org.rhq.enterprise.server.cloud;
+
+import java.util.Collection;
+import java.util.List;
+
+import javax.ejb.Stateless;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.jetbrains.annotations.Nullable;
+
+import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.enterprise.server.RHQConstants;
+
+@Stateless
+public class StorageNodeManagerBean {
+
+ @PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME)
+ private EntityManager entityManager;
+
+ @SuppressWarnings("unchecked")
+ @Nullable
+ public List<StorageNode> getStorageNodes() {
+ Query query = entityManager.createNamedQuery(StorageNode.QUERY_FIND_ALL);
+ return (List<StorageNode>) query.getResultList();
+ }
+
+ public void updateStorageNodeList(Collection<StorageNode> storageNodes) {
+ for (StorageNode storageNode : storageNodes) {
+ entityManager.persist(storageNode);
+ }
+ }
+}
11 years, 1 month
[rhq] modules/enterprise
by mazz
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java | 2 -
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypePluginTreeDataSource.java | 16 +---------
2 files changed, 2 insertions(+), 16 deletions(-)
New commits:
commit e589245b50710f5487ce3efcd527f73c02df8ea3
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Mon May 6 19:02:55 2013 -0400
BZ 817825 don't show "Loading..." for leaf nodes in resource type drop down menus
this still doesn't fix the Platform plugin's platform type submenus.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java
index e2650e4..90511d7 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/selection/ResourceSelector.java
@@ -77,8 +77,6 @@ public class ResourceSelector extends AbstractSelector<Resource, ResourceCriteri
typeSelectItem.setValueField("id");
typeSelectItem.setCanSelectParentItems(true);
typeSelectItem.setLoadDataOnDemand(false);
- typeSelectItem.setEmptyMenuMessage(MSG.common_msg_loading());
- typeSelectItem.setShowIcons(false);
if (this.forceResourceTypeFilter) {
typeSelectItem.setDisabled(true);
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypePluginTreeDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypePluginTreeDataSource.java
index 136db95..c1c9e66 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypePluginTreeDataSource.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/type/ResourceTypePluginTreeDataSource.java
@@ -19,8 +19,6 @@
package org.rhq.enterprise.gui.coregui.client.inventory.resource.type;
import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
import java.util.HashMap;
import com.google.gwt.user.client.rpc.AsyncCallback;
@@ -144,12 +142,6 @@ public class ResourceTypePluginTreeDataSource extends DataSource {
}
}
- Collections.sort(nodes, new Comparator<TreeNode>() {
- public int compare(TreeNode o1, TreeNode o2) {
- return o1.getName().compareTo(o2.getName());
- }
- });
-
TreeNode[] treeNodes = nodes.toArray(new TreeNode[nodes.size()]);
return treeNodes;
}
@@ -198,9 +190,8 @@ public class ResourceTypePluginTreeDataSource extends DataSource {
setParentID(null);
setAttribute("name", pluginName + " " + pluginStr);
- // setAttribute("plugin",pluginName);
- setIcon("types/plugin_16.png"); // todo doesn't work
setEnabled(true);
+ // setIcon(IconEnum.PLUGIN.getIcon16x16Path()); // IPickTreeItem doesn't appear to want to use this
}
@Override
@@ -245,10 +236,7 @@ public class ResourceTypePluginTreeDataSource extends DataSource {
setAttribute("name", resourceType.getName());
setAttribute("plugin", resourceType.getPlugin());
setAttribute("category", resourceType.getCategory().getDisplayName());
-
- setIcon("types/" + resourceType.getCategory().getDisplayName() + "_up_16.png");
-
- setIsFolder(true);
+ // setIcon(ImageManager.getResourceIcon(resourceType.getCategory())); // IPickTreeItem doesn't appear to want to use this
}
public ResourceType getResourceType() {
11 years, 1 month