[rhq] modules/core modules/enterprise modules/plugins
by snegrea
modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNode.java | 2
modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNodeConfigurationComposite.java | 98 ++++++++
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerBean.java | 113 ++++++++++
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerLocal.java | 5
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerRemote.java | 5
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/StorageNodeMaintenanceJob.java | 3
modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java | 16 +
modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml | 13 +
8 files changed, 246 insertions(+), 9 deletions(-)
New commits:
commit 11b8ae9cff9ca5085bfe317a01653cc8b81d8bb7
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Wed Jul 17 14:14:02 2013 -0500
Initial implementation for the Storage Node configuration composite. The final resource operation still needs to be implemented but the rest of the functionality is implemented.
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 14043db..575edc74 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
@@ -90,7 +90,7 @@ public class StorageNode implements Serializable {
public static final long serialVersionUID = 1L;
public static final String QUERY_FIND_ALL = "StorageNode.findAll";
- public static final String QUERY_FIND_BY_ADDRESS = "StorageNode.findByName";
+ public static final String QUERY_FIND_BY_ADDRESS = "StorageNode.findByAddress";
public static final String QUERY_FIND_ALL_NOT_INSTALLED = "StorageNode.findAllCloudMembers";
public static final String QUERY_DELETE_BY_ID = "StorageNode.deleteById";
public static final String QUERY_FIND_ALL_NORMAL = "StorageNode.findAllNormalCloudMembers";
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNodeConfigurationComposite.java b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNodeConfigurationComposite.java
new file mode 100644
index 0000000..e2c64f9
--- /dev/null
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/cloud/StorageNodeConfigurationComposite.java
@@ -0,0 +1,98 @@
+/*
+ * 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, 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.core.domain.cloud;
+
+import java.io.Serializable;
+
+/**
+ * @author Stefan Negrea
+ */
+public class StorageNodeConfigurationComposite implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private StorageNode storageNode;
+ private int jmxPort;
+ private String heapSize;
+
+ public StorageNodeConfigurationComposite() {
+ // GWT needs this
+ }
+
+ public StorageNodeConfigurationComposite(StorageNode storageNode) {
+ this.storageNode = storageNode;
+ }
+
+ /**
+ * @return associated storage node
+ */
+ public StorageNode getStorageNode() {
+ return storageNode;
+ }
+
+ /**
+ * @param storageNode storage node
+ */
+ protected void setStorageNode(StorageNode storageNode) {
+ this.storageNode = storageNode;
+ }
+
+
+ /**
+ * @return the JMX port
+ */
+ public int getJmxPort() {
+ return jmxPort;
+ }
+
+ /**
+ * @param jmxPort JMX port to set
+ */
+ public void setJmxPort(int jmxPort) {
+ this.jmxPort = jmxPort;
+ }
+
+ /**
+ * @return the heap size
+ */
+ public String getHeapSize() {
+ return heapSize;
+ }
+
+ /**
+ * @param heapSize heap size to set
+ */
+ public void setHeapSize(String heapSize) {
+ this.heapSize = heapSize;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append("storageNode.addresss=").append(storageNode.getAddress()).append(", ");
+ builder.append("heapSize=").append(heapSize).append(", ");
+ builder.append("jmxPort=").append(jmxPort).append("");
+ return builder.toString();
+ }
+}
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 fa51fe1..3f1ec69 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
@@ -51,14 +51,18 @@ import org.rhq.core.domain.authz.Permission;
import org.rhq.core.domain.cloud.Server;
import org.rhq.core.domain.cloud.StorageNode;
import org.rhq.core.domain.cloud.StorageNode.OperationMode;
+import org.rhq.core.domain.cloud.StorageNodeConfigurationComposite;
import org.rhq.core.domain.cloud.StorageNodeLoadComposite;
import org.rhq.core.domain.common.JobTrigger;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.criteria.AlertCriteria;
import org.rhq.core.domain.criteria.ResourceGroupCriteria;
+import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria;
import org.rhq.core.domain.criteria.StorageNodeCriteria;
import org.rhq.core.domain.measurement.MeasurementAggregate;
import org.rhq.core.domain.measurement.MeasurementUnits;
+import org.rhq.core.domain.operation.OperationRequestStatus;
+import org.rhq.core.domain.operation.ResourceOperationHistory;
import org.rhq.core.domain.operation.bean.GroupOperationSchedule;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
@@ -72,6 +76,7 @@ import org.rhq.enterprise.server.auth.SubjectManagerLocal;
import org.rhq.enterprise.server.authz.RequiredPermission;
import org.rhq.enterprise.server.authz.RequiredPermissions;
import org.rhq.enterprise.server.cloud.instance.ServerManagerLocal;
+import org.rhq.enterprise.server.configuration.ConfigurationManagerLocal;
import org.rhq.enterprise.server.measurement.MeasurementDataManagerLocal;
import org.rhq.enterprise.server.operation.OperationManagerLocal;
import org.rhq.enterprise.server.resource.ResourceTypeManagerLocal;
@@ -96,6 +101,11 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
private static final String RHQ_STORAGE_JMX_PORT_PROPERTY = "jmxPort";
private static final String RHQ_STORAGE_ADDRESS_PROPERTY = "host";
+ private static final int OPERATION_QUERY_TIMEOUT = 1000;
+ private static final int MAX_ITERATIONS = 5;
+ private static final String UPDATE_CONFIGURATION_OPERATION = "updateConfiguration";
+ private static final String RESTART_OPERATION = "restart";
+
@PersistenceContext(unitName = RHQConstants.PERSISTENCE_UNIT_NAME)
private EntityManager entityManager;
@@ -120,6 +130,9 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
@EJB
private AlertManagerLocal alertManager;
+ @EJB
+ private ConfigurationManagerLocal configurationManager;
+
@Override
public void linkResource(Resource resource) {
List<StorageNode> storageNodes = this.getStorageNodes();
@@ -438,6 +451,19 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
entityManager.flush();
}
+ private StorageNode findStorageNodeByAddress(String address) {
+ TypedQuery<StorageNode> query = entityManager.<StorageNode> createNamedQuery(StorageNode.QUERY_FIND_BY_ADDRESS,
+ StorageNode.class);
+ query.setParameter("address", address);
+ List<StorageNode> result = query.getResultList();
+
+ if (result != null && result.size() > 0) {
+ return result.get(0);
+ }
+
+ return null;
+ }
+
private StorageNodeLoadComposite.MeasurementAggregateWithUnits getMeasurementAggregateWithUnits(Subject subject,
int schedId, MeasurementUnits units, long beginTime, long endTime) {
MeasurementAggregate measurementAggregate = measurementManager.getAggregate(subject, schedId, beginTime,
@@ -559,4 +585,91 @@ public class StorageNodeManagerBean implements StorageNodeManagerLocal, StorageN
return resourceIdsWithAlertDefinitions.toArray(new Integer[resourceIdsWithAlertDefinitions.size()]);
}
+
+ @Override
+ public StorageNodeConfigurationComposite retrieveConfiguration(Subject subject, StorageNode storageNode) {
+ StorageNodeConfigurationComposite configuration = new StorageNodeConfigurationComposite(storageNode);
+
+ if (storageNode != null && storageNode.getResource() != null) {
+ Resource storageNodeResource = storageNode.getResource();
+ Configuration storageNodeConfiguration = configurationManager.getResourceConfiguration(subject,
+ storageNodeResource.getId());
+
+ configuration.setHeapSize(storageNodeConfiguration.getSimpleValue("maxHeapSize"));
+ configuration.setJmxPort(storageNode.getJmxPort());
+ }
+
+ return configuration;
+ }
+
+ @Override
+ public boolean updateConfiguration(Subject subject, StorageNodeConfigurationComposite storageNodeConfiguration) {
+ StorageNode storageNode = findStorageNodeByAddress(storageNodeConfiguration.getStorageNode().getAddress());
+
+ if (storageNode != null && storageNode.getResource() != null) {
+ Resource storageNodeResource = storageNode.getResource();
+ Configuration parameters = new Configuration();
+ parameters.setSimpleValue("jmxPort", storageNodeConfiguration.getJmxPort() + "");
+ parameters.setSimpleValue("heapSize", storageNodeConfiguration.getHeapSize() + "");
+
+ boolean updateConfigurationResult = runOperationAndWaitForResult(subject, storageNodeResource,
+ UPDATE_CONFIGURATION_OPERATION, parameters);
+
+ if (updateConfigurationResult) {
+ boolean restartResult = runOperationAndWaitForResult(subject, storageNodeResource, RESTART_OPERATION,
+ null);
+
+ if (restartResult) {
+ storageNode.setJmxPort(storageNodeConfiguration.getJmxPort());
+ entityManager.persist(storageNode);
+
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private boolean runOperationAndWaitForResult(Subject subject, Resource storageNodeResource, String operationToRun,
+ Configuration parameters) {
+
+ //scheduling the operation
+ long operationStartTime = System.currentTimeMillis();
+ operationManager.scheduleResourceOperation(subject, storageNodeResource.getId(), operationToRun, 0, 0, 0, 0,
+ parameters, "Run by StorageNodeManagerBean");
+
+ //waiting for the operation result then return it
+ int iteration = 0;
+ boolean successResultFound = false;
+ while (iteration < MAX_ITERATIONS && !successResultFound) {
+ ResourceOperationHistoryCriteria criteria = new ResourceOperationHistoryCriteria();
+ criteria.addFilterResourceIds(storageNodeResource.getId());
+ criteria.addFilterStartTime(operationStartTime);
+ criteria.addFilterOperationName(operationToRun);
+ criteria.addFilterStatus(OperationRequestStatus.SUCCESS);
+ criteria.setPageControl(PageControl.getUnlimitedInstance());
+
+ PageList<ResourceOperationHistory> results = operationManager.findResourceOperationHistoriesByCriteria(
+ subject, criteria);
+
+ if (results != null && results.size() > 0) {
+ successResultFound = true;
+ }
+
+ if (successResultFound) {
+ break;
+ } else {
+ try {
+ Thread.sleep(OPERATION_QUERY_TIMEOUT);
+ } catch (Exception e) {
+ log.error(e);
+ }
+ }
+
+ iteration++;
+ }
+
+ return successResultFound;
+ }
}
\ No newline at end of file
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
index a9b2514..6fca820 100644
--- 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
@@ -25,6 +25,7 @@ import javax.ejb.Local;
import org.rhq.core.domain.alert.Alert;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.cloud.StorageNodeConfigurationComposite;
import org.rhq.core.domain.cloud.StorageNodeLoadComposite;
import org.rhq.core.domain.criteria.StorageNodeCriteria;
import org.rhq.core.domain.resource.Resource;
@@ -56,6 +57,10 @@ public interface StorageNodeManagerLocal {
*/
StorageNodeLoadComposite getLoad(Subject subject, StorageNode node, long beginTime, long endTime);
+ StorageNodeConfigurationComposite retrieveConfiguration(Subject subject, StorageNode storageNode);
+
+ boolean updateConfiguration(Subject subject, StorageNodeConfigurationComposite storageNodeConfiguration);
+
/**
* Fetches the list of StorageNode entities based on provided criteria.
*
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerRemote.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerRemote.java
index 72432db..7be1b07 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerRemote.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/cloud/StorageNodeManagerRemote.java
@@ -23,6 +23,7 @@ import javax.ejb.Remote;
import org.rhq.core.domain.alert.Alert;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.cloud.StorageNode;
+import org.rhq.core.domain.cloud.StorageNodeConfigurationComposite;
import org.rhq.core.domain.cloud.StorageNodeLoadComposite;
import org.rhq.core.domain.criteria.StorageNodeCriteria;
import org.rhq.core.domain.util.PageList;
@@ -48,6 +49,10 @@ public interface StorageNodeManagerRemote {
*/
StorageNodeLoadComposite getLoad(Subject subject, StorageNode node, long beginTime, long endTime);
+ StorageNodeConfigurationComposite retrieveConfiguration(Subject subject, StorageNode storageNode);
+
+ boolean updateConfiguration(Subject subject, StorageNodeConfigurationComposite storageNodeConfiguration);
+
/**
* <p>Fetches the list of {@link StorageNode} entities based on provided criteria.</p>
*
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/StorageNodeMaintenanceJob.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/StorageNodeMaintenanceJob.java
index 6b1940d..54ca4c2 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/StorageNodeMaintenanceJob.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/scheduler/jobs/StorageNodeMaintenanceJob.java
@@ -71,7 +71,6 @@ public class StorageNodeMaintenanceJob extends AbstractStatefulJob {
private final static String RUN_REPAIR_PROPERTY = "runRepair";
private final static String UPDATE_SEEDS_LIST = "updateSeedsList";
private final static String SEEDS_LIST = "seedsList";
- private final static String SUCCEED_PROPERTY = "succeed";
private static final String USERNAME_PROP = "rhq.cassandra.username";
private static final String PASSWORD_PROP = "rhq.cassandra.password";
@@ -169,8 +168,6 @@ public class StorageNodeMaintenanceJob extends AbstractStatefulJob {
List<Resource> childResources = LookupUtil.getResourceManager().findResourcesByCriteria(
LookupUtil.getSubjectManager().getOverlord(), c);
-
-
for (Resource childResource : childResources) {
if (STORAGE_SERVICE.equals(childResource.getName())) {
try {
diff --git a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
index 6194146..380da65 100644
--- a/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
+++ b/modules/plugins/rhq-storage/src/main/java/org/rhq/plugins/storage/StorageNodeComponent.java
@@ -82,11 +82,19 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
return prepareForUpgrade(parameters);
} else if (name.equals("readRepair")) {
return readRepair();
+ } else if (name.equals("updateConfiguration")) {
+ return updateConfiguration(parameters);
} else {
return super.invokeOperation(name, parameters);
}
}
+ private OperationResult updateConfiguration(Configuration params) {
+ OperationResult result = new OperationResult("Configuration updated.");
+ //TODO: implement updates to various sub-resources here
+ return result;
+ }
+
private OperationResult nodeAdded(Configuration params) {
boolean runRepair = params.getSimple("runRepair").getBooleanValue();
boolean updateSeedsList = params.getSimple("updateSeedsList").getBooleanValue();
@@ -222,12 +230,12 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
}
return result;
}
-
+
private OperationResult prepareForUpgrade(Configuration parameters) throws Exception {
EmsConnection emsConnection = getEmsConnection();
EmsBean storageService = emsConnection.getBean("org.apache.cassandra.db:type=StorageService");
Class<?>[] emptyParams = new Class<?>[0];
-
+
if (log.isDebugEnabled()) {
log.debug("Disabling native transport...");
}
@@ -249,7 +257,7 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
snapshotName = System.currentTimeMillis() + "";
}
operation.invoke(snapshotName, new String[] {});
-
+
// max 2 sec
waitForTaskToComplete(500, 10, 150);
@@ -261,7 +269,7 @@ public class StorageNodeComponent extends CassandraNodeComponent implements Oper
return new OperationResult();
}
-
+
private void waitForTaskToComplete(int initialWaiting, int maxTries, int sleepMillis) {
// initial waiting
try {
diff --git a/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml
index 5a60d19..6ed31b7 100644
--- a/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/rhq-storage/src/main/resources/META-INF/rhq-plugin.xml
@@ -73,7 +73,7 @@
</c:list-property>
</results>
</operation>
-
+
<operation name="addNodeMaintenance">
<parameters>
<c:simple-property name="runRepair" type="boolean" default="true"/>
@@ -111,6 +111,16 @@
</parameters>
</operation>
+ <operation name="updateConfiguration" description="Updates the node configuration. Will require a separate server restart for the settings to take effect.">
+ <parameters>
+ <c:simple-property name="heapSize" type="string" description="The heap size to be used for both -Xms and -Xmx JVM options."/>
+ <c:simple-property name="jmxPort" type="integer" description="JMX port JVM option."/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult" description="Outcome of updating the configuration."/>
+ </results>
+ </operation>
+
<resource-configuration>
<c:group name="MemorySettings">
<c:simple-property name="minHeapSize"
@@ -195,3 +205,4 @@
<service name="Keyspace" sourcePlugin="Cassandra" sourceType="Keyspace"/>
</server>
</plugin>
+
10 years, 11 months
[rhq] Branch 'mtho11/consolidated-metrics' - modules/enterprise
by mike thompson
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsViewDataSource.java | 57 ++++++----
1 file changed, 37 insertions(+), 20 deletions(-)
New commits:
commit 256e148f6e78a6c341809921d9c650e6f4e88ebe
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Wed Jul 17 10:56:03 2013 -0700
Consolidated Metrics - Fix bug with sparkline graphs not showing proper values.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsViewDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsViewDataSource.java
index 605267d..d8bfb64 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsViewDataSource.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsViewDataSource.java
@@ -61,6 +61,7 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
final private Resource resource;
private List<MetricDisplaySummary> metricDisplaySummaries;
private List<List<MeasurementDataNumericHighLowComposite>> metricsDataList;
+ private int[] definitionArrayIds;
private MeasurementUserPreferences measurementUserPrefs;
public MetricsViewDataSource(Resource resource) {
@@ -99,10 +100,6 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
nameField.setWidth("30%");
fields.add(nameField);
- ListGridField alertsField = new ListGridField(FIELD_ALERT_COUNT, MSG.common_title_alerts());
- alertsField.setWidth("10%");
- fields.add(alertsField);
-
ListGridField minField = new ListGridField(FIELD_MIN_VALUE, MSG.view_resource_monitor_table_min());
minField.setWidth("15%");
fields.add(minField);
@@ -119,6 +116,10 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
lastField.setWidth("15%");
fields.add(lastField);
+ ListGridField alertsField = new ListGridField(FIELD_ALERT_COUNT, MSG.common_title_alerts());
+ alertsField.setWidth("10%");
+ fields.add(alertsField);
+
return fields;
}
@@ -136,7 +137,7 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
MeasurementUtility.formatSimpleMetrics(from);
ListGridRecord record = new ListGridRecord();
- record.setAttribute(FIELD_SPARKLINE, getCsvMetricsForSparkline());
+ record.setAttribute(FIELD_SPARKLINE, getCsvMetricsForSparkline(from.getDefinitionId()));
record.setAttribute(FIELD_METRIC_LABEL, from.getLabel());
record.setAttribute(FIELD_ALERT_COUNT, String.valueOf(from.getAlertCount()));
record.setAttribute(FIELD_MIN_VALUE, getMetricStringValue(from.getMinMetric()));
@@ -151,28 +152,45 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
return record;
}
- private String getCsvMetricsForSparkline() {
+ private String getCsvMetricsForSparkline(int definitionId) {
StringBuilder sb = new StringBuilder();
- Log.debug("getCsvMetricsForSparkline.metricsDataList: " + metricsDataList.size());
- for (List<MeasurementDataNumericHighLowComposite> measurementData : metricsDataList) {
- for (int i = 0; i < measurementData.size(); i++) {
+ Log.debug("getCsvMetricsForSparkline.metricsDataList("+definitionId+"): " + metricsDataList.size());
+ List<MeasurementDataNumericHighLowComposite> selectedMetricsList = getMeasurementsForMeasurementDefId(definitionId);
+
+ for (int i = 0; i < selectedMetricsList.size(); i++) {
// take the last 20 values
- if (i >= measurementData.size() - 20) {
- if (!Double.isNaN(measurementData.get(i).getValue())) {
- sb.append((int) measurementData.get(i).getValue());
+ //if (i >= selectedMetricsList.size() - 20) {
+ MeasurementDataNumericHighLowComposite measurementData = selectedMetricsList.get(i);
+ if (!Double.isNaN(measurementData.getValue())) {
+ sb.append((int) measurementData.getValue());
sb.append(",");
}
- }
- }
- if (sb.toString().endsWith(",")) {
- sb.setLength(sb.length() - 1);
+ //}
}
+
+ if (sb.toString().endsWith(",")) {
+ sb.setLength(sb.length() - 1);
}
Log.debug("getCsvMetricsForSparkline: " + sb.toString());
return sb.toString();
}
+ List<MeasurementDataNumericHighLowComposite> getMeasurementsForMeasurementDefId(int definitionId){
+ List<MeasurementDataNumericHighLowComposite> selectedMetricsDataList;
+ int selectedIndex = 0;
+
+ // find the ordinal position as specified when querying the metrics
+ for (int i = 0; i < definitionArrayIds.length; i++) {
+ if(definitionArrayIds[i] == definitionId){
+ selectedIndex = i;
+ break;
+ }
+ }
+
+ return metricsDataList.get(selectedIndex);
+ }
+
protected String getMetricStringValue(MetricDisplayValue value) {
return (value != null) ? value.toString() : "";
}
@@ -186,7 +204,6 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
@Override
protected void executeFetch(final DSRequest request, final DSResponse response, final Criteria unused) {
- Log.debug("***** Fetching MetricsView data :");
GWTServiceLookup.getMeasurementScheduleService().findSchedulesForResourceAndType(resource.getId(),
DataType.MEASUREMENT, null, true, new AsyncCallback<ArrayList<MeasurementSchedule>>() {
@Override
@@ -211,7 +228,7 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
BrowserUtility.graphSparkLines();
}
}.schedule(150);
- Log.debug("*** Finished CountdownLatch for metrics loaded: " + metricsDataList.size());
+ Log.debug("Finished CountdownLatch for metrics loaded: " + metricsDataList.size());
}
});
@@ -262,7 +279,7 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
measurementDefMap.put(definition.getDisplayName(), definition);
}
//bundle definition ids for asynch call.
- int[] definitionArrayIds = new int[definitions.size()];
+ definitionArrayIds = new int[definitions.size()];
final String[] displayOrder = new String[definitions.size()];
measurementDefMap.keySet().toArray(displayOrder);
//sort the charting data ex. Free Memory, Free Swap Space,..System Load
@@ -288,7 +305,7 @@ public class MetricsViewDataSource extends RPCDataSource<MetricDisplaySummary, C
if (!measurementDataList.isEmpty()) {
metricsDataList = measurementDataList;
- Log.debug("*** Setting metricsDataList.size: " + metricsDataList.size());
+ Log.debug("Retrieved metrics metricsDataList.size: " + metricsDataList.size());
countDownLatch.countDown();
}
}
10 years, 11 months
[rhq] modules/common modules/enterprise
by John Sanda
modules/common/cassandra-schema/pom.xml | 6 ++++++
modules/enterprise/server/server-metrics/pom.xml | 12 ++++++++++++
2 files changed, 18 insertions(+)
New commits:
commit b268d00034cb7af8d929006e8ac4688eeae58549
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Jul 17 13:10:58 2013 -0400
Revert "cleaning up dependencies"
This reverts commit e798901b83e37cd267a2d11489664569918ef90d.
diff --git a/modules/common/cassandra-schema/pom.xml b/modules/common/cassandra-schema/pom.xml
index 55dedb8..8e3b44a 100644
--- a/modules/common/cassandra-schema/pom.xml
+++ b/modules/common/cassandra-schema/pom.xml
@@ -15,6 +15,12 @@
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
+ <artifactId>rhq-cassandra-ccm-core</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
<artifactId>rhq-cassandra-util</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/modules/enterprise/server/server-metrics/pom.xml b/modules/enterprise/server/server-metrics/pom.xml
index 97496f7..2245978 100644
--- a/modules/enterprise/server/server-metrics/pom.xml
+++ b/modules/enterprise/server/server-metrics/pom.xml
@@ -47,6 +47,18 @@
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
+ <artifactId>rhq-cassandra-ccm-core</artifactId>
+ <version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.cassandra</groupId>
+ <artifactId>cassandra-clientutil</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
<artifactId>rhq-cassandra-ccm-testng</artifactId>
<version>${project.version}</version>
<scope>test</scope>
10 years, 11 months
[rhq] modules/core
by Thomas Segismont
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java | 15 ++++++++--
1 file changed, 13 insertions(+), 2 deletions(-)
New commits:
commit a05f561f5fcac94b3308937b07d3b1e1e3f84d58
Author: Thomas Segismont <tsegismo(a)redhat.com>
Date: Wed Jul 17 16:59:03 2013 +0200
Print simpler log message when component invocation is interrupted and log level is higher than debug
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
index a9fe1c2..3669947 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceContainer.java
@@ -671,8 +671,19 @@ public class ResourceContainer implements Serializable {
public void markContextInterrupted() {
localContext.markInterrupted();
- LOG.warn("Invocation has been marked interrupted for method [" + method + "] on resource ["
- + resourceContainer.getResource() + "]");
+ LOG.warn(getContextInterruptedWarningMessage(LOG.isDebugEnabled()));
+ }
+
+ private String getContextInterruptedWarningMessage(boolean detailed) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Invocation has been marked interrupted for method [");
+ if (detailed) {
+ sb.append(method.toGenericString());
+ } else {
+ sb.append(method.getDeclaringClass().getSimpleName()).append(".").append(method.getName());
+ }
+ sb.append("] on resource [").append(resourceContainer.getResource()).append("]");
+ return sb.toString();
}
}
}
10 years, 11 months
[rhq] modules/enterprise
by Heiko W. Rupp
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/jaas/LdapLoginModule.java | 16 +++++++-
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/LdapGroupManagerBean.java | 20 ++++------
2 files changed, 23 insertions(+), 13 deletions(-)
New commits:
commit 01cd91b130f563ba62cd96a46f2cb3a2ac567a48
Author: Larry O'Leary <loleary(a)redhat.com>
Date: Wed Jul 17 16:32:05 2013 +0200
BZ 981015 - Ldap auth failed if DN contained a backslash
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/jaas/LdapLoginModule.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/jaas/LdapLoginModule.java
index 6b7add6..0db28f7 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/jaas/LdapLoginModule.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/core/jaas/LdapLoginModule.java
@@ -23,6 +23,7 @@ import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Properties;
+import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.SearchControls;
@@ -194,7 +195,18 @@ public class LdapLoginModule extends UsernamePasswordLoginModule {
SearchResult si = (SearchResult) answer.next();
// Construct the UserDN
- String userDN = si.getName() + "," + baseDNs[x];
+ String userDN = null;
+
+ try {
+ userDN = si.getNameInNamespace();
+ } catch (UnsupportedOperationException use) {
+ userDN = new CompositeName(si.getName()).get(0);
+ if (si.isRelative()) {
+ userDN += "," + baseDNs[x];
+ }
+ }
+
+ log.debug("Using LDAP userDN=" + userDN);
ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDN);
ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, inputPassword);
@@ -209,7 +221,7 @@ public class LdapLoginModule extends UsernamePasswordLoginModule {
// If we try all the BaseDN's and have not found a match, return false
return false;
} catch (Exception e) {
- log.info("Failed to validate password: " + e.getMessage());
+ log.info("Failed to validate password for [" + userName + "]: " + e.getMessage());
return false;
}
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/LdapGroupManagerBean.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/LdapGroupManagerBean.java
index 532a944..a28c709 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/LdapGroupManagerBean.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/resource/group/LdapGroupManagerBean.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2011 Red Hat, Inc.
+ * Copyright (C) 2005-2013 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -13,8 +13,8 @@
* 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.
+ * 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.resource.group;
@@ -33,6 +33,7 @@ import java.util.Set;
import javax.ejb.EJB;
import javax.ejb.Stateless;
+import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
@@ -345,12 +346,9 @@ public class LdapGroupManagerBean implements LdapGroupManagerLocal {
try {
userDN = si.getNameInNamespace();
} catch (UnsupportedOperationException use) {
- userDN = si.getName();
- if (userDN.startsWith("\"")) {
- userDN = userDN.substring(1, userDN.length());
- }
- if (userDN.endsWith("\"")) {
- userDN = userDN.substring(0, userDN.length() - 1);
+ userDN = new CompositeName(si.getName()).get(0);
+ if (si.isRelative()) {
+ userDN += "," + baseDNs[x];
}
userDN = userDN + "," + baseDNs[x];
}
@@ -507,7 +505,7 @@ public class LdapGroupManagerBean implements LdapGroupManagerLocal {
/** Translate SystemSettings to familiar Properties instance since we're
* passing not one but multiple values.
- *
+ *
* @param systemSettings
* @return
*/
@@ -532,7 +530,7 @@ public class LdapGroupManagerBean implements LdapGroupManagerLocal {
/** Executes the LDAP group query using the filters, context and search controls, etc. parameters passed in.
* The matching groups located during processing this pages of results are added as new entries to the
* groupDetailsMap passed in.
- *
+ *
* @param filter
* @param groupDetailsMap
* @param ctx
10 years, 11 months
[rhq] 3 commits - modules/common modules/enterprise modules/helpers
by John Sanda
modules/common/cassandra-ccm/cassandra-ccm-core/src/main/java/org/rhq/cassandra/CassandraClusterManager.java | 2
modules/common/cassandra-installer/src/main/java/org/rhq/storage/installer/StorageInstaller.java | 4
modules/common/cassandra-installer/src/test/java/org/rhq/storage/installer/StorageInstallerTest.java | 123 ++++++++++
modules/common/cassandra-installer/src/test/resources/log4j.properties | 41 +++
modules/common/cassandra-schema/pom.xml | 6
modules/enterprise/server/server-metrics/pom.xml | 12
modules/helpers/metrics-simulator/pom.xml | 6
7 files changed, 173 insertions(+), 21 deletions(-)
New commits:
commit 165c9c9f8da7251c0000444f04161171a7d5794f
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Jul 17 07:37:12 2013 -0400
need to make cassandra-ccm-core a direct dependency now
diff --git a/modules/helpers/metrics-simulator/pom.xml b/modules/helpers/metrics-simulator/pom.xml
index a55afa5..0a06610 100644
--- a/modules/helpers/metrics-simulator/pom.xml
+++ b/modules/helpers/metrics-simulator/pom.xml
@@ -13,6 +13,12 @@
<dependencies>
<dependency>
<groupId>org.rhq</groupId>
+ <artifactId>rhq-cassandra-ccm-core</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.rhq</groupId>
<artifactId>rhq-cassandra-schema</artifactId>
<version>${project.version}</version>
</dependency>
commit fb59ea4fb09414875afcaa9543788e3cfc1b14f1
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Jul 17 07:35:22 2013 -0400
initial commit for StorageInstallerTest
This commit provides some initial test coverage for the storage installer. More
tests will be added to cover various error handling situations and upgrade
scenarios.
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 7496d08..338ef3a 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
@@ -303,7 +303,7 @@ public class CassandraClusterManager {
return nodeIds;
}
- private void killNode(File nodeDir) throws Exception {
+ public void killNode(File nodeDir) throws Exception {
long pid = getPid(nodeDir);
CLibrary.kill((int) pid, 9);
}
diff --git a/modules/common/cassandra-installer/src/main/java/org/rhq/storage/installer/StorageInstaller.java b/modules/common/cassandra-installer/src/main/java/org/rhq/storage/installer/StorageInstaller.java
index 2fec2dc..63282e4 100644
--- a/modules/common/cassandra-installer/src/main/java/org/rhq/storage/installer/StorageInstaller.java
+++ b/modules/common/cassandra-installer/src/main/java/org/rhq/storage/installer/StorageInstaller.java
@@ -485,7 +485,7 @@ public class StorageInstaller {
private PropertiesFileUpdate getServerProperties() {
String sysprop = System.getProperty("rhq.server.properties-file");
if (sysprop == null) {
- throw new RuntimeException("The required system property [rhq.server.properties] is not defined.");
+ throw new RuntimeException("The required system property [rhq.server.properties-file] is not defined.");
}
File file = new File(sysprop);
@@ -605,7 +605,7 @@ public class StorageInstaller {
return new File(binDir, "cassandra.pid").exists();
}
- private boolean verifyNodeIsUp(String address, int jmxPort, int retries, long timeout) throws Exception {
+ boolean verifyNodeIsUp(String address, int jmxPort, int retries, long timeout) throws Exception {
String url = "service:jmx:rmi:///jndi/rmi://" + address + ":" + jmxPort + "/jmxrmi";
JMXServiceURL serviceURL = new JMXServiceURL(url);
JMXConnector connector = null;
diff --git a/modules/common/cassandra-installer/src/test/java/org/rhq/storage/installer/StorageInstallerTest.java b/modules/common/cassandra-installer/src/test/java/org/rhq/storage/installer/StorageInstallerTest.java
new file mode 100644
index 0000000..3fd13c7
--- /dev/null
+++ b/modules/common/cassandra-installer/src/test/java/org/rhq/storage/installer/StorageInstallerTest.java
@@ -0,0 +1,123 @@
+package org.rhq.storage.installer;
+
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.Properties;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.PosixParser;
+import org.apache.commons.io.FileUtils;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import org.rhq.cassandra.CassandraClusterManager;
+import org.rhq.core.util.file.FileUtil;
+
+/**
+ * @author John Sanda
+ */
+public class StorageInstallerTest {
+
+ private File basedir;
+
+ private File storageDir;
+
+ private StorageInstaller installer;
+
+ @BeforeMethod
+ public void initDirs(Method test) throws Exception {
+ File dir = new File(getClass().getResource(".").toURI());
+ basedir = new File(dir, getClass().getSimpleName() + "/" + test.getName());
+ FileUtil.purge(basedir, true);
+ basedir.mkdirs();
+
+ System.setProperty("rhq.server.basedir", basedir.getAbsolutePath());
+
+ File serverPropsFile = new File(basedir, "rhq-server.properties");
+ FileUtils.touch(serverPropsFile);
+ System.setProperty("rhq.server.properties-file", serverPropsFile.getAbsolutePath());
+
+ storageDir = new File(basedir, "rhq-storage");
+
+ installer = new StorageInstaller();
+ }
+
+ @AfterMethod
+ public void shutdownStorageNode() throws Exception {
+ CassandraClusterManager ccm = new CassandraClusterManager();
+ ccm.killNode(storageDir);
+ }
+
+ @Test
+ public void performValidInstall() throws Exception {
+ CommandLineParser parser = new PosixParser();
+
+ String[] args = {
+ "--dir", storageDir.getAbsolutePath(),
+ "--commitlog", new File(storageDir, "commit_log").getAbsolutePath(),
+ "--data", new File(storageDir, "data").getAbsolutePath(),
+ "--saved-caches", new File(storageDir, "saved_caches").getAbsolutePath(),
+ "--heap-size", "256M",
+ "--heap-new-size", "64M",
+ "--hostname", "127.0.0.1"
+ };
+
+ CommandLine cmdLine = parser.parse(installer.getOptions(), args);
+ int status = installer.run(cmdLine);
+
+ assertEquals(status, 0, "Expected to get back a status code of 0 for a successful install");
+ assertNodeIsRunning();
+ assertRhqServerPropsUpdated();
+
+ File binDir = new File(storageDir, "bin");
+ assertTrue(binDir.exists(), "Expected to find bin directory at " + binDir);
+
+ File confDir = new File(storageDir, "conf");
+ assertTrue(confDir.exists(), "Expected to find conf directory at " + confDir);
+
+ File libDir = new File(storageDir, "lib");
+ assertTrue(libDir.exists(), "Expected to find lib directory at " + libDir);
+
+ File commitLogDir = new File(storageDir, "commit_log");
+ assertTrue(commitLogDir.exists(), "Expected to find commit_log directory at " + commitLogDir);
+
+ File dataDir = new File(storageDir, "data");
+ assertTrue(dataDir.exists(), "Expected to find data directory at " + dataDir);
+
+ File savedCachesDir = new File(storageDir, "saved_caches");
+ assertTrue(savedCachesDir.exists(), "Expected to find saved_caches directory at " + savedCachesDir);
+ }
+
+ private void assertNodeIsRunning() {
+ try {
+ installer.verifyNodeIsUp("127.0.0.1", 7299, 3, 1000);
+ } catch (Exception e) {
+ fail("Failed to verify that node is up", e);
+ }
+ }
+
+ private void assertRhqServerPropsUpdated() {
+ File serverPropsFile = new File(basedir, "rhq-server.properties");
+ Properties properties = new Properties();
+
+ try {
+ properties.load(new FileInputStream(serverPropsFile));
+ } catch (IOException e) {
+ fail("Failed to verify that " + serverPropsFile + " was updated", e);
+ }
+
+ String seeds = properties.getProperty("rhq.cassandra.seeds");
+
+ assertEquals(seeds, "127.0.0.1|7299|9142");
+ }
+
+}
diff --git a/modules/common/cassandra-installer/src/test/resources/log4j.properties b/modules/common/cassandra-installer/src/test/resources/log4j.properties
new file mode 100644
index 0000000..d56cc88
--- /dev/null
+++ b/modules/common/cassandra-installer/src/test/resources/log4j.properties
@@ -0,0 +1,41 @@
+#
+# /*
+# * 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.
+# */
+#
+
+log4j.rootCategory=WARN, FILE, CONSOLE
+
+log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
+log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
+log4j.appender.FILE.File=./target/test.log
+log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
+log4j.appender.FILE.layout.ConversionPattern=%d{ABSOLUTE} %-5p %c %m%n
+#log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
+log4j.appender.FILE.Append=false
+
+log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
+log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
+#log4j.appender.CONSOLE.layout.ConversionPattern=%5p %d{HH:mm:ss,SSS} %m%n
+log4j.appender.CONSOLE.layout.ConversionPattern=%d{ABSOLUTE} %-5p %c %m%n
+
+log4j.logger.org.rhq=DEBUG
commit e798901b83e37cd267a2d11489664569918ef90d
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Jul 16 16:16:01 2013 -0400
cleaning up dependencies
diff --git a/modules/common/cassandra-schema/pom.xml b/modules/common/cassandra-schema/pom.xml
index 8e3b44a..55dedb8 100644
--- a/modules/common/cassandra-schema/pom.xml
+++ b/modules/common/cassandra-schema/pom.xml
@@ -15,12 +15,6 @@
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
- <artifactId>rhq-cassandra-ccm-core</artifactId>
- <version>${project.version}</version>
- </dependency>
-
- <dependency>
- <groupId>${project.groupId}</groupId>
<artifactId>rhq-cassandra-util</artifactId>
<version>${project.version}</version>
</dependency>
diff --git a/modules/enterprise/server/server-metrics/pom.xml b/modules/enterprise/server/server-metrics/pom.xml
index 2245978..97496f7 100644
--- a/modules/enterprise/server/server-metrics/pom.xml
+++ b/modules/enterprise/server/server-metrics/pom.xml
@@ -47,18 +47,6 @@
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
- <artifactId>rhq-cassandra-ccm-core</artifactId>
- <version>${project.version}</version>
- <exclusions>
- <exclusion>
- <groupId>org.apache.cassandra</groupId>
- <artifactId>cassandra-clientutil</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
-
- <dependency>
- <groupId>${project.groupId}</groupId>
<artifactId>rhq-cassandra-ccm-testng</artifactId>
<version>${project.version}</version>
<scope>test</scope>
10 years, 11 months
[rhq] modules/helpers
by Heiko W. Rupp
modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/Parameter.java | 5
modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/RhqType.java | 77 +++
modules/helpers/pluginGen/pom.xml | 7
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/AnnotationProcessor.java | 44 +
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/DirectoryClassLoader.java | 142 ++++++
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Generator.java | 229 ++++++----
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java | 31 +
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Prop.java | 59 +-
modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java | 110 ++++
modules/helpers/pluginGen/src/main/resources/component.ftl | 9
modules/helpers/pluginGen/src/main/resources/descriptor.ftl | 5
modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl | 17
modules/helpers/pluginGen/src/main/resources/pom.ftl | 15
modules/helpers/pluginGen/src/test/java/org/rhq/helpers/pluginGen/test/FooBean.java | 55 ++
14 files changed, 671 insertions(+), 134 deletions(-)
New commits:
commit ae96f1c0ad6e797e889923dc47a1f3c55c8eb394
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed Jul 17 11:06:21 2013 +0200
Allow to specify a directory with classes to scan for plugin annotations and to auto-create metrics+operations from them.
diff --git a/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/Parameter.java b/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/Parameter.java
index 4b82a13..29dcc1e 100644
--- a/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/Parameter.java
+++ b/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/Parameter.java
@@ -29,13 +29,14 @@ import java.lang.annotation.Target;
/**
* Parameter.
- *
+ *
* @author Galder Zamarreño
* @since 4.0
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Parameter {
- String name() default "";
+ String name() ;
String description() default "";
+ RhqType type() default RhqType.VOID;
}
diff --git a/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/RhqType.java b/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/RhqType.java
new file mode 100644
index 0000000..1487a51
--- /dev/null
+++ b/modules/helpers/pluginAnnotations/src/main/java/org/rhq/helpers/pluginAnnotations/agent/RhqType.java
@@ -0,0 +1,77 @@
+/*
+ * 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.helpers.pluginAnnotations.agent;
+
+import java.io.File;
+
+
+/**
+ * Base data types from RHQ for properties
+ * @author Heiko W. Rupp
+ */
+public enum RhqType {
+ INTEGER(new Class<?>[]{Integer.class,int.class},Boolean.class),
+ LONG(new Class<?>[]{Long.class,long.class},Long.class),
+ DOUBLE(new Class<?>[]{Double.class,double.class},Double.class),
+ STRING(new Class<?>[]{String.class},String.class),
+ LONG_STRING(new Class<?>[]{},String.class),
+ PASSWORD(new Class<?>[]{},String.class),
+ BOOLEAN(new Class<?>[]{Boolean.class, boolean.class},Boolean.class),
+ FLOAT(new Class<?>[]{Float.class, float.class},Float.class),
+ FILE(new Class<?>[]{File.class},File.class),
+ DIRECTORY(new Class<?>[]{},File.class),
+ VOID(new Class<?>[]{Void.class,void.class},Void.class)
+ ;
+ private Class<?>[] fromClasses;
+ private Class<?> toClass;
+
+ private RhqType(Class<?>[] fromClasses,Class<?> toClass) {
+
+ this.fromClasses = fromClasses;
+ this.toClass = toClass;
+ }
+
+ public Class<?>[] getFromClasses() {
+ return fromClasses;
+ }
+
+ public Class<?> getToClass() {
+ return toClass;
+ }
+
+ public static RhqType findType(Class<?> clazz) {
+ for (RhqType type : RhqType.values()) {
+ for (Class from : type.getFromClasses()) {
+ if (clazz.equals(from)) {
+ return type;
+ }
+ }
+ }
+ return null;
+ }
+
+ public String getRhqName() {
+ String name = name().toLowerCase();
+ if (name.equals("long_string")) {
+ name = "longString";
+ }
+ return name;
+ }
+}
diff --git a/modules/helpers/pluginGen/pom.xml b/modules/helpers/pluginGen/pom.xml
index 5aa512c..e7744e4 100644
--- a/modules/helpers/pluginGen/pom.xml
+++ b/modules/helpers/pluginGen/pom.xml
@@ -19,6 +19,11 @@
<name>RHQ plugin generator</name>
<description>Helper to generate plugin skeletons</description>
+ <properties>
+ <!-- we are using JDK 1.7 here, as JavaFX needs this and the generator is standalone anyway -->
+ <animal.sniffer.java.signature.artifactId>java17</animal.sniffer.java.signature.artifactId>
+ </properties>
+
<build>
<plugins>
@@ -104,7 +109,7 @@
<dependency>
<groupId>org.rhq.helpers</groupId>
<artifactId>rhq-pluginAnnotations</artifactId>
- <version>4.8.0-SNAPSHOT</version>
+ <version>4.9.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/AnnotationProcessor.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/AnnotationProcessor.java
new file mode 100644
index 0000000..3c90b7b
--- /dev/null
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/AnnotationProcessor.java
@@ -0,0 +1,44 @@
+/*
+ * 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.helpers.pluginGen;
+
+import java.util.List;
+
+/**
+ * Processor that scans a directory for annotated classes and generates metrics etc. from them.
+ * @author Heiko W. Rupp
+ */
+public class AnnotationProcessor {
+
+ private List<Class> classList;
+ private final DirectoryClassLoader classLoader;
+
+ public AnnotationProcessor(String baseDirectory) {
+ classLoader = new DirectoryClassLoader();
+ classLoader.setBaseDir(baseDirectory);
+ }
+
+ public void populate(Props props) {
+ classList = classLoader.findClasses();
+
+ props.populateMetrics(classList);
+ props.populateOperations(classList);
+ }
+}
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/DirectoryClassLoader.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/DirectoryClassLoader.java
new file mode 100644
index 0000000..b4a729f
--- /dev/null
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/DirectoryClassLoader.java
@@ -0,0 +1,142 @@
+/*
+ * 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.helpers.pluginGen;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileInputStream;
+import java.nio.file.FileVisitor;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.List;
+
+/**
+ * Classloader to load from a given directory
+ * @author Heiko W. Rupp
+ */
+public class DirectoryClassLoader extends ClassLoader {
+ private Hashtable classes = new Hashtable(); //used to cache already defined classes
+ private String baseDir;
+
+ @Override
+ protected Class<?> findClass(String pathName) throws ClassNotFoundException {
+
+
+ if (baseDir==null) {
+ throw new IllegalStateException("Must set baseDir first");
+ }
+
+ byte classByte[];
+ Class result = null;
+
+ String className = pathName.substring(baseDir.length()+1); // remove base dir
+ className = className.substring(0,className.length()-6); // remove .class
+ className = className.replaceAll(File.separator,"."); // change / -> .
+
+ result = (Class) classes.get(className); //checks in cached classes
+ if (result != null) {
+ return result;
+ }
+ try {
+ File classFile = new File(pathName);
+ FileInputStream fis = new FileInputStream(classFile);
+
+ ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
+ int nextValue = fis.read();
+ while (-1 != nextValue) {
+ byteStream.write(nextValue);
+ nextValue = fis.read();
+ }
+
+ classByte = byteStream.toByteArray();
+ result = defineClass(className, classByte, 0, classByte.length, null);
+ classes.put(className, result);
+ return result;
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ public void setBaseDir(String baseDir) {
+ this.baseDir = baseDir;
+ }
+
+ public List<Class> findClasses() {
+ if (baseDir==null) {
+ throw new IllegalStateException("Must set baseDir first");
+ }
+
+ File baseFile = new File(baseDir);
+ if(!baseFile.isDirectory()) {
+ throw new IllegalStateException("BaseDir is no directory");
+ }
+ if (!baseFile.canRead()) {
+ throw new IllegalStateException("BaseDir is not readable");
+ }
+
+ List<File> files = walk(baseFile);
+
+ List<Class> classes = new ArrayList<>();
+ for (File file : files) {
+ String fileName = file.getAbsolutePath();
+
+ Class clazz = null;
+ try {
+ clazz = findClass(fileName);
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace(); // TODO: Customise this generated block
+ }
+ classes.add(clazz);
+
+ }
+
+ return classes;
+ }
+
+ private List<File> walk(File path) {
+
+ List<File> files = new ArrayList<>();
+
+ File[] list = path.listFiles();
+
+ if (list == null) {
+ return files;
+ }
+
+ for ( File f : list ) {
+ if ( f.isDirectory() ) {
+ List<File> newFiles = walk( f );
+ System.out.println( "Dir:" + f.getAbsoluteFile() );
+ files.addAll(newFiles);
+ }
+ else {
+ System.out.println( "File:" + f.getAbsoluteFile() );
+ if (f.getName().endsWith(".class") && !f.getName().contains("$")) {
+ files.add(f);
+ }
+
+ }
+ }
+ return files;
+ }
+}
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Generator.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Generator.java
index e7da952..21d0d4d 100644
--- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Generator.java
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Generator.java
@@ -149,9 +149,12 @@ public class Generator extends Application{
Label label = new Label("Messages:");
msgBox.getChildren().add(label);
errorMessage = new Text();
- errorMessage.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 12));
+ errorMessage.setFont(Font.font("Arial", FontWeight.SEMI_BOLD, 15));
errorMessage.setId("errorMessage");
msgBox.getChildren().add(errorMessage);
+ msgBox.setPadding(new Insets(5));
+ msgBox.setSpacing(3);
+ msgBox.setAlignment(Pos.BASELINE_LEFT);
return msgBox;
}
@@ -172,94 +175,14 @@ public class Generator extends Application{
// Now add the field itself
final Class propType = prop.getType();
if (propType.equals(String.class)) {
- final Pattern pattern = Pattern.compile(prop.getValidationRegex());
-
- final TextField input = new TextField();
- // Add field leave event to fill in the props with the result
- input.focusedProperty().addListener(new ChangeListener<Boolean>() {
- @Override
- public void changed(ObservableValue<? extends Boolean> observableValue, Boolean oldState,
- Boolean newState) {
- if (newState) { // User entered input field
- descriptionField.setText(prop.getDescription());
- }
- else { // User left input field
- descriptionField.setText("");
- setPropsValue(prop.getVariableName(),input.getText(), propType); // TODO right place?
- }
- }
- });
- // Add validation of the input
- input.textProperty().addListener(new ChangeListener<String>() {
- @Override
- public void changed(ObservableValue<? extends String> observableValue, String s, String newText) {
- Matcher m = pattern.matcher(newText);
- if (!m.matches()) {
- setErrorMessage("Input does not match " + prop.getValidationRegex());
- } else {
- clearErrorMessage();
- }
-
- }
- });
- root.add(input, 1, row);
+ addStringField(root, descriptionField, row, prop);
} else if (propType.equals(Boolean.class) || propType.equals(boolean.class)) {
- final ChoiceBox choiceBox = new ChoiceBox();
- choiceBox.getItems().addAll("Yes", "No");
- choiceBox.getSelectionModel().selectLast(); // NO is default
- choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
- @Override
- public void changed(ObservableValue<? extends String> observableValue, String s, String newValue) {
- setPropsValue(prop.getVariableName(), newValue.equals("Yes"), propType);
- }
- });
- Tooltip tooltip = new Tooltip(prop.getDescription()); // TODO make this a hover listener
- choiceBox.setTooltip(tooltip);
-
- root.add(choiceBox, 1, row);
+ addBooleanField(root, row, prop);
} else if (propType.equals(ResourceCategory.class)) {
- final ChoiceBox choiceBox = new ChoiceBox();
- for (ResourceCategory cat : ResourceCategory.values()) {
- choiceBox.getItems().add(cat.getLowerName());
- }
- choiceBox.getSelectionModel().selectLast(); // service is default
- choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
- @Override
- public void changed(ObservableValue<? extends String> observableValue, String s, String newValue) {
- ResourceCategory newCategory = ResourceCategory.valueOf(newValue.toUpperCase());
- setPropsValue(prop.getVariableName(),newCategory,propType);
- }
- });
- Tooltip tooltip = new Tooltip(prop.getDescription()); // TODO make this a hover listener
- choiceBox.setTooltip(tooltip);
- root.add(choiceBox,1,row);
+ addResourceTypeChooser(root, row, prop);
} else if (propType.equals(File.class)) {
- // Can not add this directly, so add a button to trigger it
- final Text text = new Text();
- text.setText("Pick a directory");
- root.add(text,1,row);
- Tooltip tooltip = new Tooltip("Pick the (parent) directory where the plugin will be put in.");
- Button pickButton = new Button("Pick");
- pickButton.setTooltip(tooltip);
- pickButton.setOnAction(new EventHandler<ActionEvent>() {
- @Override
- public void handle(ActionEvent actionEvent) {
- DirectoryChooser chooser = new DirectoryChooser();
- chooser.setTitle("Pick a directory where the plugin will be put in.");
- File dir = chooser.showDialog(primaryStage);
- if (dir != null) {
- String dirName = dir.getAbsolutePath();
- props.setFileSystemRoot(dirName);
- clearErrorMessage();
- text.setText(dirName);
- } else {
- setErrorMessage("No directory selected");
- text.setText("Pick a directory");
- }
- }
- });
-
- root.add(pickButton,2,row);
+ addDirectoryChooserField(root, row, prop, descriptionField);
+
}
row++;
@@ -269,6 +192,115 @@ public class Generator extends Application{
return row;
}
+ private void addDirectoryChooserField(GridPane root, int row, final Prop prop, final Text descriptionField) {
+ // Can not add this directly, so add a button to trigger it
+ final TextField input = new TextField();
+ root.add(input,1,row);
+ Tooltip tooltip = new Tooltip(prop.getDescription());
+ Button pickButton = new Button("Pick");
+ input.setTooltip(tooltip);
+ pickButton.setTooltip(tooltip);
+ pickButton.setOnAction(new EventHandler<ActionEvent>() {
+ @Override
+ public void handle(ActionEvent actionEvent) {
+ DirectoryChooser chooser = new DirectoryChooser();
+ chooser.setTitle(prop.getDescription());
+ File dir = chooser.showDialog(primaryStage);
+ if (dir != null) {
+ String dirName = dir.getAbsolutePath();
+ setPropsValue(prop.getVariableName(), dirName, String.class);
+ clearErrorMessage();
+ input.setText(dirName);
+ } else {
+ setErrorMessage("No directory selected");
+ input.setText("Pick a directory");
+ }
+ }
+ });
+ input.focusedProperty().addListener(new ShowFieldDescriptionHandler(prop,descriptionField,input));
+ // Add validation of the input
+ input.textProperty().addListener(new ChangeListener<String>() {
+ @Override
+ public void changed(ObservableValue<? extends String> observableValue, String s, String newText) {
+ File file = new File(newText);
+ if (!file.isDirectory()) {
+ setErrorMessage(newText + " is no directory");
+ } else if (prop.isDirectoryWriteable() && !file.canWrite()) {
+ setErrorMessage(newText + " is not writable");
+ } else if (!prop.isDirectoryWriteable() && !file.canRead()) {
+ setErrorMessage(newText + " is not readable");
+ } else {
+ clearErrorMessage();
+ }
+
+ }
+ });
+
+
+
+ root.add(pickButton,2,row);
+ }
+
+ private void addResourceTypeChooser(GridPane root, int row, final Prop prop) {
+ final ChoiceBox choiceBox = new ChoiceBox();
+ for (ResourceCategory cat : ResourceCategory.values()) {
+ choiceBox.getItems().add(cat.getLowerName());
+ }
+ choiceBox.getSelectionModel().selectLast(); // service is default
+ choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
+ @Override
+ public void changed(ObservableValue<? extends String> observableValue, String s, String newValue) {
+ ResourceCategory newCategory = ResourceCategory.valueOf(newValue.toUpperCase());
+ setPropsValue(prop.getVariableName(),newCategory,prop.getType());
+ }
+ });
+ Tooltip tooltip = new Tooltip(prop.getDescription()); // TODO make this a hover listener
+ choiceBox.setTooltip(tooltip);
+ root.add(choiceBox,1,row);
+ }
+
+ private void addBooleanField(GridPane root, int row, final Prop prop) {
+ final ChoiceBox choiceBox = new ChoiceBox();
+ choiceBox.getItems().addAll("Yes", "No");
+ choiceBox.getSelectionModel().selectLast(); // NO is default
+ choiceBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
+ @Override
+ public void changed(ObservableValue<? extends String> observableValue, String s, String newValue) {
+ setPropsValue(prop.getVariableName(), newValue.equals("Yes"), prop.getType());
+ }
+ });
+ Tooltip tooltip = new Tooltip(prop.getDescription()); // TODO make this a hover listener
+ choiceBox.setTooltip(tooltip);
+
+ root.add(choiceBox, 1, row);
+ }
+
+ private void addStringField(GridPane root, final Text descriptionField, int row, final Prop prop) {
+ final Pattern pattern = Pattern.compile(prop.getValidationRegex());
+
+ final TextField input = new TextField();
+ if (prop.getDefaultValue()!=null && !prop.getDefaultValue().isEmpty()) {
+ input.setText(prop.getDefaultValue());
+ setPropsValue(prop.getVariableName(),prop.getDefaultValue(),prop.getType());
+ }
+ // Add field leave event to fill in the props with the result
+ input.focusedProperty().addListener(new ShowFieldDescriptionHandler(prop,descriptionField,input));
+ // Add validation of the input
+ input.textProperty().addListener(new ChangeListener<String>() {
+ @Override
+ public void changed(ObservableValue<? extends String> observableValue, String s, String newText) {
+ Matcher m = pattern.matcher(newText);
+ if (!m.matches()) {
+ setErrorMessage("Input does not match " + prop.getValidationRegex());
+ } else {
+ clearErrorMessage();
+ }
+
+ }
+ });
+ root.add(input, 1, row);
+ }
+
private void setInfoMessage(String message) {
errorMessage.setText(message);
errorMessage.setFill(Color.DARKGREEN);
@@ -297,4 +329,29 @@ public class Generator extends Application{
}
}
+
+ private class ShowFieldDescriptionHandler implements ChangeListener<Boolean> {
+
+ private Prop prop;
+ private Text descriptionField;
+ private TextField input;
+
+ private ShowFieldDescriptionHandler(Prop prop,Text descriptionField, TextField input) {
+ this.prop = prop;
+ this.descriptionField = descriptionField;
+ this.input = input;
+ }
+
+ @Override
+ public void changed(ObservableValue<? extends Boolean> observableValue, Boolean oldState,
+ Boolean newState) {
+ if (newState) { // User entered input field
+ descriptionField.setText(prop.getDescription());
+ }
+ else { // User left input field
+ descriptionField.setText("");
+ setPropsValue(prop.getVariableName(),input.getText(), String.class); // TODO right place?
+ }
+ }
+ }
}
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
index 64b5509..8722446 100644
--- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/PluginGen.java
@@ -51,6 +51,19 @@ public class PluginGen {
private final Log log = LogFactory.getLog(PluginGen.class);
public static void main(String[] arg) throws Exception {
+
+ if (arg.length>0) {
+ if (arg[0].equals("-ui")) {
+ Generator.main(arg);
+
+ }
+ else {
+ System.out.println("use option -ui to start the UI version");
+ }
+ System.exit(0);
+ }
+
+
PluginGen pg = new PluginGen();
pg.run();
@@ -121,10 +134,24 @@ public class PluginGen {
String pkg = props.getPackagePrefix() + "." + props.getName();
props.setPkg(pkg);
+ String name = props.getName(); // Type name
+
+ if (props.getComponentClass().contains("{name}")) {
+ props.setComponentClass(props.getComponentClass().replace("{name}",name));
+ }
+
+ if (props.getDiscoveryClass().contains("{name}")) {
+ props.setDiscoveryClass(props.getDiscoveryClass().replace("{name}",name));
+ }
+
for (Props cProp : props.getChildren()) {
cProp.setPkg(pkg);
}
+ if (props.getScanForAnnotations()!=null) {
+ AnnotationProcessor ap = new AnnotationProcessor(props.getScanForAnnotations());
+ ap.populate(props);
+ }
}
/**
@@ -247,7 +274,7 @@ public class PluginGen {
}
boolean success;
- File activeDirectory = new File(props.getFileSystemRoot(), props.getName());
+ File activeDirectory = new File(props.getFileSystemRoot(), props.getPluginName());
if (!activeDirectory.exists()) {
success = activeDirectory.mkdir();
@@ -260,7 +287,7 @@ public class PluginGen {
// write pom.xml
createFile(props, "pom", "pom.xml", activeDirectory.getAbsolutePath());
- // Create java directory hierarchie
+ // Create java directory hierarchy
String path = activeDirectory.getAbsolutePath() + File.separator + "src" + File.separator + "main"
+ File.separator;
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Prop.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Prop.java
index 4ed019a..40e729c 100644
--- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Prop.java
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Prop.java
@@ -30,48 +30,62 @@ public enum Prop {
PLUGIN_NAME("pluginName", String.class,"Name of the plugin", "\\w+" , true ),
PLUGIN_DESCRIPTION("pluginDescription", String.class,"Description of the plugin",".*" , true ),
PACKAGE("packagePrefix", String.class,"Default Package","[a-zA-Z\\.]+",true ),
- FILE_ROOT("fileSystemRoot", File.class,"Root directory to put the plugin",".*",true ),
+ FILE_ROOT("fileSystemRoot", File.class,"Root directory to put the plugin into",".*",true , true,null),
RHQ_VERSION("rhqVersion",String.class,"RHQ version to use","[0-9][0-9\\.]+",true),
CATEGORY("category", ResourceCategory.class, "Category of the resource type (platform = host level)",null),
TYPE_NAME("name", String.class, "Name of the resource type", "\\w+"),
DESCRIPTION("description", String.class, "Description of the type", ".*"),
- DISCOVERY_CLASS("discoveryClass", String.class, "Discovery class", "[A-Z][a-zA-Z0-9]*"),
- COMPONENT_CLASS("componentClass", String.class, "Discovery class", "[A-Z][a-zA-Z0-9]*"),
+ DISCOVERY_CLASS("discoveryClass", String.class, "Name of the Discovery class. '{name}' will be replaced with the type name", "[A-Z][a-zA-Z0-9]*",false,false,"{name}Discovery"),
+ COMPONENT_CLASS("componentClass", String.class, "Name of the Discovery class. '{name}' will be replaced with the type name", "[A-Z][a-zA-Z0-9]*",false,false,"{name}Component"),
IS_SINGLETON("singleton",boolean.class,"Is this type a singleton, which means that" +
- " there can only be one resource of that type for the given parent?",null),
- HAS_METRICS("hasMetrics",boolean.class,"Does this type support taking metrics?",null),
- HAS_OPERATIONS("hasOperations",boolean.class,"Does this type support operations?",null),
- HAS_EVENTS("events",boolean.class,"Does this type support events?",null),
- HAS_SUPPORT_FACET("supportFacet",boolean.class,"Does this type support the support facet?",null),
+ " there can only be one resource of that type for the given parent?"),
+ HAS_METRICS("hasMetrics",boolean.class,"Does this type support taking metrics?"),
+ HAS_OPERATIONS("hasOperations",boolean.class,"Does this type support operations?"),
+ HAS_EVENTS("events",boolean.class,"Does this type support events?"),
+ HAS_SUPPORT_FACET("supportFacet",boolean.class,"Does this type support the support facet?"),
RESOURCE_CONFIGURATION("resourceConfiguration",boolean.class,"Does this type support " +
- "configuring the resource?",".*"),
- CAN_CREATE_CHILDREN("createChildren",boolean.class,"Can the type create child resources?",null),
- CAN_DELETE_CHILDREN("deleteChildren",boolean.class,"Can the type delete child resources?",null),
-
- // TODO add the remaining properties from Prop.class
-
+ "configuring the resource?"),
+ CAN_CREATE_CHILDREN("createChildren",boolean.class,"Can the type create child resources?"),
+ CAN_DELETE_CHILDREN("deleteChildren",boolean.class,"Can the type delete child resources?"),
+ USE_EXTENAL_JARS("usesExternalJarsInPlugin",boolean.class,"Will the plugin use external jars in the plugin jar?"),
+ ALLOW_MANUAL_ADD("manualAddOfResourceType",boolean.class,"Should manually adding resource be supported?"),
+ USE_LIFECYLE_API("usePluginLifecycleListenerApi",boolean.class,"Should the plugin lifecycle api be supported?"),
+ DEPENDS_ON_JMX_PLUGIN("dependsOnJmxPlugin",boolean.class,"Does the plugin use JMX and extend the JMX Plugin?"),
+ DEPENDS_ON_AS7_PLUGIN("dependsOnAs7Plugin",boolean.class,"Does the plugin use DMR and extend the AS7 Plugin?"),
+ USE_SUPPORT_FACET("supportFacet",boolean.class,"Will the support facet be used?"),
+
+ SCAN_FOR_ANNOTATIONS("scanForAnnotations",File.class,"Directory to scan for plugin annotations to include in type",null, false,false, null)
;
private String variableName;
private Class type;
private String description;
private boolean pluginLevel;
+ private boolean directoryWriteable;
+ private String defaultValue;
private String validationRegex;
- private Prop(String variableName, Class type, String description, String validationRegex, boolean pluginLevel) {
+ private Prop(String variableName, Class type, String description, String validationRegex, boolean pluginLevel, boolean directoryWriteable, String defaultValue) {
this.variableName = variableName;
this.type = type;
this.description = description;
this.validationRegex = validationRegex;
this.pluginLevel = pluginLevel;
+ this.directoryWriteable = directoryWriteable;
+ this.defaultValue = defaultValue;
+ }
+
+ private Prop(String variableName, Class type, String description, String validationRegex, boolean pluginLevel) {
+ this(variableName,type,description,validationRegex,pluginLevel,false,null);
}
private Prop(String variableName, Class type, String description, String validationRegex) {
- this.variableName = variableName;
- this.type = type;
- this.description = description;
- this.validationRegex = validationRegex;
+ this(variableName,type,description,validationRegex,false,false,null);
+ }
+
+ private Prop(String variableName, Class type, String description) {
+ this(variableName,type,description,null,false,false,null);
}
public String getVariableName() {
@@ -111,4 +125,11 @@ public enum Prop {
return builder.toString();
}
+ public boolean isDirectoryWriteable() {
+ return directoryWriteable;
+ }
+
+ public String getDefaultValue() {
+ return defaultValue;
+ }
}
diff --git a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java
index 237f5ad..95be574 100644
--- a/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java
+++ b/modules/helpers/pluginGen/src/main/java/org/rhq/helpers/pluginGen/Props.java
@@ -18,6 +18,9 @@
*/
package org.rhq.helpers.pluginGen;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
@@ -26,6 +29,9 @@ import java.util.Set;
import org.rhq.helpers.pluginAnnotations.agent.DataType;
import org.rhq.helpers.pluginAnnotations.agent.DisplayType;
import org.rhq.helpers.pluginAnnotations.agent.Metric;
+import org.rhq.helpers.pluginAnnotations.agent.Operation;
+import org.rhq.helpers.pluginAnnotations.agent.Parameter;
+import org.rhq.helpers.pluginAnnotations.agent.RhqType;
import org.rhq.helpers.pluginAnnotations.agent.Units;
/**
@@ -33,6 +39,7 @@ import org.rhq.helpers.pluginAnnotations.agent.Units;
*
* @author Heiko W. Rupp
*/
+@SuppressWarnings("unused")
public class Props {
/** What category is this ? */
@@ -69,7 +76,7 @@ public class Props {
private boolean createChildren;
/** Can the service delete children ? */
private boolean deleteChildren;
- /** Use externals chars in the plugin jar ? */
+ /** Use externals jars in the plugin jar ? */
private boolean usesExternalJarsInPlugin;
/** Does it support manual add of children ? */
private boolean manualAddOfResourceType;
@@ -77,8 +84,12 @@ public class Props {
private boolean usePluginLifecycleListenerApi;
/** Depends on JMX plugin ? */
private boolean dependsOnJmxPlugin;
+ /** Depends on AS7 plugin ? */
+ private boolean dependsOnAs7Plugin;
+ /** Directory with java files to scan for plugin annotations */
+ private String scanForAnnotations;
/** What version of RHQ should this plugin's pom use ? */
- private String rhqVersion = "3.0.0";
+ private String rhqVersion = "4.8.0";
/** Embedded children */
private Set<Props> children = new HashSet<Props>();
@@ -336,22 +347,97 @@ public class Props {
this.runsInsides = runsInsides;
}
+ public boolean isDependsOnAs7Plugin() {
+ return dependsOnAs7Plugin;
+ }
+
+ public void setDependsOnAs7Plugin(boolean dependsOnAs7Plugin) {
+ this.dependsOnAs7Plugin = dependsOnAs7Plugin;
+ }
+
+ public String getScanForAnnotations() {
+ return scanForAnnotations;
+ }
+
+ public void setScanForAnnotations(String scanForAnnotations) {
+ this.scanForAnnotations = scanForAnnotations;
+ }
+
public void populateMetrics(List<Class> classes) {
- for (Class<?> clazz : classes) {
- Metric metricAnnot = clazz.getAnnotation(Metric.class);
- if (metricAnnot != null) {
- MetricProps metric = new MetricProps(metricAnnot.property());
+ for (Class<?> clazz : classes) {
+ for (Field field : clazz.getDeclaredFields()) {
+ Metric metricAnnot = field.getAnnotation(Metric.class);
+ addMetric(metricAnnot, field.getName());
+ }
+
+ for (Method method : clazz.getDeclaredMethods()) {
+ Metric metricAnnot = method.getAnnotation(Metric.class);
+ addMetric(metricAnnot, method.getName());
+ }
+ }
+ }
+
+ public void populateOperations(List<Class> classes) {
+ for (Class<?> clazz : classes) {
+ for (Method method : clazz.getDeclaredMethods()) {
+ Operation operationAnnot = method.getAnnotation(Operation.class);
+ if (operationAnnot != null) {
+ String property = operationAnnot.name();
+ if (property.isEmpty()) {
+ property = method.getName();
+ }
+ OperationProps op = new OperationProps(property);
+ op.setDisplayName(operationAnnot.displayName());
+ op.setDescription(operationAnnot.description());
+ RhqType type = RhqType.findType(method.getReturnType());
+ if (type != RhqType.VOID) {
+ SimpleProperty simpleProperty = new SimpleProperty(type.getRhqName());
+ op.setResult(simpleProperty);
+ }
+
+ Class[] types = method.getParameterTypes();
+ int i=0;
+ for (Annotation[] annotations : method.getParameterAnnotations() ) {
+ for (Annotation annotation : annotations) {
+ if (annotation instanceof Parameter) {
+ Parameter parameter = (Parameter) annotation;
+ SimpleProperty simpleProperty = new SimpleProperty(parameter.name());
+ simpleProperty.setDescription(parameter.description());
+ Class typeClass = types[i];
+ RhqType rhqType = RhqType.findType(typeClass);
+ if (parameter.type()!=RhqType.VOID){
+ rhqType = parameter.type();
+ }
+ simpleProperty.setType(rhqType.getRhqName());
+ op.getParams().add(simpleProperty);
+ }
+ }
+ i++;
+ }
+ operations.add(op);
+ }
+
+ }
+ }
+ }
+
+ private void addMetric(Metric metricAnnot, String name) {
+ if (metricAnnot != null) {
+ String property = metricAnnot.property();
+ if (property.isEmpty()) {
+ property = name;
+ }
+ MetricProps metric = new MetricProps(property);
metric.setDisplayName(metricAnnot.displayName());
metric.setDisplayType(metricAnnot.displayType());
metric.setDataType(metricAnnot.dataType());
metric.setDescription(metricAnnot.description());
+ metric.setUnits(metricAnnot.units());
metrics.add(metric);
- }
-
- }
- }
+ }
+ }
- @Override
+ @Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Props");
@@ -387,7 +473,7 @@ public class Props {
return sb.toString();
}
- public static class TypeKey {
+ public static class TypeKey {
private String name;
private String pluginName;
diff --git a/modules/helpers/pluginGen/src/main/resources/component.ftl b/modules/helpers/pluginGen/src/main/resources/component.ftl
index 1b3dda1..b445008 100644
--- a/modules/helpers/pluginGen/src/main/resources/component.ftl
+++ b/modules/helpers/pluginGen/src/main/resources/component.ftl
@@ -187,7 +187,6 @@ public class ${props.componentClass} implements ResourceComponent<#if props.pare
<#if props.operations??>
-
public void startOperationFacet(OperationContext context) {
}
@@ -203,6 +202,13 @@ public class ${props.componentClass} implements ResourceComponent<#if props.pare
public OperationResult invokeOperation(String name, Configuration params) throws Exception {
OperationResult res = new OperationResult();
+<#if props.operations?has_content>
+ <#list props.operations as operation>
+ if (name.equals("${operation.name}") {
+ // TODO implement me
+ }
+ </#list>
+<#else>
if ("dummyOperation".equals(name)) {
// TODO implement me
@@ -210,6 +216,7 @@ public class ${props.componentClass} implements ResourceComponent<#if props.pare
return res;
}
</#if>
+</#if>
<#if props.resourceConfiguration>
diff --git a/modules/helpers/pluginGen/src/main/resources/descriptor.ftl b/modules/helpers/pluginGen/src/main/resources/descriptor.ftl
index 85195e8..1fe2a6b 100644
--- a/modules/helpers/pluginGen/src/main/resources/descriptor.ftl
+++ b/modules/helpers/pluginGen/src/main/resources/descriptor.ftl
@@ -1,7 +1,7 @@
<#--
/*
* RHQ Management Platform
- * Copyright (C) 2005-2008 Red Hat, Inc.
+ * Copyright (C) 2005-2013 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -38,6 +38,9 @@
<#if props.dependsOnJmxPlugin>
<depends plugin="JMX" useClasses="true"/>
</#if>
+<#if props.dependsOnAs7Plugin>
+ <depends plugin="JBossAS7" useClasses="true"/>
+</#if>
<${props.category.lowerName} <#include "descriptorMain.ftl"/>
diff --git a/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl b/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl
index b650f7a..5579806 100644
--- a/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl
+++ b/modules/helpers/pluginGen/src/main/resources/descriptorMain.ftl
@@ -1,7 +1,7 @@
<#--
/*
* RHQ Management Platform
- * Copyright (C) 2005-2010 Red Hat, Inc.
+ * Copyright (C) 2005-2013 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -39,6 +39,11 @@ name="${props.name}"
</#list>
</runs-inside>
</#if>
+ <#if props.dependsOnAs7Plugin>
+ <runs-inside> <!-- TODO adjust type -->
+ <parent-resource-type name="JBossAS7 Standalone Server" plugin="JBossAS7"/>
+ </runs-inside>
+ </#if>
<#if props.simpleProps?has_content>
<plugin-configuration>
@@ -57,14 +62,14 @@ name="${props.name}"
</plugin-configuration>
</#if>
- <#if props.hasOperations>
+ <#if props.hasOperations || props.operations?has_content>
<#if props.operations?has_content>
<#list props.operations as operation>
- <operation name="${operation.name}" displayName="${operation.displayName}" description="${operation.description}">
+ <operation name="${operation.name}" <#if operation.displayName?has_content>displayName="${operation.displayName}"</#if> description="${operation.description}">
<#if operation.params?has_content>
<parameters>
<#list operation.params as param>
- <c:simple-property name="${param.name}" <#if param.description??>description="${param.description}"</#if>/>
+ <c:simple-property name="${param.name}" <#if param.description??>description="${param.description}"</#if> type="${param.type}"/>
</#list>
</parameters>
</#if>
@@ -82,10 +87,10 @@ name="${props.name}"
</#if>
</#if>
- <#if props.hasMetrics>
+ <#if props.hasMetrics || props.metrics?has_content>
<#if props.metrics?has_content>
<#list props.metrics as metric>
- <metric property="${metric.property}" displayName="${metric.displayName}" displayType="${metric.displayType}" units="${metric.units}" dataType="${metric.dataType}"
+ <metric property="${metric.property}" <#if metric.displayName?has_content>displayName="${metric.displayName}"</#if> displayType="${metric.displayType}" units="${metric.units}" dataType="${metric.dataType}"
description="${metric.description}" />
</#list>
<#else>
diff --git a/modules/helpers/pluginGen/src/main/resources/pom.ftl b/modules/helpers/pluginGen/src/main/resources/pom.ftl
index 01daca1..7c799b8 100644
--- a/modules/helpers/pluginGen/src/main/resources/pom.ftl
+++ b/modules/helpers/pluginGen/src/main/resources/pom.ftl
@@ -2,7 +2,7 @@
<#--
/*
* RHQ Management Platform
- * Copyright (C) 2005-20012 Red Hat, Inc.
+ * Copyright (C) 2005-20013 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -35,10 +35,10 @@
</parent>
<groupId>org.rhq</groupId>
- <artifactId>${props.name}-plugin</artifactId>
+ <artifactId>${props.pluginName}-plugin</artifactId>
<packaging>jar</packaging>
- <name>RHQ ${props.name} Plugin</name>
+ <name>RHQ ${props.pluginName} Plugin</name>
<#if props.description??>
<description>${props.description}</description>
</#if>
@@ -86,7 +86,6 @@
</executions>
</plugin>
</#if>
-
</plugins>
</build>
@@ -232,6 +231,14 @@
<scope>provided</scope>
</dependency>
</#if>
+<#if props.dependsOnAs7Plugin>
+ <dependency>
+ <groupId>org.rhq</groupId>
+ <artifactId>rhq-jboss-as-7-plugin</artifactId>
+ <version>${r"${project.version}"}</version>
+ <scope>provided</scope>
+ </dependency>
+</#if>
<!-- TODO add your dependencies here -->
diff --git a/modules/helpers/pluginGen/src/test/java/org/rhq/helpers/pluginGen/test/FooBean.java b/modules/helpers/pluginGen/src/test/java/org/rhq/helpers/pluginGen/test/FooBean.java
new file mode 100644
index 0000000..fbc571b
--- /dev/null
+++ b/modules/helpers/pluginGen/src/test/java/org/rhq/helpers/pluginGen/test/FooBean.java
@@ -0,0 +1,55 @@
+/*
+ * 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.helpers.pluginGen.test;
+
+import org.rhq.helpers.pluginAnnotations.agent.DataType;
+import org.rhq.helpers.pluginAnnotations.agent.DisplayType;
+import org.rhq.helpers.pluginAnnotations.agent.MeasurementType;
+import org.rhq.helpers.pluginAnnotations.agent.Metric;
+import org.rhq.helpers.pluginAnnotations.agent.Operation;
+import org.rhq.helpers.pluginAnnotations.agent.Parameter;
+import org.rhq.helpers.pluginAnnotations.agent.RhqType;
+
+/**
+ * Just a sample
+ * @author Heiko W. Rupp
+ */
+
+public class FooBean {
+
+ @Metric(description = "How often was this bean invoked", displayType = DisplayType.SUMMARY, measurementType = MeasurementType.DYNAMIC)
+ int invocationCount;
+
+ @Metric(description = "Just a foo", dataType = DataType.TRAIT)
+ String lastCommand;
+
+ @Operation(description = "Increase the invocation count")
+ public int increaseCounter() {
+ invocationCount++;
+ return invocationCount;
+ }
+
+ @Operation(description = "Decrease the counter")
+ public void decreaseCounter(@Parameter(description = "How much to decrease?", name = "by") int by) {
+ invocationCount -= by;
+ }
+
+
+}
10 years, 11 months
[rhq] Branch 'mtho11/consolidated-metrics' - 2 commits - modules/enterprise
by mike thompson
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java | 152 -------
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsTableView.java | 177 ++------
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/ResourceMetricAvailabilityView.java | 208 ++++++++++
3 files changed, 278 insertions(+), 259 deletions(-)
New commits:
commit 9cd21d169957e369a2b57972face734491f84d07
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Tue Jul 16 15:01:37 2013 -0700
Consolidated Metrics - Add availability detail panel.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java
index 25603fe..9273e0b 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java
@@ -58,13 +58,14 @@ public class MetricsResourceView extends AbstractD3GraphListView {
private Img expandCollapseArrow;
private MetricsTableView metricsTableView;
private MetricsViewDataSource dataSource;
- private EnhancedHLayout availabilityDetails;
+ private ResourceMetricAvailabilityView availabilityDetails;
public MetricsResourceView(Resource resource) {
super();
this.resource = resource;
dataSource = new MetricsViewDataSource(resource);
metricsTableView = new MetricsTableView(resource, this);
+ availabilityDetails = new ResourceMetricAvailabilityView(resource);
}
private EnhancedHLayout createAvailabilityDetails() {
@@ -115,7 +116,6 @@ public class MetricsResourceView extends AbstractD3GraphListView {
}
});
- availabilityDetails = createAvailabilityDetails();
availabilityGraph = new AvailabilityD3GraphView<AvailabilityOverUnderGraphType>(
new AvailabilityOverUnderGraphType(resource.getId()));
@@ -123,6 +123,7 @@ public class MetricsResourceView extends AbstractD3GraphListView {
expandCollapseHLayout.addMember(expandCollapseArrow);
expandCollapseHLayout.addMember(availabilityGraph);
vLayout.addMember(expandCollapseHLayout);
+ availabilityDetails.hide();
vLayout.addMember(availabilityDetails);
metricsTableView.setHeight100();
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/ResourceMetricAvailabilityView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/ResourceMetricAvailabilityView.java
new file mode 100644
index 0000000..9d6b892
--- /dev/null
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/ResourceMetricAvailabilityView.java
@@ -0,0 +1,208 @@
+/*
+ * RHQ Management Platform
+ * Copyright 2012, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * 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.resource.detail.monitoring.table;
+
+import com.google.gwt.user.client.rpc.AsyncCallback;
+import com.smartgwt.client.widgets.form.DynamicForm;
+import com.smartgwt.client.widgets.form.fields.FormItem;
+import com.smartgwt.client.widgets.form.fields.StaticTextItem;
+
+import org.rhq.core.domain.measurement.MeasurementUnits;
+import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.composite.ResourceAvailabilitySummary;
+import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter;
+import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
+import org.rhq.enterprise.gui.coregui.client.util.MeasurementConverterClient;
+import org.rhq.enterprise.gui.coregui.client.util.enhanced.EnhancedVLayout;
+
+/**
+ * This shows the availability history for a resource.
+ *
+ * @author Jay Shaughnessy
+ * @author John Mazzitelli
+ * @author Mike Thompson
+ */
+public class ResourceMetricAvailabilityView extends EnhancedVLayout {
+
+ private Resource resource;
+ private StaticTextItem currentField;
+ private StaticTextItem availField;
+ private StaticTextItem availTimeField;
+ private StaticTextItem downField;
+ private StaticTextItem downTimeField;
+ private StaticTextItem disabledField;
+ private StaticTextItem disabledTimeField;
+ private StaticTextItem failureCountField;
+ private StaticTextItem disabledCountField;
+ private StaticTextItem mtbfField;
+ private StaticTextItem mttrField;
+ private StaticTextItem unknownField;
+ private StaticTextItem currentTimeField;
+
+ public ResourceMetricAvailabilityView(Resource resource) {
+ super();
+
+ this.resource = resource;
+
+ setWidth100();
+ setHeight(165);
+ }
+
+ @Override
+ protected void onInit() {
+ super.onInit();
+
+ addMember(createSummaryForm());
+ }
+
+ private DynamicForm createSummaryForm() {
+ DynamicForm form = new DynamicForm();
+ form.setWidth100();
+ form.setAutoHeight();
+ form.setMargin(10);
+ form.setNumCols(4);
+
+ // row 1
+ currentField = new StaticTextItem("current", MSG.view_resource_monitor_availability_currentStatus());
+ currentField.setWrapTitle(false);
+ currentField.setColSpan(4);
+
+ // row 2
+ availField = new StaticTextItem("avail", MSG.view_resource_monitor_availability_availability());
+ availField.setWrapTitle(false);
+ prepareTooltip(availField, MSG.view_resource_monitor_availability_availability_tooltip());
+
+ availTimeField = new StaticTextItem("availTime", MSG.view_resource_monitor_availability_uptime());
+ availTimeField.setWrapTitle(false);
+ prepareTooltip(availTimeField, MSG.view_resource_monitor_availability_uptime_tooltip());
+
+ // row 3
+ downField = new StaticTextItem("down", MSG.view_resource_monitor_availability_down());
+ downField.setWrapTitle(false);
+ prepareTooltip(downField, MSG.view_resource_monitor_availability_down_tooltip());
+
+ downTimeField = new StaticTextItem("downTime", MSG.view_resource_monitor_availability_downtime());
+ downTimeField.setWrapTitle(false);
+ prepareTooltip(downTimeField, MSG.view_resource_monitor_availability_downtime_tooltip());
+
+ // row 4
+ disabledField = new StaticTextItem("disabled", MSG.view_resource_monitor_availability_disabled());
+ disabledField.setWrapTitle(false);
+ prepareTooltip(disabledField, MSG.view_resource_monitor_availability_disabled_tooltip());
+
+ disabledTimeField = new StaticTextItem("disabledTime", MSG.view_resource_monitor_availability_disabledTime());
+ disabledTimeField.setWrapTitle(false);
+ prepareTooltip(disabledTimeField, MSG.view_resource_monitor_availability_disabledTime_tooltip());
+
+ // row 5
+ failureCountField = new StaticTextItem("failureCount", MSG.view_resource_monitor_availability_numFailures());
+ failureCountField.setWrapTitle(false);
+ prepareTooltip(failureCountField, MSG.view_resource_monitor_availability_numFailures_tooltip());
+
+ disabledCountField = new StaticTextItem("disabledCount", MSG.view_resource_monitor_availability_numDisabled());
+ disabledCountField.setWrapTitle(false);
+ prepareTooltip(disabledCountField, MSG.view_resource_monitor_availability_numDisabled_tooltip());
+
+ // row 6
+ mtbfField = new StaticTextItem("mtbf", MSG.view_resource_monitor_availability_mtbf());
+ mtbfField.setWrapTitle(false);
+ prepareTooltip(mtbfField, MSG.view_resource_monitor_availability_mtbf_tooltip());
+
+ mttrField = new StaticTextItem("mttr", MSG.view_resource_monitor_availability_mttr());
+ mttrField.setWrapTitle(false);
+ prepareTooltip(mttrField, MSG.view_resource_monitor_availability_mttr_tooltip());
+
+ // row 7
+ unknownField = new StaticTextItem("unknown");
+ unknownField.setWrapTitle(false);
+ unknownField.setColSpan(4);
+ unknownField.setShowTitle(false);
+
+ // row 8
+ currentTimeField = new StaticTextItem("currentTime");
+ currentTimeField.setWrapTitle(false);
+ currentTimeField.setColSpan(4);
+ currentTimeField.setShowTitle(false);
+
+ form.setItems(currentField, availField, availTimeField, downField, downTimeField, disabledField,
+ disabledTimeField, failureCountField, disabledCountField, mtbfField, mttrField, unknownField,
+ currentTimeField);
+
+ reloadSummaryData();
+
+ return form;
+ }
+
+ private void reloadSummaryData() {
+ GWTServiceLookup.getResourceService().getResourceAvailabilitySummary(resource.getId(),
+ new AsyncCallback<ResourceAvailabilitySummary>() {
+
+ @Override
+ public void onSuccess(ResourceAvailabilitySummary result) {
+
+ currentField.setValue(MSG.view_resource_monitor_availability_currentStatus_value(result
+ .getCurrent().getName(), TimestampCellFormatter.format(result.getLastChange().getTime())));
+ availField.setValue(MeasurementConverterClient.format(result.getUpPercentage(),
+ MeasurementUnits.PERCENTAGE, true));
+ availTimeField.setValue(MeasurementConverterClient.format((double) result.getUpTime(),
+ MeasurementUnits.MILLISECONDS, true));
+ downField.setValue(MeasurementConverterClient.format(result.getDownPercentage(),
+ MeasurementUnits.PERCENTAGE, true));
+ downTimeField.setValue(MeasurementConverterClient.format((double) result.getDownTime(),
+ MeasurementUnits.MILLISECONDS, true));
+ disabledField.setValue(MeasurementConverterClient.format(result.getDisabledPercentage(),
+ MeasurementUnits.PERCENTAGE, true));
+ disabledTimeField.setValue(MeasurementConverterClient.format((double) result.getDisabledTime(),
+ MeasurementUnits.MILLISECONDS, true));
+ failureCountField.setValue(result.getFailures());
+ disabledCountField.setValue(result.getDisabled());
+ mtbfField.setValue(MeasurementConverterClient.format((double) result.getMTBF(),
+ MeasurementUnits.MILLISECONDS, true));
+ mttrField.setValue(MeasurementConverterClient.format((double) result.getMTTR(),
+ MeasurementUnits.MILLISECONDS, true));
+
+ if (result.getUnknownTime() > 0L) {
+ unknownField.setValue(MSG.view_resource_monitor_availability_unknown(MeasurementConverterClient
+ .format((double) result.getUnknownTime(), MeasurementUnits.MILLISECONDS, true)));
+ } else {
+ unknownField.setValue("");
+ }
+
+ currentTimeField.setValue(MSG.view_resource_monitor_availability_currentAsOf(TimestampCellFormatter
+ .format(result.getCurrentTime())));
+ }
+
+ @Override
+ public void onFailure(Throwable caught) {
+ currentField.setValue(MSG.common_label_error());
+ CoreGUI.getErrorHandler()
+ .handleError(MSG.view_resource_monitor_availability_summaryError(), caught);
+ }
+ });
+ }
+
+ private void prepareTooltip(FormItem item, String tooltip) {
+ item.setHoverWidth(400);
+ item.setPrompt(tooltip);
+ }
+
+}
commit 46d64c5f157d18d2778fdec15909e25226513b6d
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Tue Jul 16 08:50:36 2013 -0700
Consolidated Metrics - more availability work.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java
index e4785da..25603fe 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsResourceView.java
@@ -18,43 +18,27 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.table;
-import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Set;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
-import com.smartgwt.client.types.ExpansionMode;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.VerticalAlignment;
-import com.smartgwt.client.widgets.Canvas;
-import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
-import com.smartgwt.client.widgets.grid.ListGrid;
-import com.smartgwt.client.widgets.grid.ListGridField;
-import com.smartgwt.client.widgets.grid.ListGridRecord;
-import com.smartgwt.client.widgets.grid.events.RecordExpandEvent;
-import com.smartgwt.client.widgets.grid.events.RecordExpandHandler;
import com.smartgwt.client.widgets.layout.VLayout;
import org.rhq.core.domain.common.EntityContext;
import org.rhq.core.domain.measurement.Availability;
-import org.rhq.core.domain.measurement.MeasurementDefinition;
-import org.rhq.core.domain.measurement.composite.MeasurementDataNumericHighLowComposite;
import org.rhq.core.domain.resource.Resource;
-import org.rhq.core.domain.resource.ResourceType;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
import org.rhq.enterprise.gui.coregui.client.IconEnum;
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.graph.graphtype.AvailabilityOverUnderGraphType;
-import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.MetricD3Graph;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.avail.AvailabilityD3GraphView;
-import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility;
import org.rhq.enterprise.gui.coregui.client.util.Log;
import org.rhq.enterprise.gui.coregui.client.util.async.CountDownLatch;
import org.rhq.enterprise.gui.coregui.client.util.enhanced.EnhancedHLayout;
@@ -70,40 +54,17 @@ public class MetricsResourceView extends AbstractD3GraphListView {
private static final String EXPANDED_TOOLTIP = MSG.chart_metrics_expand_tooltip();
private Resource resource;
- private Set<Integer> definitionIds = null;
private VLayout vLayout;
private Img expandCollapseArrow;
- MetricsTableListGrid metricsGrid;
- MetricsViewDataSource dataSource;
- EnhancedHLayout availabilityDetails;
-
+ private MetricsTableView metricsTableView;
+ private MetricsViewDataSource dataSource;
+ private EnhancedHLayout availabilityDetails;
public MetricsResourceView(Resource resource) {
super();
this.resource = resource;
dataSource = new MetricsViewDataSource(resource);
- metricsGrid = new MetricsTableListGrid();
-
- ArrayList<ListGridField> fields = dataSource.getListGridFields();
- metricsGrid.setFields(fields.toArray(new ListGridField[0]));
- metricsGrid.setCanExpandRecords(true);
- metricsGrid.addRecordExpandHandler(new RecordExpandHandler() {
- @Override
- public void onRecordExpand(RecordExpandEvent recordExpandEvent) {
- Log.debug("Record Expanded: "
- + recordExpandEvent.getRecord().getAttribute(MetricsViewDataSource.FIELD_METRIC_LABEL));
- new Timer() {
-
- @Override
- public void run() {
- BrowserUtility.graphSparkLines();
- }
- }.schedule(150);
-
- }
-
- });
-
+ metricsTableView = new MetricsTableView(resource, this);
}
private EnhancedHLayout createAvailabilityDetails() {
@@ -123,11 +84,10 @@ public class MetricsResourceView extends AbstractD3GraphListView {
Log.debug("MetricResourceView.onDraw() for: " + resource.getName() + " id: " + resource.getId());
destroyMembers();
-
vLayout = new VLayout();
vLayout.setOverflow(Overflow.AUTO);
vLayout.setWidth100();
- vLayout.setHeight(220);
+ vLayout.setHeight100();
vLayout.addMember(buttonBarDateTimeRangeEditor);
EnhancedHLayout expandCollapseHLayout = new EnhancedHLayout();
@@ -146,8 +106,7 @@ public class MetricsResourceView extends AbstractD3GraphListView {
expandCollapseArrow.setSrc(IconEnum.COLLAPSED_ICON.getIcon16x16Path());
expandCollapseArrow.setTooltip(COLLAPSED_TOOLTIP);
availabilityDetails.hide();
- }
- else {
+ } else {
expandCollapseArrow.setSrc(IconEnum.EXPANDED_ICON.getIcon16x16Path());
expandCollapseArrow.setTooltip(EXPANDED_TOOLTIP);
availabilityDetails.show();
@@ -166,13 +125,14 @@ public class MetricsResourceView extends AbstractD3GraphListView {
vLayout.addMember(expandCollapseHLayout);
vLayout.addMember(availabilityDetails);
- vLayout.addMember(metricsGrid);
+ metricsTableView.setHeight100();
+ vLayout.addMember(metricsTableView);
addMember(vLayout);
if (resource != null) {
queryAvailability(EntityContext.forResource(resource.getId()), buttonBarDateTimeRangeEditor.getStartTime(),
- buttonBarDateTimeRangeEditor.getEndTime(), null);
+ buttonBarDateTimeRangeEditor.getEndTime(), null);
}
}
@@ -212,95 +172,4 @@ public class MetricsResourceView extends AbstractD3GraphListView {
});
}
- private class MetricsTableListGrid extends ListGrid {
- public MetricsTableListGrid() {
- super();
-
- setCanExpandRecords(true);
- setCanExpandMultipleRecords(true);
- setExpansionMode(ExpansionMode.DETAIL_FIELD);
- }
-
- @Override
- protected Canvas getExpansionComponent(final ListGridRecord record) {
- final Integer definitionId = record.getAttributeAsInt(MetricsViewDataSource.FIELD_METRIC_DEF_ID);
- final Integer resourceId = record.getAttributeAsInt(MetricsViewDataSource.FIELD_RESOURCE_ID);
- VLayout vLayout = new VLayout();
- vLayout.setPadding(5);
-
- final String chartId = "rChart" + resourceId + "-" + definitionId;
- HTMLFlow htmlFlow = new HTMLFlow(MetricD3Graph.createGraphMarkerTemplate(chartId, 200));
- vLayout.addMember(htmlFlow);
-
- new Timer() {
-
- @Override
- public void run() {
- BrowserUtility.graphSparkLines();
- }
- }.schedule(150);
-
-
- // Load the fully fetched ResourceType.
- ResourceType resourceType = resource.getResourceType();
-
- Set<MeasurementDefinition> definitions = resourceType.getMetricDefinitions();
- final MeasurementDefinition measurementDefinition;
-
- //build id mapping for measurementDefinition instances Ex. Free Memory -> MeasurementDefinition[100071]
- final HashMap<String, MeasurementDefinition> measurementDefMap = new HashMap<String, MeasurementDefinition>();
- for (MeasurementDefinition definition : definitions) {
- measurementDefMap.put(definition.getDisplayName(), definition);
- if (definition.getId() == definitionId) {
- measurementDefinition = definition;
- break;
- }
- }
-
- int[] definitionArrayIds = new int[1];
- definitionArrayIds[0] = definitionId;
- GWTServiceLookup.getMeasurementDataService().findDataForResource(resourceId, definitionArrayIds,
- measurementUserPrefs.getMetricRangePreferences().begin,
- measurementUserPrefs.getMetricRangePreferences().end, 60,
- new AsyncCallback<List<List<MeasurementDataNumericHighLowComposite>>>() {
- @Override
- public void onFailure(Throwable caught) {
- Log.debug("Error retrieving recent metrics charting data for resource [" + resourceId + "]:"
- + caught.getMessage());
- }
-
- @Override
- public void onSuccess(List<List<MeasurementDataNumericHighLowComposite>> results) {
- if (!results.isEmpty()) {
-
- //load the data results for the given metric definition
- List<MeasurementDataNumericHighLowComposite> data = results.get(0);
- Log.debug(" *** Metric Data Results: "+data.size());
-
-// MetricGraphData metricGraphData = MetricGraphData
-// .createForResource(resourceId, resource.getName(),
-// measurementDefinition, data, null);
-//
-// StackedBarMetricGraphImpl graph = GWT
-// .create(StackedBarMetricGraphImpl.class);
-// graph.setMetricGraphData(metricGraphData);
-// final MetricD3Graph graphView = new MetricD3Graph(graph, this);
-// new Timer() {
-// @Override
-// public void run() {
-// graphView.drawJsniChart();
-//
-// }
-// }.schedule(150);
-
- } else {
- Log.warn("No chart data retrieving for resource [" + resourceId + "]");
-
- }
- }
- });
-
- return vLayout;
- }
- }
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsTableView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsTableView.java
index 82fe2d2..3cb9233 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsTableView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/monitoring/table/MetricsTableView.java
@@ -22,7 +22,6 @@ package org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitori
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
-import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -45,26 +44,21 @@ import com.smartgwt.client.widgets.grid.events.RecordExpandEvent;
import com.smartgwt.client.widgets.grid.events.RecordExpandHandler;
import com.smartgwt.client.widgets.layout.VLayout;
-import org.rhq.core.domain.criteria.ResourceCriteria;
import org.rhq.core.domain.measurement.MeasurementData;
import org.rhq.core.domain.measurement.MeasurementDefinition;
import org.rhq.core.domain.measurement.MeasurementUnits;
import org.rhq.core.domain.measurement.composite.MeasurementDataNumericHighLowComposite;
import org.rhq.core.domain.resource.Resource;
-import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.core.domain.resource.composite.ResourceComposite;
-import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
import org.rhq.enterprise.gui.coregui.client.UserSessionManager;
import org.rhq.enterprise.gui.coregui.client.components.table.Table;
import org.rhq.enterprise.gui.coregui.client.components.table.TableAction;
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
-import org.rhq.enterprise.gui.coregui.client.inventory.common.graph.ButtonBarDateTimeRangeEditor;
+import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractD3GraphListView;
import org.rhq.enterprise.gui.coregui.client.inventory.common.graph.MetricGraphData;
import org.rhq.enterprise.gui.coregui.client.inventory.common.graph.RedrawGraphs;
import org.rhq.enterprise.gui.coregui.client.inventory.common.graph.graphtype.StackedBarMetricGraphImpl;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.detail.monitoring.MetricD3Graph;
-import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository;
import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility;
import org.rhq.enterprise.gui.coregui.client.util.Log;
import org.rhq.enterprise.gui.coregui.client.util.MeasurementConverterClient;
@@ -76,20 +70,19 @@ import org.rhq.enterprise.gui.coregui.client.util.preferences.MeasurementUserPre
* @author John Mazzitelli
* @author Mike Thompson
*/
-@Deprecated
-public class MetricsTableView extends Table<MetricsTableDataSource> implements RedrawGraphs {
+public class MetricsTableView extends Table<MetricsViewDataSource> implements RedrawGraphs {
- private final int resourceId;
+ private final Resource resource;
+ private final AbstractD3GraphListView abstractD3GraphListView;
private MeasurementUserPreferences measurementUserPrefs;
- private ButtonBarDateTimeRangeEditor buttonBarDateTimeRangeEditor;
- public MetricsTableView(int resourceId) {
+ public MetricsTableView(Resource resource, AbstractD3GraphListView abstractD3GraphListView) {
super();
- this.resourceId = resourceId;
- setDataSource(new MetricsTableDataSource(resourceId));
+ this.resource = resource;
+ this.abstractD3GraphListView = abstractD3GraphListView;
+ setDataSource(new MetricsViewDataSource(resource));
measurementUserPrefs = new MeasurementUserPreferences(UserSessionManager.getUserPreferences());
- buttonBarDateTimeRangeEditor = new ButtonBarDateTimeRangeEditor(measurementUserPrefs, this);
}
/**
@@ -100,7 +93,7 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
*/
@Override
protected ListGrid createListGrid() {
- return new MetricsTableListGrid();
+ return new MetricsTableListGrid(resource);
}
protected void configureTable() {
@@ -111,7 +104,7 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
@Override
public void onRecordExpand(RecordExpandEvent recordExpandEvent) {
Log.debug("Record Expanded: "
- + recordExpandEvent.getRecord().getAttribute(MetricsTableDataSource.FIELD_METRIC_LABEL));
+ + recordExpandEvent.getRecord().getAttribute(MetricsViewDataSource.FIELD_METRIC_LABEL));
new Timer() {
@Override
@@ -124,9 +117,8 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
});
- addExtraWidget(buttonBarDateTimeRangeEditor, true);
addTableAction(MSG.view_measureTable_getLive(), new ShowLiveDataTableAction(this));
- addTableAction(MSG.view_measureTable_addToDashboard(), new AddToDashboardTableAction(this));
+ //addTableAction(MSG.view_measureTable_addToDashboard(), new AddToDashboardTableAction(this));
}
@@ -152,12 +144,12 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
int[] definitionIds = new int[selection.length];
int i = 0;
for (ListGridRecord record : selection) {
- Integer defId = record.getAttributeAsInt(MetricsTableDataSource.FIELD_METRIC_DEF_ID);
+ Integer defId = record.getAttributeAsInt(MetricsViewDataSource.FIELD_METRIC_DEF_ID);
definitionIds[i++] = defId;
- String name = record.getAttribute(MetricsTableDataSource.FIELD_METRIC_NAME);
- String label = record.getAttribute(MetricsTableDataSource.FIELD_METRIC_LABEL);
- String units = record.getAttribute(MetricsTableDataSource.FIELD_METRIC_UNITS);
+ String name = record.getAttribute(MetricsViewDataSource.FIELD_METRIC_NAME);
+ String label = record.getAttribute(MetricsViewDataSource.FIELD_METRIC_LABEL);
+ String units = record.getAttribute(MetricsViewDataSource.FIELD_METRIC_UNITS);
if (units == null || units.length() < 1) {
units = MeasurementUnits.NONE.name();
}
@@ -166,8 +158,8 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
}
// actually go out and ask the agents for the data
- GWTServiceLookup.getMeasurementDataService(60000).findLiveData(metricsTableView.resourceId, definitionIds,
- new AsyncCallback<Set<MeasurementData>>() {
+ GWTServiceLookup.getMeasurementDataService(60000).findLiveData(metricsTableView.resource.getId(),
+ definitionIds, new AsyncCallback<Set<MeasurementData>>() {
@Override
public void onSuccess(Set<MeasurementData> result) {
if (result == null) {
@@ -281,9 +273,14 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
}
private class MetricsTableListGrid extends ListGrid {
- public MetricsTableListGrid() {
- super();
+ private static final int TREEVIEW_DETAIL_CHART_HEIGHT = 205;
+ private static final int NUM_METRIC_POINTS = 60;
+ private Resource resource;
+
+ public MetricsTableListGrid(Resource resource) {
+ super();
+ this.resource = resource;
setCanExpandRecords(true);
setCanExpandMultipleRecords(true);
setExpansionMode(ExpansionMode.DETAIL_FIELD);
@@ -291,116 +288,60 @@ public class MetricsTableView extends Table<MetricsTableDataSource> implements R
@Override
protected Canvas getExpansionComponent(final ListGridRecord record) {
- final Integer definitionId = record.getAttributeAsInt(MetricsTableDataSource.FIELD_METRIC_DEF_ID);
- final Integer resourceId = record.getAttributeAsInt(MetricsTableDataSource.FIELD_RESOURCE_ID);
+ final Integer definitionId = record.getAttributeAsInt(MetricsViewDataSource.FIELD_METRIC_DEF_ID);
+ final Integer resourceId = record.getAttributeAsInt(MetricsViewDataSource.FIELD_RESOURCE_ID);
VLayout vLayout = new VLayout();
vLayout.setPadding(5);
- final String chartId = "rChart" + resourceId + "-" + definitionId;
- HTMLFlow htmlFlow = new HTMLFlow(MetricD3Graph.createGraphMarkerTemplate(chartId, 200));
+ final String chartId = "rChart-" + resourceId + "-" + definitionId;
+ Log.debug("getExpansionComponent for: " + chartId);
+ HTMLFlow htmlFlow = new HTMLFlow(MetricD3Graph.createGraphMarkerTemplate(chartId, TREEVIEW_DETAIL_CHART_HEIGHT));
vLayout.addMember(htmlFlow);
- //locate resource reference
- ResourceCriteria criteria = new ResourceCriteria();
- criteria.addFilterId(resourceId);
-
- //locate the resource
- GWTServiceLookup.getResourceService().findResourceCompositesByCriteria(criteria,
- new AsyncCallback<PageList<ResourceComposite>>() {
+ int[] definitionArrayIds = new int[1];
+ definitionArrayIds[0] = definitionId;
+ GWTServiceLookup.getMeasurementDataService().findDataForResource(resourceId, definitionArrayIds,
+ measurementUserPrefs.getMetricRangePreferences().begin,
+ measurementUserPrefs.getMetricRangePreferences().end, NUM_METRIC_POINTS,
+ new AsyncCallback<List<List<MeasurementDataNumericHighLowComposite>>>() {
@Override
public void onFailure(Throwable caught) {
- Log.debug("Error retrieving resource resource composite for resource [" + resourceId + "]:"
+ Log.debug("Error retrieving recent metrics charting data for resource [" + resourceId + "]:"
+ caught.getMessage());
}
@Override
- public void onSuccess(PageList<ResourceComposite> results) {
+ public void onSuccess(List<List<MeasurementDataNumericHighLowComposite>> results) {
if (!results.isEmpty()) {
- new Timer() {
+ //load the data results for the given metric definition
+ List<MeasurementDataNumericHighLowComposite> measurementList = results.get(0);
+ Log.debug("getExpansionComponent MeasurementList.size: " + measurementList.size());
+ MeasurementDefinition measurementDefinition = null;
+ for (MeasurementDefinition definition : resource.getResourceType().getMetricDefinitions()) {
+ if (definition.getId() == definitionId) {
+ measurementDefinition = definition;
+ break;
+ }
+ }
+
+ MetricGraphData metricGraphData = MetricGraphData.createForResource(resourceId,
+ resource.getName(), measurementDefinition, measurementList, null);
+
+ StackedBarMetricGraphImpl graph = GWT.create(StackedBarMetricGraphImpl.class);
+ graph.setMetricGraphData(metricGraphData);
+ final MetricD3Graph graphView = new MetricD3Graph(graph, abstractD3GraphListView);
+ new Timer() {
@Override
public void run() {
- BrowserUtility.graphSparkLines();
+ graphView.drawJsniChart();
+
}
}.schedule(150);
- final Resource resource = results.get(0).getResource();
- //D3GraphListView graphListView = D3GraphListView.createSingleGraph(resource, definitionId, false);
-
- // Load the fully fetched ResourceType.
- ResourceType resourceType = resource.getResourceType();
- ResourceTypeRepository.Cache.getInstance().getResourceTypes(
- resourceType.getId(),
- EnumSet.of(ResourceTypeRepository.MetadataType.content,
- ResourceTypeRepository.MetadataType.operations,
- ResourceTypeRepository.MetadataType.measurements,
- ResourceTypeRepository.MetadataType.events,
- ResourceTypeRepository.MetadataType.resourceConfigurationDefinition),
- new ResourceTypeRepository.TypeLoadedCallback() {
- public void onTypesLoaded(ResourceType type) {
- resource.setResourceType(type);
- //metric definitions
- Set<MeasurementDefinition> definitions = type.getMetricDefinitions();
- final MeasurementDefinition measurementDefinition;
-
- //build id mapping for measurementDefinition instances Ex. Free Memory -> MeasurementDefinition[100071]
- final HashMap<String, MeasurementDefinition> measurementDefMap = new HashMap<String, MeasurementDefinition>();
- for (MeasurementDefinition definition : definitions) {
- measurementDefMap.put(definition.getDisplayName(), definition);
- if (definition.getId() == definitionId) {
- measurementDefinition = definition;
- break;
- }
- }
-
- int[] definitionArrayIds = new int[1];
- definitionArrayIds[0] = definitionId;
- GWTServiceLookup.getMeasurementDataService().findDataForResource(resourceId,
- definitionArrayIds, measurementUserPrefs.getMetricRangePreferences().begin,
- measurementUserPrefs.getMetricRangePreferences().end, 60,
- new AsyncCallback<List<List<MeasurementDataNumericHighLowComposite>>>() {
- @Override
- public void onFailure(Throwable caught) {
- Log.debug("Error retrieving recent metrics charting data for resource ["
- + resourceId + "]:" + caught.getMessage());
- }
-
- @Override
- public void onSuccess(
- List<List<MeasurementDataNumericHighLowComposite>> results) {
- if (!results.isEmpty()) {
-
- //load the data results for the given metric definition
- List<MeasurementDataNumericHighLowComposite> data = results
- .get(0);
-
-// MetricGraphData metricGraphData = MetricGraphData
-// .createForResource(resourceId, resource.getName(),
-// measurementDefinition, data, null);
-//
-// StackedBarMetricGraphImpl graph = GWT
-// .create(StackedBarMetricGraphImpl.class);
-// graph.setMetricGraphData(metricGraphData);
-// final MetricD3Graph graphView = new MetricD3Graph(graph, this);
-// new Timer() {
-// @Override
-// public void run() {
-// graphView.drawJsniChart();
-//
-// }
-// }.schedule(150);
-
- } else {
- Log.warn("No chart data retrieving for resource [" + resourceId
- + "]");
-
- }
- }
- });
-
- }
- });
+ } else {
+ Log.warn("No chart data retrieving for resource [" + resourceId + "-"+definitionId+"]");
}
}
10 years, 11 months