[rhq] Branch 'as7plugin' - 2 commits - modules/plugins
by Heiko W. Rupp
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java | 9
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java | 85 ++++++--
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/PluginStats.java | 61 +++++
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 103 ++++++----
4 files changed, 197 insertions(+), 61 deletions(-)
New commits:
commit 1831a12d39873b64e0f4a07be6f274fc40c4a5cb
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Thu May 26 17:57:31 2011 +0200
Add some stats on processing times.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java
index d86b365..5f350c0 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java
@@ -95,7 +95,9 @@ public class ASConnection {
InputStream inputStream = null;
BufferedReader br=null;
+ long t1 = System.currentTimeMillis();
try {
+
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
@@ -135,11 +137,10 @@ public class ASConnection {
else {
outcome="- no response from server -";
}
-// System.out.println("==> " + outcome);
return operationResult;
}
else {
- System.err.println("IS was null and code was " + responseCode);
+ log.error("IS was null and code was " + responseCode);
}
@@ -152,6 +153,10 @@ public class ASConnection {
} catch (IOException e) {
e.printStackTrace(); // TODO: Customise this generated block
}
+ long t2 = System.currentTimeMillis();
+ PluginStats stats = PluginStats.getInstance();
+ stats.incrementRequestCount();
+ stats.addRequestTime(t2-t1);
}
return null;
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
index ecb3fd6..de53386 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
@@ -77,6 +77,8 @@ import java.util.Set;
public class BaseComponent implements ResourceComponent, MeasurementFacet, ConfigurationFacet, DeleteResourceFacet,
CreateChildResourceFacet, OperationFacet
{
+ private static final String INTERNAL = "_internal:";
+ private static final int INTERNAL_SIZE = INTERNAL.length();
final Log log = LogFactory.getLog(this.getClass());
ResourceContext context;
@@ -149,31 +151,68 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
for (MeasurementScheduleRequest req : metrics) {
- Operation op = new ReadAttribute(pathToAddress(path),req.getName()); // TODO batching
- //JsonNode obj = connection.executeRaw(op);
- Result res = connection.execute(op, false);
- if (!res.isSuccess())
- continue;
-
- String val = (String) res.getResult();
-
- if (req.getDataType()== DataType.MEASUREMENT) {
- if (!val.equals("no metrics available")) { // AS 7 returns this
- try {
- Double d = Double.parseDouble(val);
- MeasurementDataNumeric data = new MeasurementDataNumeric(req,d);
- report.addData(data);
- } catch (NumberFormatException e) {
- log.warn("Non numeric input for [" + req.getName() + "] : [" + val + "]");
+ if (req.getName().startsWith(INTERNAL))
+ processPluginStats(req,report);
+ else {
+ // Metrics from the application server
+
+ Operation op = new ReadAttribute(pathToAddress(path),req.getName()); // TODO batching
+ //JsonNode obj = connection.executeRaw(op);
+ Result res = connection.execute(op, false);
+ if (!res.isSuccess())
+ continue;
+
+ String val = (String) res.getResult();
+
+ if (req.getDataType()== DataType.MEASUREMENT) {
+ if (!val.equals("no metrics available")) { // AS 7 returns this
+ try {
+ Double d = Double.parseDouble(val);
+ MeasurementDataNumeric data = new MeasurementDataNumeric(req,d);
+ report.addData(data);
+ } catch (NumberFormatException e) {
+ log.warn("Non numeric input for [" + req.getName() + "] : [" + val + "]");
+ }
}
+ } else if (req.getDataType()== DataType.TRAIT) {
+ MeasurementDataTrait data = new MeasurementDataTrait(req,val);
+ report.addData(data);
}
- } else if (req.getDataType()== DataType.TRAIT) {
- MeasurementDataTrait data = new MeasurementDataTrait(req,val);
- report.addData(data);
}
}
}
+ /**
+ * Return internal statistics data
+ * @param req Schedule for the requested data
+ * @param report report to add th data to.
+ */
+ private void processPluginStats(MeasurementScheduleRequest req, MeasurementReport report) {
+
+ String name = req.getName();
+ if (!name.startsWith(INTERNAL))
+ return;
+
+ name = name.substring(INTERNAL_SIZE);
+
+ PluginStats stats = PluginStats.getInstance();
+ MeasurementDataNumeric data;
+ Double val;
+ if (name.equals("mgmtRequests")) {
+ val= (double) stats.getRequestCount();
+ }
+ else if (name.equals("requestTime")) {
+ val =(double) stats.getRequestTime();
+ }
+ else if (name.equals("maxTime")) {
+ val = (double) stats.getMaxTime();
+ }
+ else
+ val = Double.NaN;
+
+ data = new MeasurementDataNumeric(req,val);
+ report.addData(data);
+ }
protected ASConnection getASConnection() {
return connection;
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/PluginStats.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/PluginStats.java
new file mode 100644
index 0000000..1a44dde
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/PluginStats.java
@@ -0,0 +1,61 @@
+package org.rhq.modules.plugins.jbossas7;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Singleton that keeps track of some statistics of this plugin
+ * @author Heiko W. Rupp
+ */
+public class PluginStats {
+ private static PluginStats ourInstance = new PluginStats();
+
+ AtomicLong requestCount = new AtomicLong();
+ AtomicLong requestTime = new AtomicLong();
+ private static final int FIFO_SIZE = 200; // Initial capacity
+ List<Long> maxTime = new ArrayList<Long>(FIFO_SIZE);
+ final Object lock = new Object();
+
+
+ public static PluginStats getInstance() {
+ return ourInstance;
+ }
+
+ private PluginStats() {
+ }
+
+ public void incrementRequestCount() {
+ requestCount.incrementAndGet();
+ }
+
+ public void addRequestTime(long l) {
+ requestTime.addAndGet(l);
+ insertTime(l);
+ }
+
+ public long getRequestCount() {
+ return requestCount.get();
+ }
+
+ public long getRequestTime() {
+ return requestTime.get();
+ }
+
+ public long getMaxTime() {
+ long max = 0;
+ synchronized (lock) {
+ for (Long i : maxTime)
+ if (i > max )
+ max = i;
+ maxTime = new ArrayList<Long>();
+ }
+ return max;
+ }
+
+ private void insertTime(long time) {
+ synchronized (lock) {
+ maxTime.add(time);
+ }
+ }
+}
diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
index 75484c8..64251bc 100644
--- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
@@ -135,6 +135,18 @@
</operation>
+ <metric property="_internal:mgmtRequests" category="performance" dataType="measurement" defaultInterval="120000"
+ displayType="summary" measurementType="trendsup" description="Number of requests sent to the controller"
+ displayName="Number of management requests"
+ />
+ <metric property="_internal:requestTime" category="performance" dataType="measurement" defaultInterval="120000"
+ displayType="summary" measurementType="trendsup" description="Total time for requests" units="milliseconds"
+ displayName="Time used for management requests"/>
+ <metric property="_internal:maxTime" category="performance" dataType="measurement" defaultInterval="120000"
+ displayType="summary" measurementType="dynamic" description="Max time for a request since last metric get" units="milliseconds"
+ displayName="Maximum request time"/>
+
+
<server name="Profile"
description="One profile in a domain"
discovery="SubsystemDiscovery"
@@ -237,6 +249,16 @@
<process-scan name="StandaloneAS" query="process|basename|match=^java.*,arg|org.jboss.as.standalone|match=.*"/>
+ <metric property="_internal:mgmtRequests" category="performance" dataType="measurement" defaultInterval="120000"
+ displayType="summary" measurementType="trendsup" description="Number of requests sent to the controller"
+ displayName="Number of management requests"/>
+ <metric property="_internal:requestTime" category="performance" dataType="measurement" defaultInterval="120000"
+ displayType="summary" measurementType="trendsup" description="Total time for requests" units="milliseconds"
+ displayName="Time used for management requests"/>
+ <metric property="_internal:maxTime" category="performance" dataType="measurement" defaultInterval="120000"
+ displayType="summary" measurementType="dynamic" description="Max time for a request since last metric get" units="milliseconds"
+ displayName="Maximum request time"/>
+
<resource-configuration>
<c:list-property name="schema-locations" displayName="Schema locations">
@@ -618,9 +640,9 @@
description="Should an archive validation error report fail the deployment. Default: true"/>
<c:simple-property name="archive-validation-fail-on-warn" type="boolean" readOnly="true" default="false"
description="Should an archive validation warning report fail the deployment. Default: false"/>
- <c:simple-property name="cached-connection-manager-debug" type="boolean" readOnly="true"
+ <c:simple-property name="cached-connection-manager-debug" type="boolean" readOnly="true" default="false"
description="enable/disable debug information logging for cached connection manager"/>
- <c:simple-property name="cached-connection-manager-error" type="boolean" readOnly="true"
+ <c:simple-property name="cached-connection-manager-error" type="boolean" readOnly="true" default="false"
description="enable/disable error information logging for cached connection manager"/>
</resource-configuration>
@@ -937,15 +959,15 @@
<c:simple-property name="path" required="true" type="string" readOnly="false" description="The filesystem path."/>
<c:simple-property name="relative-to" required="false" type="string" readOnly="false"
description="The name of another previously named path, or of one of the standard paths provided by the system.
- If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
- The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
- distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
- working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
- root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
- use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
- log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
- storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
- working area for individual server instances</li></ul>"/>
+If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
+The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
+distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
+working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
+root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
+use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
+log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
+storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
+working area for individual server instances</li></ul>"/>
</parameters>
</operation>
<resource-configuration>
@@ -1001,15 +1023,15 @@
<c:simple-property name="path" required="true" type="string" readOnly="false" description="The filesystem path."/>
<c:simple-property name="relative-to" required="false" type="string" readOnly="false"
description="The name of another previously named path, or of one of the standard paths provided by the system.
- If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
- The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
- distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
- working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
- root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
- use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
- log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
- storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
- working area for individual server instances</li></ul>"/>
+If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
+The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
+distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
+working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
+root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
+use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
+log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
+storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
+working area for individual server instances</li></ul>"/>
</parameters>
</operation>
<resource-configuration>
@@ -1023,14 +1045,14 @@
<c:simple-property name="append" required="false" type="boolean" readOnly="true" description="Specify whether to append to the target file."/>
<c:map-property name="file" description="null" >
<c:simple-property name="relative-to" required="false" type="string" readOnly="true" description="The name of another previously named path, or of one of the standard paths
- provided by the system. If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path
- specified by this attribute. The standard paths provided by the system include:<ul><li>jboss.home - the root directory
- of the JBoss AS distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current working
- directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir - root directory for an
- individual server instance</li><li>jboss.server.data.dir - directory the server will use for persistent data file
- storage</li><li>jboss.server.log.dir - directory the server will use for log file storage</li><li>jboss.server.tmp.dir -
- directory the server will use for temporary file storage</li><li>jboss.domain.servers.dir - directory under which a host controller
- will create the working area for individual server instances</li></ul>"/>
+provided by the system. If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path
+specified by this attribute. The standard paths provided by the system include:<ul><li>jboss.home - the root directory
+of the JBoss AS distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current working
+directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir - root directory for an
+individual server instance</li><li>jboss.server.data.dir - directory the server will use for persistent data file
+storage</li><li>jboss.server.log.dir - directory the server will use for log file storage</li><li>jboss.server.tmp.dir -
+directory the server will use for temporary file storage</li><li>jboss.domain.servers.dir - directory under which a host controller
+will create the working area for individual server instances</li></ul>"/>
<c:simple-property name="path" required="false" type="string" readOnly="true" description="The filesystem path."/>
</c:map-property>
<c:simple-property name="suffix" required="false" type="string" readOnly="true" description="Set the suffix string. The string is in a format which
@@ -1072,15 +1094,15 @@
<c:simple-property name="path" required="true" type="string" readOnly="false" description="The filesystem path."/>
<c:simple-property name="relative-to" required="false" type="string" readOnly="false"
description="The name of another previously named path, or of one of the standard paths provided by the system.
- If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
- The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
- distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
- working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
- root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
- use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
- log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
- storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
- working area for individual server instances</li></ul>"/>
+If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
+The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
+distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
+working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
+root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
+use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
+log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
+storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
+working area for individual server instances</li></ul>"/>
</parameters>
</operation>
<resource-configuration>
@@ -1157,7 +1179,12 @@
<resource-configuration>
<c:simple-property name="extends" required="false" type="string" readOnly="true" description="The parent security domain"/>
<c:simple-property name="cache-type" required="false" type="string" readOnly="true"
- description="Adds a cache to speed up authentication checks. Allowed values are 'default' to use simple map as the cache and 'infinispan' to use an Infinispan cache."/>
+ description="Adds a cache to speed up authentication checks. Allowed values are 'default' to use simple map as the cache and 'infinispan' to use an Infinispan cache.">
+ <c:property-options>
+ <c:option value="default"/>
+ <c:option value="infinispan"/>
+ </c:property-options>
+ </c:simple-property>
</resource-configuration>
</service>
commit 7a7c767c359f82a92056ad4a92ca8cc363ab9bcc
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 25 13:21:43 2011 +0200
Get availability by checking if the resource is readable.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
index f35720e..ecb3fd6 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
@@ -93,8 +93,11 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
* @see org.rhq.core.pluginapi.inventory.ResourceComponent#getAvailability()
*/
public AvailabilityType getAvailability() {
- // TODO supply real implementation
- return AvailabilityType.UP;
+
+ ReadResource op = new ReadResource(pathToAddress(path));
+ Result res = connection.execute(op);
+
+ return res.isSuccess()? AvailabilityType.UP: AvailabilityType.DOWN;
}
@@ -179,6 +182,7 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
protected String getPath() { return path; }
+ // TODO this needs completeion and a big fat refactoring
public Configuration loadResourceConfiguration() throws Exception {
ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition();
// String myPath = getResultingPath();
12 years, 11 months
[rhq] modules/enterprise
by John Sanda
modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml | 3 ++-
modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml | 3 ++-
2 files changed, 4 insertions(+), 2 deletions(-)
New commits:
commit 7cbd8d79e13608b826e696375811d9e75a7d7c01
Author: John Sanda <jsanda(a)redhat.com>
Date: Thu May 26 11:45:29 2011 -0400
Fixing more FK constraint violoations happening during test runs
diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml
index fe4dfd4..3f1d88e 100644
--- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml
+++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml
@@ -79,6 +79,7 @@
<rhq_availability/>
<rhq_measurement_sched/>
<rhq_content_source/>
+ <rhq_repo_content_src_map/>
<rhq_package/>
<rhq_bundle/>
@@ -92,4 +93,4 @@
md5="1234567"
ctime="12345"
mtime="123456"/>
-</dataset>
\ No newline at end of file
+</dataset>
diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml
index 2ac6566..55aa1f2 100644
--- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml
+++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml
@@ -103,7 +103,8 @@
<rhq_availability/>
<rhq_measurement_sched/>
<rhq_content_source/>
+ <rhq_repo_content_src_map/>
<rhq_package/>
<rhq_bundle/>
<rhq_plugin/>
-</dataset>
\ No newline at end of file
+</dataset>
12 years, 11 months
[rhq] modules/enterprise
by John Sanda
modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml | 1 +
modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml | 1 +
2 files changed, 2 insertions(+)
New commits:
commit fd23bd7219bc073748be07238b618b30a0cf5d62
Author: John Sanda <jsanda(a)redhat.com>
Date: Thu May 26 11:00:57 2011 -0400
Attempting to fix test failures
diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml
index f2f0fb4..fe4dfd4 100644
--- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml
+++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/discovery/DiscoveryBossBeanTest.xml
@@ -78,6 +78,7 @@
<rhq_alert_notif_log/>
<rhq_availability/>
<rhq_measurement_sched/>
+ <rhq_content_source/>
<rhq_package/>
<rhq_bundle/>
diff --git a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml
index 5d38d1f..2ac6566 100644
--- a/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml
+++ b/modules/enterprise/server/jar/src/test/resources/org/rhq/enterprise/server/inventory/InventoryManagerBeanTest.xml
@@ -102,6 +102,7 @@
<rhq_alert_notif_log/>
<rhq_availability/>
<rhq_measurement_sched/>
+ <rhq_content_source/>
<rhq_package/>
<rhq_bundle/>
<rhq_plugin/>
12 years, 11 months
[rhq] Branch 'drift' - modules/core
by John Sanda
modules/core/dbutils/pom.xml | 2 -
modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml | 2 +
modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml | 15 ++++++++++
modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java | 11 +++++++
modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java | 6 ++--
5 files changed, 33 insertions(+), 3 deletions(-)
New commits:
commit dc146dae82bdea0afed27985ed572ba7bfd50787
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed May 25 22:55:25 2011 -0400
Adding dbupgrade script for Snapshot and adding a basedir field/property
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml
index 063f2ce..4bcb8f1 100644
--- a/modules/core/dbutils/pom.xml
+++ b/modules/core/dbutils/pom.xml
@@ -22,7 +22,7 @@
<properties>
<scm.module.path>modules/core/dbutils/</scm.module.path>
- <db.schema.version>2.107</db.schema.version>
+ <db.schema.version>2.108</db.schema.version>
</properties>
<dependencies>
diff --git a/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml b/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
index 94fe4c3..851e797 100644
--- a/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
+++ b/modules/core/dbutils/src/main/scripts/dbsetup/content-schema.xml
@@ -650,8 +650,10 @@
<column name="ID" default="sequence-only" initial="10001" primarykey="true" required="true" type="INTEGER"/>
<column name="DATA" type="LARGEOBJECT" required="false"/>
<column name="DATA_SIZE" type="LONG"/>
+ <column name="BASEDIR" type="VARCHAR2" size="512" required="true"/>
<column name="CTIME" type="LONG" required="true"/>
</table>
+
</dbsetup>
diff --git a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml
index 1e7fffe..bb2c716 100644
--- a/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml
+++ b/modules/core/dbutils/src/main/scripts/dbupgrade/db-upgrade.xml
@@ -3389,6 +3389,21 @@
<schemaSpec version="2.107">
<schema-createSequence name="RHQ_OPERATION_SCHEDULE_ID_SEQ" initial="10001"/>
</schemaSpec>
+
+ <schemaSpec version="2.108">
+ <schema-createSequence name="RHQ_SNAPSHOT_ID_SEQ" initial="10001" />
+ <schema-directSQL>
+ <statement desc="Creating table RHQ_SNAPSHOT">
+ CREATE TABLE RHQ_SNAPSHOT (ID INTEGER PRIMARY KEY)
+ </statement>
+ </schema-directSQL>
+ <schema-alterColumn table="RHQ_SNAPSHOT" column="ID" columnType="INTEGER" nullable="FALSE" />
+ <schema-addColumn table="RHQ_SNAPSHOT" column="BASEDIR" columnType="VARCHAR2" />
+ <schema-alterColumn table="RHQ_SNAPSHOT" column="BASEDIR" nullable="false" precision="512"/>
+ <schema-addColumn table="RHQ_SNAPSHOT" column="DATA" columnType="LARGEOBJECT"/>
+ <schema-addColumn table="RHQ_SNAPSHOT" column="DATA_SIZE" columnType="LONG"/>
+ <schema-addColumn table="RHQ_SNAPSHOT" column="CTIME" columnType="LONG" />
+ </schemaSpec>
</dbupgrade>
</target>
</project>
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java
index 48c64f1..bef88b6 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java
@@ -31,6 +31,9 @@ public class Snapshot implements Serializable {
//private SnapshotMetadata metadata = new SnapshotMetadata();
+ @Column(name = "BASEDIR", nullable = false, length = 512)
+ private String basedir;
+
@Lob
@Column(name = "DATA")
private Blob data;
@@ -77,6 +80,14 @@ public class Snapshot implements Serializable {
dataSize = size;
}
+ public String getBasedir() {
+ return basedir;
+ }
+
+ public void setBasedir(String dir) {
+ basedir = dir;
+ }
+
public long getCtime() {
return ctime;
}
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java
index 4c476ff..a3cf9c2 100644
--- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java
+++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java
@@ -47,6 +47,7 @@ public class SnapshotTest extends AbstractEJB3Test {
final Snapshot s1 = new Snapshot();
s1.setDataSize(content.length());
s1.setData(Hibernate.createBlob(toInputStream(content), content.length()));
+ s1.setBasedir("snapshot/test/s1");
executeInTransaction(new TransactionCallback() {
@Override
@@ -89,13 +90,14 @@ public class SnapshotTest extends AbstractEJB3Test {
// running and should be moved to an integration test suite.
@Test(groups = {"integration.ejb3", "snapshot"})
public void loadMultipleSnapshotsWithoutLoadingData() throws Exception {
- File dataFile = createDataFile("test_data.txt", 100);
- int numSnapshots = 25;
+ File dataFile = createDataFile("test_data.txt", 10);
+ int numSnapshots = 10;
final List<Integer> snapshotIds = new ArrayList<Integer>();
for (int i = 0; i <numSnapshots; ++i) {
final Snapshot snapshot = new Snapshot();
snapshot.setDataSize(dataFile.length());
+ snapshot.setBasedir("snapshot/" + i);
snapshot.setData(Hibernate.createBlob(new BufferedInputStream(new FileInputStream(dataFile))));
executeInTransaction(new TransactionCallback() {
12 years, 11 months
[rhq] modules/core modules/plugins modules/test-utils
by lkrejci
modules/core/plugin-container/pom.xml | 15
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java | 70 +
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java | 577 ++++------
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java | 229 +--
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java | 436 +++----
modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java | 390 ------
modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java | 118 ++
modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java | 397 ++++++
modules/plugins/pom.xml | 15
modules/test-utils/pom.xml | 8
modules/test-utils/src/main/java/org/rhq/test/JMockTest.java | 134 ++
11 files changed, 1369 insertions(+), 1020 deletions(-)
New commits:
commit 712d0e14d2cd4edb2be070d8028f83c4552b50bb
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Thu May 26 00:10:11 2011 +0200
Refactoring the way plugin container can be started up in the tests
and converted the resource upgrade tests to use this new approach.
When the test inherits from PluginContainerTest or uses it as an TestNG
listener, the plugin container can be configured declaratively using
an @PluginContainerSetup annotation. There is a couple of static methods
on the PluginContainerTest class to work with such preconfigured PC
(like starting it).
The JMockTest generic base class was augmented so that it can be used as both
a base class to tests and a TestNG listener.
diff --git a/modules/core/plugin-container/pom.xml b/modules/core/plugin-container/pom.xml
index fd14685..8cb24a4 100644
--- a/modules/core/plugin-container/pom.xml
+++ b/modules/core/plugin-container/pom.xml
@@ -102,6 +102,8 @@
<type>zip</type>
</dependency>
+ <!-- Test dependencies -->
+
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>test-utils</artifactId>
@@ -360,7 +362,18 @@
-->
</configuration>
</plugin>
-
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>jar</goal>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java
new file mode 100644
index 0000000..e2c7f5c
--- /dev/null
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResType.java
@@ -0,0 +1,70 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.core.pc.upgrade;
+
+/**
+ * A helper class representing a resource type in a simplistic manner.
+ *
+ *
+ * @author Lukas Krejci
+ */
+class ResType {
+ private String resourceTypeName;
+ private String resourceTypePluginName;
+
+ public ResType(String resourceTypeName, String resourceTypePluginName) {
+ super();
+ this.resourceTypeName = resourceTypeName;
+ this.resourceTypePluginName = resourceTypePluginName;
+ }
+
+ public String getResourceTypeName() {
+ return resourceTypeName;
+ }
+
+ public String getResourceTypePluginName() {
+ return resourceTypePluginName;
+ }
+
+ @Override
+ public int hashCode() {
+ return resourceTypeName.hashCode() * resourceTypePluginName.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other == this) {
+ return true;
+ }
+
+ if (!(other instanceof ResType)) {
+ return false;
+ }
+
+ ResType o = (ResType)other;
+
+ return resourceTypeName.equals(o.getResourceTypeName()) && resourceTypePluginName.equals(o.getResourceTypePluginName());
+ }
+
+ @Override
+ public String toString() {
+ return "ResType[name='" + resourceTypeName + "', plugin='" + resourceTypePluginName + "']";
+ }
+}
\ No newline at end of file
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
index 5f493c9..6821b44 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeFailureHandlingTest.java
@@ -27,7 +27,6 @@ import static org.testng.Assert.fail;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -36,25 +35,25 @@ import java.util.Map;
import java.util.Set;
import org.jmock.Expectations;
-import org.jmock.Mockery;
import org.testng.annotations.Test;
import org.rhq.core.clientapi.agent.PluginContainerException;
import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException;
import org.rhq.core.clientapi.server.discovery.InvalidInventoryReportException;
import org.rhq.core.clientapi.server.discovery.InventoryReport;
-import org.rhq.core.clientapi.server.discovery.StaleTypeException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceErrorType;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.pc.inventory.ResourceContainer;
import org.rhq.core.pc.inventory.ResourceContainer.ResourceComponentState;
import org.rhq.core.pc.upgrade.plugins.multi.base.BaseResourceComponentInterface;
import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet;
+import org.rhq.test.pc.PluginContainerSetup;
/**
* The plugins and their resource types form the following dependency structure:
@@ -74,42 +73,29 @@ import org.rhq.core.pluginapi.upgrade.ResourceUpgradeFacet;
*
* @author Lukas Krejci
*/
-@Test(sequential = true, invocationCount = 1)
+@Test(singleThreaded = true, invocationCount = 1)
public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase {
+ //test names
+ private static final String SUCCESS_TEST = "SUCCESS_TEST";
+ private static final String FAILURE_ON_LEAF_TEST = "FAILURE_ON_LEAF_TEST";
+ private static final String FAILURE_ON_DEPENDENCIES_TEST = "FAILURE_ON_DEPENDENCIES_TEST";
+ private static final String RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST = "RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST";
+
//plugin names
- private static final String BASE_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-base-1.0.0.jar";
- private static final String PARENT_DEP_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
- private static final String PARENT_DEP_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
- private static final String PARENT_SIBLING_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentsibling-1.0.0.jar";
- private static final String PARENT_SIBLING_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentsibling-2.0.0.jar";
- private static final String ROOT_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-root-1.0.0.jar";
- private static final String SIBLING_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-sibling-1.0.0.jar";
- private static final String SIBLING_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-sibling-2.0.0.jar";
- private static final String TEST_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-1.0.0.jar";
- private static final String TEST_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-test-2.0.0.jar";
+ private static final String BASE_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-base-1.0.0.jar";
+ private static final String PARENT_DEP_V1_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
+ private static final String PARENT_DEP_V2_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
+ private static final String PARENT_SIBLING_V1_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-parentsibling-1.0.0.jar";
+ private static final String PARENT_SIBLING_V2_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-parentsibling-2.0.0.jar";
+ private static final String ROOT_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-root-1.0.0.jar";
+ private static final String SIBLING_V1_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-sibling-1.0.0.jar";
+ private static final String SIBLING_V2_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-sibling-2.0.0.jar";
+ private static final String TEST_V1_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-test-1.0.0.jar";
+ private static final String TEST_V2_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-test-2.0.0.jar";
private static final String UPGRADED_RESOURCE_KEY_PREFIX = "UPGRADED";
- private static final HashMap<String, List<String>> DEPS;
-
- static {
- DEPS = new HashMap<String, List<String>>();
-
- DEPS.put(BASE_PLUGIN_NAME, Collections.<String> emptyList());
- DEPS.put(PARENT_DEP_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME));
- DEPS.put(PARENT_DEP_V2_PLUGIN_NAME, DEPS.get(PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(PARENT_SIBLING_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME));
- DEPS.put(PARENT_SIBLING_V2_PLUGIN_NAME, DEPS.get(PARENT_SIBLING_V1_PLUGIN_NAME));
- DEPS.put(ROOT_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME));
- DEPS.put(SIBLING_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(SIBLING_V2_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME));
- DEPS.put(TEST_V1_PLUGIN_NAME,
- Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME));
- DEPS.put(TEST_V2_PLUGIN_NAME,
- Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME));
- }
-
private static final ResType TEST_TYPE = new ResType("TestResource", "test");
private static final ResType SIBLING_TYPE = new ResType("TestResourceSibling", "test");
private static final ResType PARENT_TYPE = new ResType("TestResourceParent", "test");
@@ -120,294 +106,276 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase
private static List<ResType> ALL_TYPES = Arrays.asList(TEST_TYPE, SIBLING_TYPE, PARENT_TYPE, PARENT_DEP_TYPE,
PARENT_DEP_SIBLING_TYPE, ROOT_TYPE);
- protected Collection<String> getRequiredPlugins() {
- return Arrays.asList(BASE_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME,
- PARENT_SIBLING_V1_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, ROOT_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME,
- SIBLING_V2_PLUGIN_NAME, TEST_V1_PLUGIN_NAME, TEST_V2_PLUGIN_NAME);
- }
-
@Test
- public void testSuccess() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- //let it all run in v1
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- //now let's run with v2 plugins and check the layout of the inventory
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
-
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
-
- //check that the resources are upgraded
- checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
- checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
- checkResourcesUpgraded(resources.get(SIBLING_TYPE), 45);
- checkResourcesUpgraded(resources.get(TEST_TYPE), 45);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = SUCCESS_TEST, clearDataDir = true, numberOfInitialDiscoveries = 3)
+ public void testSuccess_V1() throws Exception {
+ final FakeServerInventory inv = new FakeServerInventory();
+ setServerSideFake(SUCCESS_TEST, inv);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
+ }
+ });
+
+ //let the discovery run in V1
+ startConfiguredPluginContainer();
}
+
+ @Test(dependsOnMethods = "testSuccess_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = SUCCESS_TEST, clearInventoryDat = false, numberOfInitialDiscoveries = 3)
+ public void testSuccess_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory) getServerSideFake(SUCCESS_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources = getResourcesFromInventory(inventory, ALL_TYPES);
+
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+ //check that the resources are upgraded
+ checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+ checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
+ checkResourcesUpgraded(resources.get(SIBLING_TYPE), 45);
+ checkResourcesUpgraded(resources.get(TEST_TYPE), 45);
+
+ }
+
@Test
- public void testFailureOnLeaf() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- //in here we set up the failures that are going to happen when
- //the v2 plugins are run
-
- Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
- assertNotNull(parent0, "Failed to find the parent to setup the failures for.");
- Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
- assertNotNull(parent1, "Failed to find the parent to setup the failures for.");
-
- addChildrenToFail(parent0, TEST_TYPE, 1, 2);
- addChildrenToFail(parent1, SIBLING_TYPE, 1);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
-
- checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
- checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
-
- Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
- Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
- Resource parent2 = findResourceWithOrdinal(PARENT_TYPE, 2);
-
- Set<Resource> testsUnderParent0 = filterResources(parent0.getChildResources(), TEST_TYPE);
- Set<Resource> siblingsUnderParent0 = filterResources(parent0.getChildResources(), SIBLING_TYPE);
- Set<Resource> testsUnderParent1 = filterResources(parent1.getChildResources(), TEST_TYPE);
- Set<Resource> siblingsUnderParent1 = filterResources(parent1.getChildResources(), SIBLING_TYPE);
- Set<Resource> testsUnderParent2 = filterResources(parent2.getChildResources(), TEST_TYPE);
- Set<Resource> siblingsUnderParent2 = filterResources(parent2.getChildResources(), SIBLING_TYPE);
-
- //first check for the successful upgrades
- checkResourcesUpgraded(testsUnderParent2, 15);
- checkResourcesUpgraded(siblingsUnderParent2, 15);
- checkResourcesUpgraded(siblingsUnderParent0, 15);
- checkResourcesUpgraded(testsUnderParent1, 15);
-
- //there should be no newly discovered sibling resources of the failed ones
- assertEquals(testsUnderParent0.size(), 10);
- assertEquals(siblingsUnderParent1.size(), 10);
-
- //check that the failed resources have the error attached to them
- //we find the resource instance from the map provided to this method
- //because that map contains the resources as found on the server-side
- //(i.e. they include error objects).
- Resource failedTest1 = getEqualFrom(resources.get(TEST_TYPE),
- findResourceWithOrdinal(testsUnderParent0, 1));
- Resource failedTest2 = getEqualFrom(resources.get(TEST_TYPE),
- findResourceWithOrdinal(testsUnderParent0, 2));
-
- checkResourceFailedUpgrade(failedTest1);
- checkResourceFailedUpgrade(failedTest2);
- checkOthersUpgraded(testsUnderParent0, failedTest1, failedTest2);
-
- Resource failedSibling = getEqualFrom(resources.get(SIBLING_TYPE),
- findResourceWithOrdinal(siblingsUnderParent1, 1));
-
- checkResourceFailedUpgrade(failedSibling);
- checkOthersUpgraded(siblingsUnderParent1, failedSibling);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_LEAF_TEST, clearDataDir = true, numberOfInitialDiscoveries = 3)
+ public void testFailureOnLeaf_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(FAILURE_ON_LEAF_TEST, inventory);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ //in here we set up the failures that are going to happen when
+ //the v2 plugins are run
+
+ Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
+ assertNotNull(parent0, "Failed to find the parent to setup the failures for.");
+ Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
+ assertNotNull(parent1, "Failed to find the parent to setup the failures for.");
+
+ addChildrenToFail(parent0, TEST_TYPE, 1, 2);
+ addChildrenToFail(parent1, SIBLING_TYPE, 1);
}
+ @Test(dependsOnMethods = "testFailureOnLeaf_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_LEAF_TEST, clearInventoryDat = false, numberOfInitialDiscoveries = 3)
+ public void testFailureOnLeaf_V2() {
+ final FakeServerInventory inventory = (FakeServerInventory) getServerSideFake(FAILURE_ON_LEAF_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources = getResourcesFromInventory(inventory, ALL_TYPES);
+
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+
+ checkResourcesUpgraded(resources.get(PARENT_TYPE), 3);
+ checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+
+ Resource parent0 = findResourceWithOrdinal(PARENT_TYPE, 0);
+ Resource parent1 = findResourceWithOrdinal(PARENT_TYPE, 1);
+ Resource parent2 = findResourceWithOrdinal(PARENT_TYPE, 2);
+
+ Set<Resource> testsUnderParent0 = filterResources(parent0.getChildResources(), TEST_TYPE);
+ Set<Resource> siblingsUnderParent0 = filterResources(parent0.getChildResources(), SIBLING_TYPE);
+ Set<Resource> testsUnderParent1 = filterResources(parent1.getChildResources(), TEST_TYPE);
+ Set<Resource> siblingsUnderParent1 = filterResources(parent1.getChildResources(), SIBLING_TYPE);
+ Set<Resource> testsUnderParent2 = filterResources(parent2.getChildResources(), TEST_TYPE);
+ Set<Resource> siblingsUnderParent2 = filterResources(parent2.getChildResources(), SIBLING_TYPE);
+
+ //first check for the successful upgrades
+ checkResourcesUpgraded(testsUnderParent2, 15);
+ checkResourcesUpgraded(siblingsUnderParent2, 15);
+ checkResourcesUpgraded(siblingsUnderParent0, 15);
+ checkResourcesUpgraded(testsUnderParent1, 15);
+
+ //there should be no newly discovered sibling resources of the failed ones
+ assertEquals(testsUnderParent0.size(), 10);
+ assertEquals(siblingsUnderParent1.size(), 10);
+
+ //check that the failed resources have the error attached to them
+ //we find the resource instance from the map provided to this method
+ //because that map contains the resources as found on the server-side
+ //(i.e. they include error objects).
+ Resource failedTest1 = getEqualFrom(resources.get(TEST_TYPE),
+ findResourceWithOrdinal(testsUnderParent0, 1));
+ Resource failedTest2 = getEqualFrom(resources.get(TEST_TYPE),
+ findResourceWithOrdinal(testsUnderParent0, 2));
+
+ checkResourceFailedUpgrade(failedTest1);
+ checkResourceFailedUpgrade(failedTest2);
+ checkOthersUpgraded(testsUnderParent0, failedTest1, failedTest2);
+
+ Resource failedSibling = getEqualFrom(resources.get(SIBLING_TYPE),
+ findResourceWithOrdinal(siblingsUnderParent1, 1));
+
+ checkResourceFailedUpgrade(failedSibling);
+ checkOthersUpgraded(siblingsUnderParent1, failedSibling);
+ }
+
@Test
- public void testFailureOnDependencies() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- //in here we set up the failures that are going to happen when
- //the v2 plugins are run
-
- Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
- assertNotNull(parent, "Failed to find the parent to setup the failures for.");
-
- addChildrenToFail(parent, PARENT_TYPE, 0);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
- checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
-
- //check that the failed resources have the error attached to them
- //we find the resource instance from the map provided to this method
- //because that map contains the resources as found on the server-side
- //(i.e. they include error objects).
- Resource parent0 = getEqualFrom(resources.get(PARENT_TYPE), findResourceWithOrdinal(PARENT_TYPE, 0));
- Resource parent1 = getEqualFrom(resources.get(PARENT_TYPE), findResourceWithOrdinal(PARENT_TYPE, 1));
-
- //v2 plugin discovers 3 resources but because parent0 failed to upgrade,
- //the discovery shouldn't have occurred leaving us with the 2 already existing resources.
- checkNumberOfResources(resources, PARENT_TYPE, 2);
- checkResourceFailedUpgrade(parent0);
- checkOthersUpgraded(resources.get(PARENT_TYPE), parent0);
-
- //parent1 upgraded ok, so discovering its children should have executed.
- //this is v2, so we should find 15 of each.
- checkResourcesUpgraded(filterResources(parent1.getChildResources(), TEST_TYPE), 15);
- checkResourcesUpgraded(filterResources(parent1.getChildResources(), SIBLING_TYPE), 15);
-
- //these shouldn't have been upgraded. in v1 we had 10 resources of TEST_TYPE
- //and 10 resources of SIBLING_TYPE and that's what we should be seeing
- //now.
- checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), TEST_TYPE), 10);
- checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), SIBLING_TYPE), 10);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_DEPENDENCIES_TEST, clearDataDir = true, numberOfInitialDiscoveries = 3)
+ public void testFailureOnDependencies_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(FAILURE_ON_DEPENDENCIES_TEST, inventory);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ //in here we set up the failures that are going to happen when
+ //the v2 plugins are run
+
+ Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
+ assertNotNull(parent, "Failed to find the parent to setup the failures for.");
+
+ addChildrenToFail(parent, PARENT_TYPE, 0);
}
+
+ @Test(dependsOnMethods = "testFailureOnDependencies_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = FAILURE_ON_DEPENDENCIES_TEST, clearInventoryDat = false, numberOfInitialDiscoveries = 3)
+ public void testFailureOnDependencies_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory) getServerSideFake(FAILURE_ON_DEPENDENCIES_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources = getResourcesFromInventory(inventory, ALL_TYPES);
+
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+ checkResourcesUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+
+ //check that the failed resources have the error attached to them
+ //we find the resource instance from the map provided to this method
+ //because that map contains the resources as found on the server-side
+ //(i.e. they include error objects).
+ Resource parent0 = getEqualFrom(resources.get(PARENT_TYPE), findResourceWithOrdinal(PARENT_TYPE, 0));
+ Resource parent1 = getEqualFrom(resources.get(PARENT_TYPE), findResourceWithOrdinal(PARENT_TYPE, 1));
+
+ checkResourceFailedUpgrade(parent0);
+ checkOthersUpgraded(resources.get(PARENT_TYPE), parent0);
+ //v2 plugin discovers 3 resources but because parent0 failed to upgrade,
+ //the discovery shouldn't have occurred leaving us with the 2 already existing resources.
+ checkNumberOfResources(resources, PARENT_TYPE, 2);
+
+ //parent1 upgraded ok, so discovering its children should have executed.
+ //this is v2, so we should find 15 of each.
+ checkResourcesUpgraded(filterResources(parent1.getChildResources(), TEST_TYPE), 15);
+ checkResourcesUpgraded(filterResources(parent1.getChildResources(), SIBLING_TYPE), 15);
+
+ //these shouldn't have been upgraded. in v1 we had 10 resources of TEST_TYPE
+ //and 10 resources of SIBLING_TYPE and that's what we should be seeing
+ //now.
+ checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), TEST_TYPE), 10);
+ checkResourcesNotUpgraded(filterResources(parent0.getChildResources(), SIBLING_TYPE), 10);
+ }
+
@Test
- public void testResourcesRevertedToOriginalStateAfterFailedUpgrade() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- //let it all run in v1
- executeTestWithPlugins(getAllDepsFor(TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
- getCurrentServerSideInventory().setFailUpgrade(true);
+ @PluginContainerSetup(plugins = {TEST_V1_PLUGIN_NAME, PARENT_SIBLING_V1_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, SIBLING_V1_PLUGIN_NAME},
+ sharedGroup = RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST, clearDataDir = true, numberOfInitialDiscoveries = 3)
+ public void testResourcesRevertedToOriginalStateAfterFailedUpgrade_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST, inventory);
- //now let's run with v2 plugins and check the layout of the inventory
- executeTestWithPlugins(getAllDepsFor(TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME),
- new AbstractTestPayload(false, ALL_TYPES) {
-
- public void test(Map<ResType, Set<Resource>> resources) {
- checkPresenceOfResourceTypes(resources, getExpectedResourceTypes());
-
- checkNumberOfResources(resources, ROOT_TYPE, 1);
- checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
-
- //check that the resources are upgraded
- checkResourcesNotUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
- checkResourcesNotUpgraded(resources.get(PARENT_TYPE), 2);
- checkResourcesNotUpgraded(resources.get(SIBLING_TYPE), 20);
- checkResourcesNotUpgraded(resources.get(TEST_TYPE), 20);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
}
+
+ @Test(dependsOnMethods = "testResourcesRevertedToOriginalStateAfterFailedUpgrade_V1")
+ @PluginContainerSetup(plugins = {TEST_V2_PLUGIN_NAME, PARENT_SIBLING_V2_PLUGIN_NAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME, SIBLING_V2_PLUGIN_NAME},
+ sharedGroup = RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST, clearInventoryDat = false, numberOfInitialDiscoveries = 3)
+ public void testResourcesRevertedToOriginalStateAfterFailedUpgrade_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory) getServerSideFake(RESOURCES_REVERTED_TO_ORIGINAL_STATE_AFTER_FAILED_UPGRAGE_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ inventory.setFailUpgrade(true);
+
+ startConfiguredPluginContainer();
+
+ Map<ResType, Set<Resource>> resources = getResourcesFromInventory(inventory, ALL_TYPES);
+ checkPresenceOfResourceTypes(resources, ALL_TYPES);
+
+ checkNumberOfResources(resources, ROOT_TYPE, 1);
+ checkNumberOfResources(resources, PARENT_DEP_TYPE, 1);
+
+ //check that the resources are not upgraded
+ checkResourcesNotUpgraded(resources.get(PARENT_DEP_SIBLING_TYPE), 1);
+ checkResourcesNotUpgraded(resources.get(PARENT_TYPE), 2);
+ checkResourcesNotUpgraded(resources.get(SIBLING_TYPE), 20);
+ checkResourcesNotUpgraded(resources.get(TEST_TYPE), 20);
+ }
@SuppressWarnings("unchecked")
- @Override
- protected void defineDefaultExpectations(Expectations expectations) {
- super.defineDefaultExpectations(expectations);
+ protected void defineDefaultExpectations(FakeServerInventory inventory, Expectations expectations) {
+ super.defineDefaultExpectations(inventory, expectations);
try {
- expectations.allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
+ ServerServices ss = pluginContainerConfiguration.getServerServices();
+ expectations.allowing(ss.getDiscoveryServerService()).mergeInventoryReport(
expectations.with(Expectations.any(InventoryReport.class)));
- expectations.will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ expectations.will(inventory.mergeInventoryReport(InventoryStatus.COMMITTED));
- expectations.allowing(getCurrentDiscoveryServerService()).upgradeResources(
+ expectations.allowing(ss.getDiscoveryServerService()).upgradeResources(
expectations.with(Expectations.any(Set.class)));
- expectations.will(getCurrentServerSideInventory().upgradeResources());
+ expectations.will(inventory.upgradeResources());
} catch (InvalidInventoryReportException e) {
//this is not going to happen because we're mocking the invocation
}
}
- private Set<String> getAllDepsFor(String... plugins) {
- HashSet<String> deps = new HashSet<String>();
- for (String plugin : plugins) {
- deps.add(plugin);
- deps.addAll(DEPS.get(plugin));
- }
-
- return deps;
- }
-
- protected static void checkPresenceOfResourceTypes(Map<ResType, Set<Resource>> resources, Set<ResType> expectedTypes) {
+ protected static void checkPresenceOfResourceTypes(Map<ResType, Set<Resource>> resources, Collection<ResType> expectedTypes) {
for (ResType resType : expectedTypes) {
assertNotNull(resources.get(resType), "Expecting some resources of type " + resType);
}
@@ -531,6 +499,21 @@ public class ResourceUpgradeFailureHandlingTest extends ResourceUpgradeTestBase
return ret;
}
+
+ private Map<ResType, Set<Resource>> getResourcesFromInventory(FakeServerInventory inventory, Collection<ResType> types) {
+ Map<ResType, Set<Resource>> resources = new HashMap<ResType, Set<Resource>>();
+
+ for(ResType type : types) {
+ ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager()
+ .getType(type.getResourceTypeName(), type.getResourceTypePluginName());
+
+ Set<Resource> rs = inventory.findResourcesByType(resType);
+ resources.put(type, rs);
+ }
+
+ return resources;
+ }
+
private static <T> T getEqualFrom(Collection<? extends T> collection, T object) {
for (T other : collection) {
if (object.equals(other)) {
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
index 3234c30..65deac7 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeProgressHandlingTest.java
@@ -19,23 +19,14 @@
package org.rhq.core.pc.upgrade;
-import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertEquals;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import static org.testng.Assert.assertNotNull;
import org.jmock.Expectations;
-import org.jmock.Mockery;
import org.testng.annotations.Test;
import org.rhq.core.domain.resource.Resource;
+import org.rhq.test.pc.PluginContainerSetup;
/**
*
@@ -45,139 +36,113 @@ import org.rhq.core.domain.resource.Resource;
@Test
public class ResourceUpgradeProgressHandlingTest extends ResourceUpgradeFailureHandlingTest {
- private static final String BASE_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-base-1.0.0.jar";
- private static final String PARENT_DEP_V1_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
- private static final String PARENT_DEP_V2_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
- private static final String ROOT_PLUGIN_NAME = "/resource-upgrade-test-plugin-multi-root-1.0.0.jar";
- private static final String UPGRADE_PROGRESS_PLUGIN_V1_FILENAME = "/resource-upgrade-test-plugin-progress-test-1.0.0.jar";
- private static final String UPGRADE_PROGRESS_PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-progress-test-2.0.0.jar";
- private static final String UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME = "/resource-upgrade-test-plugin-duplicate-test-1.0.0.jar";
- private static final String UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-duplicate-test-2.0.0.jar";
-
+ //test names
+ private static final String DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST = "DuplicitResourceKeysHandledCorrectly";
+ private static final String PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST = "ParentResourceStartedUpgradedWhenChildResourceBeingUpgraded";
+
+ //plugin names
+ private static final String BASE_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-base-1.0.0.jar";
+ private static final String PARENT_DEP_V1_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-parentdep-1.0.0.jar";
+ private static final String PARENT_DEP_V2_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-parentdep-2.0.0.jar";
+ private static final String ROOT_PLUGIN_NAME = "classpath:///resource-upgrade-test-plugin-multi-root-1.0.0.jar";
+ private static final String UPGRADE_PROGRESS_PLUGIN_V1_FILENAME = "classpath:///resource-upgrade-test-plugin-progress-test-1.0.0.jar";
+ private static final String UPGRADE_PROGRESS_PLUGIN_V2_FILENAME = "classpath:///resource-upgrade-test-plugin-progress-test-2.0.0.jar";
+ private static final String UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME = "classpath:///resource-upgrade-test-plugin-duplicate-test-1.0.0.jar";
+ private static final String UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME = "classpath:///resource-upgrade-test-plugin-duplicate-test-2.0.0.jar";
+
private static final ResType TEST_TYPE = new ResType("TestResource", "test");
private static final ResType PARENT_DEP_TYPE = new ResType("ParentDependency", "parentdep");
- private static final ResType ROOT_TYPE = new ResType("Root", "root");
-
- private static final HashMap<String, List<String>> DEPS;
-
- static {
- DEPS = new HashMap<String, List<String>>();
-
- DEPS.put(BASE_PLUGIN_NAME, Collections.<String> emptyList());
- DEPS.put(PARENT_DEP_V1_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME));
- DEPS.put(PARENT_DEP_V2_PLUGIN_NAME, DEPS.get(PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(ROOT_PLUGIN_NAME, Arrays.asList(BASE_PLUGIN_NAME));
- DEPS.put(UPGRADE_PROGRESS_PLUGIN_V1_FILENAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(UPGRADE_PROGRESS_PLUGIN_V2_FILENAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME));
- DEPS.put(UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME));
- DEPS.put(UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME, Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME));
- }
+
+ @Test
+ @PluginContainerSetup(plugins = { UPGRADE_PROGRESS_PLUGIN_V1_FILENAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V1_PLUGIN_NAME }, sharedGroup = PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST, clearDataDir = true)
+ public void testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST, inventory);
- private Set<String> getAllDepsFor(String... plugins) {
- HashSet<String> deps = new HashSet<String>();
- for (String plugin : plugins) {
- deps.add(plugin);
- deps.addAll(DEPS.get(plugin));
- }
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
- return deps;
- }
-
- @Override
- protected Collection<String> getRequiredPlugins() {
- return Arrays.asList(BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME, PARENT_DEP_V1_PLUGIN_NAME, PARENT_DEP_V2_PLUGIN_NAME,
- UPGRADE_PROGRESS_PLUGIN_V1_FILENAME, UPGRADE_PROGRESS_PLUGIN_V2_FILENAME, UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME,
- UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME);
+ startConfiguredPluginContainer();
+
+ //in here we set up the failures that are going to happen when
+ //the v2 plugins are run
+
+ Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
+ assertNotNull(parent, "Failed to find the parent.");
}
- @Test
- public void testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(UPGRADE_PROGRESS_PLUGIN_V1_FILENAME),
- new AbstractTestPayload(true, Collections.<ResType> emptyList()) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- //in here we set up the failures that are going to happen when
- //the v2 plugins are run
-
- Resource parent = findResourceWithOrdinal(PARENT_DEP_TYPE, 0);
- assertNotNull(parent, "Failed to find the parent.");
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
+ @Test(dependsOnMethods = "testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded_V1")
+ @PluginContainerSetup(plugins = { UPGRADE_PROGRESS_PLUGIN_V2_FILENAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V2_PLUGIN_NAME }, sharedGroup = PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST, clearInventoryDat = false)
+ public void testParentResourceStartedUpgradedWhenChildResourceBeingUpgraded_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory) getServerSideFake(PARENT_RESOURCE_STARTED_UPGRADED_WHEN_CHILD_RESOURCE_BEING_UPGRADED_TEST);
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
//the upgrade progress plugin is set to check that the parent resource key
//has been upgraded during its upgrade method, so we just need to check here
//that everything got upgraded. If it was not, it'd mean that the the progress
//plugin failed the upgrade because it didn't see its parent upgraded.
- executeTestWithPlugins(getAllDepsFor(UPGRADE_PROGRESS_PLUGIN_V2_FILENAME),
- new AbstractTestPayload(false, Arrays.asList(TEST_TYPE, PARENT_DEP_TYPE)) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- checkResourcesUpgraded(resourceUpgradeTestResources.get(PARENT_DEP_TYPE), 1);
- checkResourcesUpgraded(resourceUpgradeTestResources.get(TEST_TYPE), 2);
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
+
+ checkResourcesUpgraded(getTestingResources(inventory, PARENT_DEP_TYPE), 1);
+ checkResourcesUpgraded(getTestingResources(inventory, TEST_TYPE), 2);
}
-
+
@Test
- public void testDuplicitResourceKeysHandledCorrectly() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
-
- executeTestWithPlugins(getAllDepsFor(UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME),
- new AbstractTestPayload(true, Arrays.asList(PARENT_DEP_TYPE, TEST_TYPE)) {
-
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- //there's not much to check with the v1 plugins. let's just check all the
- //resources have been discovered
- assertEquals(resourceUpgradeTestResources.get(PARENT_DEP_TYPE).size(), 1, "The V1 inventory should have 1 parent.");
- assertEquals(resourceUpgradeTestResources.get(TEST_TYPE).size(), 2, "The V1 inventory should have 2 test resources.");
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
-
+ @PluginContainerSetup(plugins = { UPGRADE_DUPLICATE_PLUGIN_V1_FILENAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V1_PLUGIN_NAME }, sharedGroup = DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST, clearDataDir = true, numberOfInitialDiscoveries = 2)
+ public void testDuplicitResourceKeysHandledCorrectly_V1() throws Exception {
+ final FakeServerInventory inventory = new FakeServerInventory();
+ setServerSideFake(DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST, inventory);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
+ //there's not much to check with the v1 plugins. let's just check all the
+ //resources have been discovered
+ assertEquals(getTestingResources(inventory, PARENT_DEP_TYPE).size(), 1,
+ "The V1 inventory should have 1 parent.");
+ assertEquals(getTestingResources(inventory, TEST_TYPE).size(), 2,
+ "The V1 inventory should have 2 test resources.");
+ }
+
+ @Test(dependsOnMethods = "testDuplicitResourceKeysHandledCorrectly_V1")
+ @PluginContainerSetup(plugins = { UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME, BASE_PLUGIN_NAME, ROOT_PLUGIN_NAME,
+ PARENT_DEP_V2_PLUGIN_NAME }, sharedGroup = DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST, clearInventoryDat = false, numberOfInitialDiscoveries = 2)
+ public void testDuplicitResourceKeysHandledCorrectly_V2() throws Exception {
+ final FakeServerInventory inventory = (FakeServerInventory) getServerSideFake(DUPLICIT_RESOURCE_KEYS_HANDLED_CORRECTLY_TEST);
+
+ context.checking(new Expectations() {
+ {
+ defineDefaultExpectations(inventory, this);
+ }
+ });
+
+ startConfiguredPluginContainer();
+
//now the V2 test resource is set to create 2 resources with the same resource keys.
//the upgrade should therefore fail.
- executeTestWithPlugins(getAllDepsFor(UPGRADE_DUPLICATE_PLUGIN_V2_FILENAME),
- new AbstractTestPayload(false, Arrays.asList(PARENT_DEP_TYPE, TEST_TYPE)) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- checkResourcesUpgraded(resourceUpgradeTestResources.get(PARENT_DEP_TYPE), 1);
-
- checkResourcesNotUpgraded(resourceUpgradeTestResources.get(TEST_TYPE), 2);
-
- for(Resource r : resourceUpgradeTestResources.get(TEST_TYPE)) {
- checkResourceFailedUpgrade(r);
- }
- }
-
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
- }
- };
- }
- });
- }
+
+ checkResourcesUpgraded(getTestingResources(inventory, PARENT_DEP_TYPE), 1);
+
+ checkResourcesNotUpgraded(getTestingResources(inventory, TEST_TYPE), 2);
+
+ for (Resource r : getTestingResources(inventory, TEST_TYPE)) {
+ checkResourceFailedUpgrade(r);
+ }
+ }
}
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
index e2a8a84..39ae23d 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTest.java
@@ -1,24 +1,20 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2010 Red Hat, Inc.
+ * Copyright (C) 2005-2011 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.
+ * 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 and the GNU Lesser General Public License
- * for more details.
+ * GNU 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.
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.rhq.core.pc.upgrade;
@@ -28,304 +24,320 @@ import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.File;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
import java.util.Set;
import org.jmock.Expectations;
-import org.jmock.Mockery;
+import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import org.rhq.core.clientapi.server.discovery.InventoryReport;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.inventory.ResourceContainer;
+import org.rhq.test.pc.PluginContainerSetup;
+import org.rhq.test.pc.PluginContainerTest;
/**
- * Test cases for resource upgrade.
*
+ *
* @author Lukas Krejci
*/
-@Test(sequential = true, invocationCount = 1)
+@Test
public class ResourceUpgradeTest extends ResourceUpgradeTestBase {
- private static final String PLUGIN_V1_FILENAME = "/resource-upgrade-test-plugin-1.0.0.jar";
- private static final String PLUGIN_V2_FILENAME = "/resource-upgrade-test-plugin-2.0.0.jar";
- private static final String FAILING_PLUGIN_FILE_NAME = "/resource-upgrade-test-plugin-3.0.0.jar";
+ private static final String INCLUDE_UNCOMMITTED_RESOURCES_TEST = "includeUncommittedResources";
+ private static final String UPGRADE_DATA_TEST = "upgradeData";
+ private static final String INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST = "inventoryReinitializationFromServerDuringUpgrade";
+ private static final String SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST = "skipUpgradeWhenServerUnavailable";
+ private static final String UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST = "upgradeWithPlatformDeletedOnServer";
+ private static final String UPGRADE_FAILURE_HANDLING = "upgradeFailureHandling";
+
+ private static final String PLUGIN_V1_FILENAME = "classpath:///resource-upgrade-test-plugin-1.0.0.jar";
+ private static final String PLUGIN_V2_FILENAME = "classpath:///resource-upgrade-test-plugin-2.0.0.jar";
+ private static final String FAILING_PLUGIN_FILE_NAME = "classpath:///resource-upgrade-test-plugin-3.0.0.jar";
private static final String SINGLETON_RESOURCE_TYPE_NAME = "Resource";
private static final String SINGLETON_RESOURCE_TYPE_PLUGIN_NAME = "ResourceUpgradeTest";
private static final ResType SINGLETON_TYPE = new ResType(SINGLETON_RESOURCE_TYPE_NAME,
SINGLETON_RESOURCE_TYPE_PLUGIN_NAME);
- private static List<ResType> getMyExpectedTypes() {
- return Arrays.asList(SINGLETON_TYPE);
+ @AfterSuite
+ public void cleanAfterPluginContainers() throws Exception {
+ PluginContainerTest.clearStorage();
}
- protected Collection<String> getRequiredPlugins() {
- return Arrays.asList(PLUGIN_V1_FILENAME, PLUGIN_V2_FILENAME, FAILING_PLUGIN_FILE_NAME);
+ @Test
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup = INCLUDE_UNCOMMITTED_RESOURCES_TEST, clearDataDir = true)
+ public void testIncludeUncommittedResources_V1() throws Exception {
+ initialSyncAndDiscovery(INCLUDE_UNCOMMITTED_RESOURCES_TEST, InventoryStatus.NEW);
}
- @Test
- public void testIncludeUncommittedResources() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.NEW);
+ @Test(dependsOnMethods = { "testIncludeUncommittedResources_V1" })
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup = INCLUDE_UNCOMMITTED_RESOURCES_TEST, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testIncludeUncommittedResources_V2() throws Exception {
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(INCLUDE_UNCOMMITTED_RESOURCES_TEST);
+ final ServerServices ss = PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- TestPayload testNoChange = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources) {
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
- assertEquals(discoveredResource.getName(), "resource-name-v2");
- assertEquals(discoveredResource.getDescription(), "resource-description-v2");
+ oneOf(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
+ will(inv.upgradeResources());
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
- allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ Set<Resource> resources = getTestingResources(inv, SINGLETON_TYPE);
- oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- will(getCurrentServerSideInventory().upgradeResources());
- }
- };
- }
- };
+ assertEquals(resources.size(), 1, "Expected single test resource but multiple found.");
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), testNoChange);
+ Resource discoveredResource = resources.iterator().next();
+
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
+ assertEquals(discoveredResource.getName(), "resource-name-v2");
+ assertEquals(discoveredResource.getDescription(), "resource-description-v2");
}
@Test
- public void testUpgradeData() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- upgradeTest(false);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup = UPGRADE_DATA_TEST, clearDataDir = true)
+ public void testUpgradeData_V1() throws Exception {
+ initialSyncAndDiscovery(UPGRADE_DATA_TEST, InventoryStatus.COMMITTED);
+ }
+
+ @Test(dependsOnMethods = "testUpgradeData_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup = UPGRADE_DATA_TEST, clearInventoryDat = false)
+ public void testUpgradeData_V2() throws Exception {
+ upgradeTest(UPGRADE_DATA_TEST);
}
@Test
- public void testInventoryReinitializationFromServerDuringUpgrade() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- upgradeTest(true);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup = INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST, clearDataDir = true)
+ public void testInventoryReinitializationFromServerDuringUpgrade_V1() throws Exception {
+ initialSyncAndDiscovery(INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST, InventoryStatus.COMMITTED);
+ }
+
+ @Test(dependsOnMethods = "testInventoryReinitializationFromServerDuringUpgrade_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup = INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST, clearInventoryDat = false)
+ public void testInventoryReinitializationFromServerDuringUpgrade_V2() throws Exception {
+ upgradeTest(INVENTORY_REINITIALIZATION_FROM_SERVER_DURING_UPGRADE_TEST);
}
@Test
- public void testSkipUpgradeWhenServerUnavailable() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup = SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST, clearDataDir = true)
+ public void testSkipUpgradeWhenServerUnavailable_V1() throws Exception {
+ initialSyncAndDiscovery(SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST, InventoryStatus.COMMITTED);
+ }
+
+ @Test(dependsOnMethods = "testSkipUpgradeWhenServerUnavailable_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup = SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testSkipUpgradeWhenServerUnavailable_V2() throws Exception {
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(SKIP_UPGRADE_WHEN_SERVER_UNAVAILABLE_TEST);
+ final ServerServices ss = PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- getCurrentServerSideInventory().setFailing(true);
+ inv.setFailing(true);
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources) {
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertEquals(discoveredResource.getResourceKey(), "resource-key-v1");
- assertEquals(discoveredResource.getName(), "resource-name-v1");
- assertEquals(discoveredResource.getDescription(), "resource-description-v1");
+ never(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
- allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ Set<Resource> discoveredResources = getTestingResources(inv, SINGLETON_TYPE);
- never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- }
- };
- }
- };
+ assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
+
+ Resource discoveredResource = discoveredResources.iterator().next();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test);
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v1");
+ assertEquals(discoveredResource.getName(), "resource-name-v1");
+ assertEquals(discoveredResource.getDescription(), "resource-description-v1");
}
@Test
- public void testUpgradeWithPlatformDeletedOnServer() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ @PluginContainerSetup(plugins = { PLUGIN_V1_FILENAME }, sharedGroup = UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST, clearDataDir = true)
+ public void testUpgradeWithPlatformDeletedOnServer_V1() throws Exception {
+ initialSyncAndDiscovery(UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST, InventoryStatus.COMMITTED);
+ }
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources) {
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ @Test(dependsOnMethods = "testUpgradeWithPlatformDeletedOnServer_V1")
+ @PluginContainerSetup(plugins = { PLUGIN_V2_FILENAME }, sharedGroup = UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testUpgradeWithPlatformDeletedOnServer_V2() throws Exception {
- Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(UPGRADE_WITH_PLATFORM_DELETED_ON_SERVER_TEST);
+ final ServerServices ss = PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
- assertEquals(discoveredResource.getName(), "resource-name-v2");
- assertEquals(discoveredResource.getDescription(), "resource-description-v2");
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- ResourceContainer container = PluginContainer.getInstance().getInventoryManager()
- .getResourceContainer(discoveredResource);
- File dataDir = container.getResourceContext().getDataDirectory();
+ //the first merge will be triggered from within the upgrade process and we are
+ //going to report null sync.
+ oneOf(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.clearPlatform());
- File marker = new File(dataDir, "upgrade-succeeded");
+ //the rest of the inventory merges are executed by discoveries, so let's import the
+ //discovered stuff into the server-side inventory.
+ allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertFalse(marker.exists(),
- "The upgrade seems to have occured even though there shouldn't have been a resource to upgrade.");
+ never(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
-
- //the first merge will be triggered from within the upgrade process and we are
- //going to report null sync.
- oneOf(getCurrentDiscoveryServerService())
- .mergeInventoryReport(with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().clearPlatform());
-
- //the rest of the inventory merges are executed by discoveries, so let's import the
- //discovered stuff into the server-side inventory.
- allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
-
- never(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- }
- };
- }
- };
+ PluginContainerTest.startConfiguredPluginContainer();
+
+ Set<Resource> discoveredResources = getTestingResources(inv, SINGLETON_TYPE);
+
+ assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
+
+ Resource discoveredResource = discoveredResources.iterator().next();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), test);
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
+ assertEquals(discoveredResource.getName(), "resource-name-v2");
+ assertEquals(discoveredResource.getDescription(), "resource-description-v2");
+
+ ResourceContainer container = PluginContainer.getInstance().getInventoryManager()
+ .getResourceContainer(discoveredResource);
+ File dataDir = container.getResourceContext().getDataDirectory();
+
+ File marker = new File(dataDir, "upgrade-succeeded");
+
+ assertFalse(marker.exists(),
+ "The upgrade seems to have occured even though there shouldn't have been a resource to upgrade.");
}
@Test
- public void testUpgradeFailureHandling() throws Exception {
- setCurrentServerSideInventory(new FakeServerInventory());
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ @PluginContainerSetup(plugins = PLUGIN_V1_FILENAME, sharedGroup = UPGRADE_FAILURE_HANDLING, clearDataDir = true)
+ public void testUpgradeFailureHandling_V1() throws Exception {
+ initialSyncAndDiscovery(UPGRADE_FAILURE_HANDLING, InventoryStatus.COMMITTED);
+ }
- TestPayload test = new AbstractTestPayload(false, getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> resourceUpgradeTestResources) {
- assertEquals(resourceUpgradeTestResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ @Test(dependsOnMethods = "testUpgradeFailureHandling_V1")
+ @PluginContainerSetup(plugins = FAILING_PLUGIN_FILE_NAME, sharedGroup = UPGRADE_FAILURE_HANDLING, clearInventoryDat = false)
+ @SuppressWarnings("unchecked")
+ public void testUpgradeFailureHandling_V2() throws Exception {
+ final FakeServerInventory inv = (FakeServerInventory) PluginContainerTest
+ .getServerSideFake(UPGRADE_FAILURE_HANDLING);
+ final ServerServices ss = PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- Resource discoveredResource = resourceUpgradeTestResources.get(SINGLETON_TYPE).iterator().next();
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- assertTrue(discoveredResource.getResourceErrors().size() > 0,
- "There should be upgrade errors persisted on the server side.");
+ allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(InventoryStatus.COMMITTED));
- //the discovery of the failed resource mustn't have run
- ResourceContainer container = PluginContainer.getInstance().getInventoryManager()
- .getResourceContainer(discoveredResource);
- File dataDir = container.getResourceContext().getDataDirectory();
+ oneOf(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
+ will(inv.upgradeResources());
+ }
+ });
- File marker = new File(dataDir, "failing-discovery-ran");
+ PluginContainerTest.startConfiguredPluginContainer();
- assertFalse(marker.exists(),
- "The discovery of the resource type with a failed upgraded resource must not be executed but it was.");
- }
+ Set<Resource> resourceUpgradeTestResources = getTestingResources(inv, SINGLETON_TYPE);
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ Resource discoveredResource = resourceUpgradeTestResources.iterator().next();
- allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ assertTrue(discoveredResource.getResourceErrors().size() > 0,
+ "There should be upgrade errors persisted on the server side.");
- oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- will(getCurrentServerSideInventory().upgradeResources());
- }
- };
- }
- };
+ //the discovery of the failed resource mustn't have run
+ ResourceContainer container = PluginContainer.getInstance().getInventoryManager()
+ .getResourceContainer(discoveredResource);
+ File dataDir = container.getResourceContext().getDataDirectory();
+
+ File marker = new File(dataDir, "failing-discovery-ran");
- executeTestWithPlugins(Collections.singleton(FAILING_PLUGIN_FILE_NAME), test);
+ assertFalse(marker.exists(),
+ "The discovery of the resource type with a failed upgraded resource must not be executed but it was.");
}
- private void initialSyncAndDiscovery(final InventoryStatus requiredInventoryStatus) throws Exception {
- cleanDataDir();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V1_FILENAME), new AbstractTestPayload(true,
- getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources) {
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ private FakeServerInventory initialSyncAndDiscovery(String key, final InventoryStatus requiredInventoryStatus)
+ throws Exception {
+ final FakeServerInventory inv = new FakeServerInventory();
+ PluginContainerTest.setServerSideFake(key, inv);
+ final ServerServices ss = PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(inv, this);
- assertEquals(discoveredResource.getResourceKey(), "resource-key-v1");
- assertEquals(discoveredResource.getName(), "resource-name-v1");
- assertEquals(discoveredResource.getDescription(), "resource-description-v1");
+ allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(inv.mergeInventoryReport(requiredInventoryStatus));
}
+ });
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
- allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().mergeInventoryReport(requiredInventoryStatus));
- }
- };
- }
- });
+ Set<Resource> resources = getTestingResources(inv, SINGLETON_TYPE);
- }
+ assertEquals(resources.size(), 1, "Expected single test resource but multiple found.");
- private void upgradeTest(boolean clearInventoryDat) throws Exception {
- initialSyncAndDiscovery(InventoryStatus.COMMITTED);
+ Resource discoveredResource = resources.iterator().next();
- executeTestWithPlugins(Collections.singleton(PLUGIN_V2_FILENAME), new AbstractTestPayload(clearInventoryDat,
- getMyExpectedTypes()) {
- public void test(Map<ResType, Set<Resource>> discoveredResources) {
- assertEquals(discoveredResources.get(SINGLETON_TYPE).size(), 1,
- "Expected single test resource but multiple found.");
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v1");
+ assertEquals(discoveredResource.getName(), "resource-name-v1");
+ assertEquals(discoveredResource.getDescription(), "resource-description-v1");
- Resource discoveredResource = discoveredResources.get(SINGLETON_TYPE).iterator().next();
+ return inv;
+ }
- assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
- assertEquals(discoveredResource.getName(), "resource-name-v2");
- assertEquals(discoveredResource.getDescription(), "resource-description-v2");
+ @SuppressWarnings("unchecked")
+ private void upgradeTest(String key) throws Exception {
+ final FakeServerInventory serverInventory = (FakeServerInventory) PluginContainerTest.getServerSideFake(key);
+ final ServerServices ss = PluginContainerTest.getCurrentPluginContainerConfiguration().getServerServices();
- ResourceContainer container = PluginContainer.getInstance().getInventoryManager()
- .getResourceContainer(discoveredResource);
- File dataDir = container.getResourceContext().getDataDirectory();
+ PluginContainerTest.getCurrentMockContext().checking(new Expectations() {
+ {
+ defineDefaultExpectations(serverInventory, this);
- File marker = new File(dataDir, "upgrade-succeeded");
+ allowing(ss.getDiscoveryServerService()).mergeInventoryReport(with(any(InventoryReport.class)));
+ will(serverInventory.mergeInventoryReport(InventoryStatus.COMMITTED));
- assertTrue(marker.exists(),
- "The upgrade success marker file wasn't found. This means the upgrade didn't actually run.");
+ oneOf(ss.getDiscoveryServerService()).upgradeResources(with(any(Set.class)));
+ will(serverInventory.upgradeResources());
}
+ });
- @SuppressWarnings("unchecked")
- public Expectations getExpectations(Mockery context) throws Exception {
- return new Expectations() {
- {
- defineDefaultExpectations(this);
+ PluginContainerTest.startConfiguredPluginContainer();
- allowing(getCurrentDiscoveryServerService()).mergeInventoryReport(
- with(any(InventoryReport.class)));
- will(getCurrentServerSideInventory().mergeInventoryReport(InventoryStatus.COMMITTED));
+ Set<Resource> discoveredResources = getTestingResources(serverInventory, SINGLETON_TYPE);
- oneOf(getCurrentDiscoveryServerService()).upgradeResources(with(any(Set.class)));
- will(getCurrentServerSideInventory().upgradeResources());
- }
- };
- }
- });
+ assertEquals(discoveredResources.size(), 1, "Expected single test resource but multiple found.");
+
+ Resource discoveredResource = discoveredResources.iterator().next();
+
+ assertEquals(discoveredResource.getResourceKey(), "resource-key-v2");
+ assertEquals(discoveredResource.getName(), "resource-name-v2");
+ assertEquals(discoveredResource.getDescription(), "resource-description-v2");
+
+ ResourceContainer container = PluginContainer.getInstance().getInventoryManager()
+ .getResourceContainer(discoveredResource);
+ File dataDir = container.getResourceContext().getDataDirectory();
+
+ File marker = new File(dataDir, "upgrade-succeeded");
+
+ assertTrue(marker.exists(),
+ "The upgrade success marker file wasn't found. This means the upgrade didn't actually run.");
}
}
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
index e0526a1..3035fef 100644
--- a/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
+++ b/modules/core/plugin-container/src/test/java/org/rhq/core/pc/upgrade/ResourceUpgradeTestBase.java
@@ -19,398 +19,52 @@
package org.rhq.core.pc.upgrade;
-import static org.testng.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
import java.util.Set;
-import org.apache.commons.io.FileUtils;
import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.rhq.core.clientapi.server.bundle.BundleServerService;
-import org.rhq.core.clientapi.server.configuration.ConfigurationServerService;
-import org.rhq.core.clientapi.server.content.ContentServerService;
-import org.rhq.core.clientapi.server.core.CoreServerService;
-import org.rhq.core.clientapi.server.discovery.DiscoveryServerService;
-import org.rhq.core.clientapi.server.event.EventServerService;
-import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService;
-import org.rhq.core.clientapi.server.measurement.MeasurementServerService;
-import org.rhq.core.clientapi.server.operation.OperationServerService;
import org.rhq.core.domain.discovery.AvailabilityReport;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.pc.PluginContainer;
-import org.rhq.core.pc.PluginContainerConfiguration;
import org.rhq.core.pc.ServerServices;
-import org.rhq.core.pc.inventory.InventoryManager;
-import org.rhq.core.pc.plugin.FileSystemPluginFinder;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
+import org.rhq.test.pc.PluginContainerTest;
/**
*
* @author Lukas Krejci
*/
-public abstract class ResourceUpgradeTestBase {
-
- private static final String PLUGINS_DIR_NAME = "plugins";
- private static final String DATA_DIR_NAME = "data";
- private static final String TMP_DIR_NAME = "tmp";
- private File tmpDir;
- private File pluginDir;
- private File dataDir;
- private BundleServerService currentBundleServerService;
- private ConfigurationServerService currentConfigurationServerService;
- private ContentServerService currentContentServerService;
- private CoreServerService currentCoreServerService;
- private DiscoveryServerService currentDiscoveryServerService;
- private EventServerService currentEventServerService;
- private MeasurementServerService currentMeasurementServerService;
- private OperationServerService currentOperationServerService;
- private ResourceFactoryServerService currentResourceFactoryServerService;
- private FakeServerInventory currentServerSideInventory;
-
- protected static class ResType {
- private String resourceTypeName;
- private String resourceTypePluginName;
-
- public ResType(String resourceTypeName, String resourceTypePluginName) {
- super();
- this.resourceTypeName = resourceTypeName;
- this.resourceTypePluginName = resourceTypePluginName;
- }
-
- public String getResourceTypeName() {
- return resourceTypeName;
- }
-
- public String getResourceTypePluginName() {
- return resourceTypePluginName;
- }
-
- @Override
- public int hashCode() {
- return resourceTypeName.hashCode() * resourceTypePluginName.hashCode();
- }
-
- @Override
- public boolean equals(Object other) {
- if (other == this) {
- return true;
- }
-
- if (!(other instanceof ResType)) {
- return false;
- }
-
- ResType o = (ResType)other;
-
- return resourceTypeName.equals(o.getResourceTypeName()) && resourceTypePluginName.equals(o.getResourceTypePluginName());
- }
-
- @Override
- public String toString() {
- return "ResType[name='" + resourceTypeName + "', plugin='" + resourceTypePluginName + "']";
- }
- }
-
- protected interface TestPayload {
- Expectations getExpectations(Mockery context) throws Exception;
-
- void test(Map<ResType,Set<Resource>> resourceUpgradeTestResources);
-
- boolean isClearInventoryDat();
-
- Set<ResType> getExpectedResourceTypes();
- }
-
- protected static abstract class AbstractTestPayload implements TestPayload {
- private boolean clearInventoryDat;
- private Set<ResType> resourceTypes;
-
- public AbstractTestPayload(boolean clearInventoryDat, Collection<ResType> resourceTypes) {
- this.clearInventoryDat = clearInventoryDat;
- this.resourceTypes = new HashSet<ResType>(resourceTypes);
- }
-
- public boolean isClearInventoryDat() {
- return clearInventoryDat;
- }
-
- public Set<ResType> getExpectedResourceTypes() {
- return resourceTypes;
- }
- }
-
- @BeforeClass
- public void init() {
- tmpDir = getTmpDirectory();
- pluginDir = new File(tmpDir, PLUGINS_DIR_NAME);
- assertTrue(pluginDir.mkdir(), "Could not create plugin deploy directory.");
- dataDir = new File(tmpDir, DATA_DIR_NAME);
- assertTrue(dataDir.mkdir(), "Could not create plugin container data directory.");
- }
-
- @BeforeClass
- public void verifyPluginsExist() {
- for (String plugin : getRequiredPlugins()) {
- verifyPluginExists(plugin);
- }
- }
-
- @AfterClass
- public void undeployPlugins() throws IOException {
- FileUtils.deleteDirectory(tmpDir);
- }
-
- protected abstract Collection<String> getRequiredPlugins();
-
- protected void setCurrentServerSideInventory(FakeServerInventory currentServerSideInventory) {
- this.currentServerSideInventory = currentServerSideInventory;
- }
-
- protected FakeServerInventory getCurrentServerSideInventory() {
- return currentServerSideInventory;
- }
-
- protected void setCurrentResourceFactoryServerService(
- ResourceFactoryServerService currentResourceFactoryServerService) {
- this.currentResourceFactoryServerService = currentResourceFactoryServerService;
- }
-
- protected ResourceFactoryServerService getCurrentResourceFactoryServerService() {
- return currentResourceFactoryServerService;
- }
-
- protected void setCurrentOperationServerService(OperationServerService currentOperationServerService) {
- this.currentOperationServerService = currentOperationServerService;
- }
-
- protected OperationServerService getCurrentOperationServerService() {
- return currentOperationServerService;
- }
-
- protected void setCurrentMeasurementServerService(MeasurementServerService currentMeasurementServerService) {
- this.currentMeasurementServerService = currentMeasurementServerService;
- }
-
- protected MeasurementServerService getCurrentMeasurementServerService() {
- return currentMeasurementServerService;
- }
-
- protected void setCurrentEventServerService(EventServerService currentEventServerService) {
- this.currentEventServerService = currentEventServerService;
- }
-
- protected EventServerService getCurrentEventServerService() {
- return currentEventServerService;
- }
-
- protected void setCurrentDiscoveryServerService(DiscoveryServerService currentDiscoveryServerService) {
- this.currentDiscoveryServerService = currentDiscoveryServerService;
- }
-
- protected DiscoveryServerService getCurrentDiscoveryServerService() {
- return currentDiscoveryServerService;
- }
-
- protected void setCurrentCoreServerService(CoreServerService currentCoreServerService) {
- this.currentCoreServerService = currentCoreServerService;
- }
-
- protected CoreServerService getCurrentCoreServerService() {
- return currentCoreServerService;
- }
-
- protected void setCurrentContentServerService(ContentServerService currentContentServerService) {
- this.currentContentServerService = currentContentServerService;
- }
-
- protected ContentServerService getCurrentContentServerService() {
- return currentContentServerService;
- }
-
- protected void setCurrentConfigurationServerService(ConfigurationServerService currentConfigurationServerService) {
- this.currentConfigurationServerService = currentConfigurationServerService;
- }
-
- protected ConfigurationServerService getCurrentConfigurationServerService() {
- return currentConfigurationServerService;
- }
-
- protected void setCurrentBundleServerService(BundleServerService currentBundleServerService) {
- this.currentBundleServerService = currentBundleServerService;
- }
-
- protected BundleServerService getCurrentBundleServerService() {
- return currentBundleServerService;
- }
-
- protected static File getTmpDirectory() {
- File ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis());
-
- while (ret.exists() || !ret.mkdir()) {
- ret = new File(System.getProperty("java.io.tmpdir"), "resource-upgrade-test" + System.currentTimeMillis());
- }
-
- return ret;
- }
-
- private PluginContainerConfiguration createPluginContainerConfiguration(Mockery context) throws Exception {
- PluginContainerConfiguration conf = new PluginContainerConfiguration();
-
- conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
- conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME));
- conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME));
- conf.setInsideAgent(true); //pc must think it's inside an agent so that it persists the inventory between restarts
- conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory()));
- conf.setCreateResourceClassloaders(false);
-
- //we're not interested in any scans happening out of our control
- conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE);
- conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE);
- conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE);
- conf.setEventSenderInitialDelay(Long.MAX_VALUE);
- conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE);
- conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE);
- conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE);
-
- setCurrentBundleServerService(context.mock(BundleServerService.class));
- setCurrentConfigurationServerService(context.mock(ConfigurationServerService.class));
- setCurrentContentServerService(context.mock(ContentServerService.class));
- setCurrentCoreServerService(context.mock(CoreServerService.class));
- setCurrentDiscoveryServerService(context.mock(DiscoveryServerService.class));
- setCurrentEventServerService(context.mock(EventServerService.class));
- setCurrentMeasurementServerService(context.mock(MeasurementServerService.class));
- setCurrentOperationServerService(context.mock(OperationServerService.class));
- setCurrentResourceFactoryServerService(context.mock(ResourceFactoryServerService.class));
-
- ServerServices serverServices = new ServerServices();
- serverServices.setBundleServerService(getCurrentBundleServerService());
- serverServices.setConfigurationServerService(getCurrentConfigurationServerService());
- serverServices.setContentServerService(getCurrentContentServerService());
- serverServices.setCoreServerService(getCurrentCoreServerService());
- serverServices.setDiscoveryServerService(getCurrentDiscoveryServerService());
- serverServices.setEventServerService(getCurrentEventServerService());
- serverServices.setMeasurementServerService(getCurrentMeasurementServerService());
- serverServices.setOperationServerService(getCurrentOperationServerService());
- serverServices.setResourceFactoryServerService(getCurrentResourceFactoryServerService());
-
- conf.setServerServices(serverServices);
-
- return conf;
- }
-
- /**
- * @param pluginResourcePath
- */
- protected void verifyPluginExists(String pluginResourcePath) {
- URL url = getClass().getResource(pluginResourcePath);
-
- File pluginFile = FileUtils.toFile(url);
-
- assert pluginFile!=null : "pluginFile was null";
- assertTrue(pluginFile.exists(), pluginFile.getAbsoluteFile() + " plugin jar could not be found.");
- }
-
- private void copyPlugin(String pluginResourcePath, File pluginDirectory) throws IOException {
- URL pluginUrl = getClass().getResource(pluginResourcePath);
-
- File pluginFile = new File(pluginResourcePath);
- String pluginFileName = pluginFile.getName();
-
- FileUtils.copyURLToFile(pluginUrl, new File(pluginDirectory, pluginFileName));
- }
-
- private Set<Resource> getTestingResources(String resourceTypeName, String resourceTypePluginName) {
- ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager()
- .getType(resourceTypeName, resourceTypePluginName);
-
- return getCurrentServerSideInventory().findResourcesByType(resType);
- }
-
- protected void executeTestWithPlugins(Set<String> pluginResourcePaths, TestPayload test) throws Exception {
- FileUtils.cleanDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
-
- for (String pluginResourcePath : pluginResourcePaths) {
- copyPlugin(pluginResourcePath, pluginDir);
- }
-
- Mockery context = new Mockery();
-
- PluginContainerConfiguration pcConfig = createPluginContainerConfiguration(context);
-
- if (test.isClearInventoryDat()) {
- File inventoryDat = new File(pcConfig.getDataDirectory(), "inventory.dat");
- inventoryDat.delete();
- }
-
- context.checking(test.getExpectations(context));
-
- PluginContainer.getInstance().setConfiguration(pcConfig);
- PluginContainer.getInstance().initialize();
-
- try {
- //give the pc the time to finish resource upgrade
- while (!PluginContainer.getInstance().isStarted()) {
- Thread.sleep(500);
- }
-
- //execute full discovery
- InventoryManager im = PluginContainer.getInstance().getInventoryManager();
- im.executeServerScanImmediately();
-
- //do the service scan a couple of times so that we can commit
- //the resources deep in the type hierarchy
- for(int i = 0; i < 10; ++i) {
- im.executeServiceScanImmediately();
- }
-
- Map<ResType, Set<Resource>> resources = new HashMap<ResType, Set<Resource>>();
-
- for(ResType type : test.getExpectedResourceTypes()) {
- Set<Resource> rs = getTestingResources(type.getResourceTypeName(), type.getResourceTypePluginName());
- resources.put(type, rs);
- }
-
- test.test(resources);
-
- context.assertIsSatisfied();
- } finally {
- PluginContainer.getInstance().shutdown();
- }
- }
+public abstract class ResourceUpgradeTestBase extends PluginContainerTest {
@SuppressWarnings("unchecked")
- protected void defineDefaultExpectations(Expectations expectations) {
- expectations.ignoring(getCurrentBundleServerService());
- expectations.ignoring(getCurrentConfigurationServerService());
- expectations.ignoring(getCurrentContentServerService());
- expectations.ignoring(getCurrentCoreServerService());
- expectations.ignoring(getCurrentEventServerService());
- expectations.ignoring(getCurrentMeasurementServerService());
- expectations.ignoring(getCurrentOperationServerService());
- expectations.ignoring(getCurrentResourceFactoryServerService());
+ protected void defineDefaultExpectations(FakeServerInventory inventory, Expectations expectations) {
+ ServerServices ss = pluginContainerConfiguration.getServerServices();
+
+ expectations.ignoring(ss.getBundleServerService());
+ expectations.ignoring(ss.getConfigurationServerService());
+ expectations.ignoring(ss.getContentServerService());
+ expectations.ignoring(ss.getCoreServerService());
+ expectations.ignoring(ss.getEventServerService());
+ expectations.ignoring(ss.getMeasurementServerService());
+ expectations.ignoring(ss.getOperationServerService());
+ expectations.ignoring(ss.getResourceFactoryServerService());
//just ignore these invocations if we get a availability scan in the PC...
- expectations.allowing(getCurrentDiscoveryServerService()).mergeAvailabilityReport(
+ expectations.allowing(ss.getDiscoveryServerService()).mergeAvailabilityReport(
expectations.with(Expectations.any(AvailabilityReport.class)));
- expectations.allowing(getCurrentDiscoveryServerService()).getResources(
+ expectations.allowing(ss.getDiscoveryServerService()).getResources(
expectations.with(Expectations.any(Set.class)), expectations.with(Expectations.any(boolean.class)));
- expectations.will(getCurrentServerSideInventory().getResources());
+ expectations.will(inventory.getResources());
- expectations.allowing(getCurrentDiscoveryServerService()).postProcessNewlyCommittedResources(
+ expectations.allowing(ss.getDiscoveryServerService()).postProcessNewlyCommittedResources(
expectations.with(Expectations.any(Set.class)));
}
- protected void cleanDataDir() throws IOException {
- FileUtils.cleanDirectory(new File(tmpDir, DATA_DIR_NAME));
+ protected Set<Resource> getTestingResources(FakeServerInventory serverInventory, ResType type) {
+ ResourceType resType = PluginContainer.getInstance().getPluginManager().getMetadataManager()
+ .getType(type.getResourceTypeName(), type.getResourceTypePluginName());
+
+ return serverInventory.findResourcesByType(resType);
}
}
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java
new file mode 100644
index 0000000..a6baff0
--- /dev/null
+++ b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerSetup.java
@@ -0,0 +1,118 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.test.pc;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.rhq.core.pc.ServerServices;
+
+/**
+ * This annotation represents the setup of the plugin container to be
+ * performed before each test.
+ * @author Lukas Krejci
+ */
+(a)Retention(RetentionPolicy.RUNTIME)
+(a)Target({ElementType.METHOD, ElementType.TYPE})
+public @interface PluginContainerSetup {
+
+ /**
+ * The list of plugin URIs that should be loaded into the plugin container.
+ * The "classpath" scheme can be used in the URI to specify that the plugin
+ * is stored in the classpath of the test being executed. Other schemes are
+ * resolved as usual.
+ * <p>
+ * Examples of URIs:
+ * <ul>
+ * <li> classpath:///test-plugin.jar
+ * <li> file:///some/location/on/the/filesystem.jar
+ * <li> http://www.rhq-project.org/tests/test-plugin.jar
+ */
+ String[] plugins();
+
+ /**
+ * If specified, the plugin container setups with the same shared group will
+ * be invoked with the same directory layout for storing inventory, data and plugin
+ * files.
+ * <p>
+ * This enables the persistent data to survive among different plugin container
+ * runs which is useful for example to test plugin upgrades. We need to test for different
+ * things in each plugin container run, we need to deploy different plugins to the
+ * plugin container, yet we usually want the persisted inventory to survive.
+ * <p>
+ * By default each test creates a new directory layout.
+ */
+ String sharedGroup() default "";
+
+ /**
+ * Whether the plugin container should be started and initialized before
+ * the control is handed over to the test method.
+ * <p>
+ * Default is false.
+ */
+ boolean startImmediately() default false;
+
+ /**
+ * If the plugin container is {@link #inAgent()}, it persists the state of
+ * the inventory in a 'inventory.dat' file.
+ * <p>
+ * Because the plugin container test can start up the PC using the same
+ * directories to use (using the {@link #sharedGroup()} grouping), the persisted
+ * inventory can be shared between multiple tests.
+ * <p>
+ * The default value is true.
+ */
+ boolean clearInventoryDat() default true;
+
+ /**
+ * Whether to clear the data directory of the plugin container
+ */
+ boolean clearDataDir() default false;
+
+ /**
+ * The number of server and service discoveries executed before the control
+ * is handed over to the test method. This is useful if you have deep hierarchies
+ * of server resources that only get committed a level at a time.
+ * <p>
+ * If set to 0, no discoveries will be performed.
+ * <p>
+ * The default value is 1.
+ */
+ int numberOfInitialDiscoveries() default 1;
+
+ /**
+ * Should the plugin container be set to think it runs inside an agent?
+ * <p>
+ * The default is true.
+ */
+ boolean inAgent() default true;
+
+ /**
+ * By default the PluginContainerTest
+ * By default the {@link ServerServices} the plugin container will be initialized with
+ * will contain the mocked out interfaces of the individual services.
+ * <p>
+ * If you need to provide custom implementations, you can tell the setup
+ * to use the instance returned by the method named using this attribute.
+ */
+ String pluginConfigurationProviderMethod() default "";
+}
diff --git a/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java
new file mode 100644
index 0000000..7e91ede
--- /dev/null
+++ b/modules/core/plugin-container/src/test/java/org/rhq/test/pc/PluginContainerTest.java
@@ -0,0 +1,397 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.test.pc;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URL;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.io.FileUtils;
+import org.jmock.Mockery;
+import org.testng.ITestResult;
+import org.testng.annotations.AfterSuite;
+import org.testng.annotations.Listeners;
+
+import org.rhq.core.clientapi.server.bundle.BundleServerService;
+import org.rhq.core.clientapi.server.configuration.ConfigurationServerService;
+import org.rhq.core.clientapi.server.content.ContentServerService;
+import org.rhq.core.clientapi.server.core.CoreServerService;
+import org.rhq.core.clientapi.server.discovery.DiscoveryServerService;
+import org.rhq.core.clientapi.server.event.EventServerService;
+import org.rhq.core.clientapi.server.inventory.ResourceFactoryServerService;
+import org.rhq.core.clientapi.server.measurement.MeasurementServerService;
+import org.rhq.core.clientapi.server.operation.OperationServerService;
+import org.rhq.core.pc.PluginContainer;
+import org.rhq.core.pc.PluginContainerConfiguration;
+import org.rhq.core.pc.ServerServices;
+import org.rhq.core.pc.inventory.InventoryManager;
+import org.rhq.core.pc.plugin.FileSystemPluginFinder;
+import org.rhq.test.JMockTest;
+
+/**
+ * This class is similar to {@link JMockTest} in that it can be used both
+ * as a base class to your test or as a TestNG {@link Listeners listener}
+ * on your test class.
+ * <p>
+ * This class is used to declaratively setup a plugin container a test wants
+ * to use using the {@link PluginContainerSetup} annotation on a test method or class.
+ *
+ * @author Lukas Krejci
+ */
+public class PluginContainerTest extends JMockTest {
+ private static final File ROOT;
+ private static boolean cleanedUp = false;
+
+ private static final String PLUGINS_DIR_NAME = "plugins";
+
+ private static final String DATA_DIR_NAME = "data";
+ private static final String TMP_DIR_NAME = "tmp";
+
+ private static final ThreadLocal<PluginContainerConfiguration> STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION = new ThreadLocal<PluginContainerConfiguration>();
+
+ private static final ThreadLocal<PluginContainerSetup> CURRENT_SETUP = new ThreadLocal<PluginContainerSetup>();
+
+ private static final Map<String, Object> SERVERSIDE_FAKES = Collections.synchronizedMap(new HashMap<String, Object>());
+
+ protected PluginContainerConfiguration pluginContainerConfiguration;
+
+ static {
+ File f = new File(System.getProperty("java.io.tmpdir"), "plugin-container-test-" + System.currentTimeMillis());
+ while (f.exists() || !f.mkdir()) {
+ f = new File(System.getProperty("java.io.tmpdir"), "plugin-container-test-" + System.currentTimeMillis());
+ }
+
+ ROOT = f;
+ }
+
+ /**
+ * During the tests, one might need to "fake" responses that come to the plugin container
+ * from external sources, like RHQ server. These are usually mocked out using the facilities
+ * provided by JMock.
+ * <p>
+ * This method together with {@link #setServerSideFake(String, Object)} provides a generic
+ * "storage" for tests to share these objects and is only provided as a convenience to
+ * the test writers. There's nothing that would manadate using it.
+ *
+ * @param name
+ * @return
+ */
+ public static Object getServerSideFake(String name) {
+ return SERVERSIDE_FAKES.get(name);
+ }
+
+ /**
+ * The opposite of {@link #getServerSideFake(String)}.
+ */
+ public static void setServerSideFake(String name, Object object) {
+ SERVERSIDE_FAKES.put(name, object);
+ }
+
+ /**
+ * Returns the {@link PluginContainerConfiguration} as configured using
+ * the {@link PluginContainerSetup} annotation on the current test (or null
+ * if no such thing is configured).
+ * @return
+ */
+ public static PluginContainerConfiguration getCurrentPluginContainerConfiguration() {
+ return STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.get();
+ }
+
+ @Override
+ protected void initBeforeTest(Object testObject, Method testMethod) {
+ super.initBeforeTest(testObject, testMethod);
+
+ CURRENT_SETUP.set(getSetup(testMethod));
+
+ if (CURRENT_SETUP.get() != null) {
+ try {
+ initPluginContainerConfiguration(testObject, testMethod);
+ initDirectoryStructure();
+ deployPlugins(testObject, pluginContainerConfiguration.getPluginDirectory(), CURRENT_SETUP.get());
+
+ PluginContainer.getInstance().setConfiguration(pluginContainerConfiguration);
+
+ if (CURRENT_SETUP.get().clearInventoryDat()) {
+ File inventoryDat = new File(pluginContainerConfiguration.getDataDirectory(), "inventory.dat");
+ inventoryDat.delete();
+ }
+
+ if (CURRENT_SETUP.get().startImmediately()) {
+ startConfiguredPluginContainer();
+ }
+ } catch (Throwable t) {
+ throw new IllegalStateException("Failed to setup the plugin container.", t);
+ }
+ }
+ }
+
+ @Override
+ protected void tearDownAfterTest(ITestResult testResult) {
+ try {
+ deletePlugins(pluginContainerConfiguration.getPluginDirectory());
+ } catch (Exception e) {
+ //hmmm
+ } finally {
+ PluginContainer.getInstance().shutdown();
+ super.tearDownAfterTest(testResult);
+ }
+ }
+
+ /**
+ * Starts the plugin container. This method is supposed to be called from tests that
+ * need to start the plugin container manually after it has been configured using
+ * the {@link PluginContainerSetup} annotation.
+ */
+ public static void startConfiguredPluginContainer() {
+ PluginContainer.getInstance().setConfiguration(getCurrentPluginContainerConfiguration());
+
+ PluginContainer.getInstance().initialize();
+
+ try {
+ while (!PluginContainer.getInstance().isStarted()) {
+ Thread.sleep(100);
+ }
+ } catch (InterruptedException e) {
+ throw new IllegalStateException("Thread interrupted while waiting for plugin container to start.");
+ }
+
+ InventoryManager im = PluginContainer.getInstance().getInventoryManager();
+ for (int i = 0; i < CURRENT_SETUP.get().numberOfInitialDiscoveries(); ++i) {
+ im.executeServerScanImmediately();
+ im.executeServiceScanImmediately();
+ }
+ }
+
+ /**
+ * This method can be called in the after methods of the tests to clear up data
+ * left after the plugin container run.
+ * <p>
+ * This is not done automatically to support sharing the plugin container among
+ * multiple tests to simulate upgrades, etc.
+ *
+ * @throws IOException
+ */
+ public static void clearStorageOfCurrentPluginContainer() throws IOException {
+ File f = STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.get().getPluginDirectory();
+ f = f.getParentFile();
+
+ if (f.exists()) {
+ FileUtils.cleanDirectory(f);
+
+ f.delete();
+ }
+ }
+
+ /**
+ * This method clears the storage of all tests made. This is useful in {@link AfterSuite}
+ * method to clean up after all the tests (annotated with {@link PluginContainerSetup})
+ * that have been run.
+ *
+ * @throws IOException
+ */
+ public synchronized static void clearStorage() throws IOException {
+ if (!cleanedUp) {
+ FileUtils.cleanDirectory(ROOT);
+ ROOT.delete();
+ cleanedUp = true;
+ }
+ }
+
+ /**
+ * If PluginContainerTest is used as a base class to your tests (and not as a {@link Listeners listener},
+ * this method is provided to automatically clean up after all the plugin container tests that ran
+ * in the test suite.
+ * <p>
+ * If you use PluginContainerTest as a listener, you have to call {@link #clearStorage()} method
+ * on your own.
+ *
+ * @throws IOException
+ */
+ @AfterSuite
+ public void cleanUpAfterPluginContainerTests() throws IOException {
+ clearStorage();
+ }
+
+ /**
+ * This method returns the {@link PluginContainerConfiguration} that will be used in
+ * the current test as was configured by the PluginContainerSetup annotation.
+ * <p>
+ * If your test class inherits from PluginContainerTest, you can override this method
+ * to provide custom configuration.
+ *
+ * @param testObject the object of the current test
+ * @param testMethod the test method currently being executed on the test object
+ * @return
+ */
+ protected PluginContainerConfiguration createPluginConfigurationToUse(Object testObject, Method testMethod) {
+ PluginContainerSetup setup = CURRENT_SETUP.get();
+
+ if (setup.pluginConfigurationProviderMethod().isEmpty()) {
+ return createDefaultPluginConfiguration(setup, context);
+ } else {
+ String providerName = setup.pluginConfigurationProviderMethod();
+ Class<?> testClass = testMethod.getDeclaringClass();
+ try {
+ Method pluginContainerProvider = testClass.getMethod(providerName, (Class<?>[]) null);
+
+ if (!PluginContainerConfiguration.class.isAssignableFrom(pluginContainerProvider.getReturnType())) {
+ throw new IllegalStateException("The configured pluginConfigurationProviderMethod '" + providerName + "' on the test class '" + testClass + "' does not return a PluginContainerConfiguration.");
+ }
+
+ return (PluginContainerConfiguration) pluginContainerProvider.invoke(testObject, (Object[]) null);
+ } catch (SecurityException e) {
+ throw new IllegalStateException("The configured pluginConfigurationProviderMethod '" + providerName + "' could not be found on the test class '" + testClass + "'.", e);
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException("The configured pluginConfigurationProviderMethod '" + providerName + "' could not be found on the test class '" + testClass + "'.", e);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException("Failed to invoke method '" + providerName + "' on test class '" + testClass + "'.", e);
+ } catch (InvocationTargetException e) {
+ throw new IllegalStateException("Failed to invoke method '" + providerName + "' on test class '" + testClass + "'.", e);
+ }
+ }
+ }
+
+ /**
+ * This method is called after the test to tear down resources associated with the
+ * current plugin container configuration.
+ */
+ protected void tearDownPluginContainerConfiguration() {
+ pluginContainerConfiguration = null;
+ STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.set(null);
+ }
+
+ private void initPluginContainerConfiguration(Object testObject, Method testMethod) {
+ pluginContainerConfiguration = createPluginConfigurationToUse(testObject, testMethod);
+ STATICALLY_ACCESSIBLE_PLUGIN_CONTAINER_CONFIGURATION.set(pluginContainerConfiguration);
+ }
+
+ private static PluginContainerSetup getSetup(Method method) {
+ PluginContainerSetup setup = method.getAnnotation(PluginContainerSetup.class);
+
+ if (setup == null) {
+ setup = method.getDeclaringClass().getAnnotation(PluginContainerSetup.class);
+ }
+
+ return setup;
+ }
+
+ private void initDirectoryStructure() {
+ File pluginDir = pluginContainerConfiguration.getPluginDirectory();
+ File dataDir = pluginContainerConfiguration.getDataDirectory();
+ File tempDir = pluginContainerConfiguration.getTemporaryDirectory();
+
+ pluginDir.mkdirs();
+ dataDir.mkdirs();
+ tempDir.mkdirs();
+ }
+
+ private static PluginContainerConfiguration createDefaultPluginConfiguration(PluginContainerSetup setup, Mockery context) {
+ PluginContainerConfiguration conf = new PluginContainerConfiguration();
+
+ File tmpDir = createTemporaryDirectory(setup);
+
+ conf.setPluginDirectory(new File(tmpDir, PLUGINS_DIR_NAME));
+ conf.setDataDirectory(new File(tmpDir, DATA_DIR_NAME));
+ conf.setTemporaryDirectory(new File(tmpDir, TMP_DIR_NAME));
+ conf.setInsideAgent(setup.inAgent());
+ conf.setPluginFinder(new FileSystemPluginFinder(conf.getPluginDirectory()));
+ conf.setCreateResourceClassloaders(false);
+
+ //we're not interested in any scans happening out of our control
+ conf.setAvailabilityScanInitialDelay(Long.MAX_VALUE);
+ conf.setConfigurationDiscoveryInitialDelay(Long.MAX_VALUE);
+ conf.setContentDiscoveryInitialDelay(Long.MAX_VALUE);
+ conf.setEventSenderInitialDelay(Long.MAX_VALUE);
+ conf.setMeasurementCollectionInitialDelay(Long.MAX_VALUE);
+ conf.setServerDiscoveryInitialDelay(Long.MAX_VALUE);
+ conf.setServiceDiscoveryInitialDelay(Long.MAX_VALUE);
+
+ ServerServices serverServices = new ServerServices();
+ serverServices.setBundleServerService(context.mock(BundleServerService.class));
+ serverServices.setConfigurationServerService(context.mock(ConfigurationServerService.class));
+ serverServices.setContentServerService(context.mock(ContentServerService.class));
+ serverServices.setCoreServerService(context.mock(CoreServerService.class));
+ serverServices.setDiscoveryServerService(context.mock(DiscoveryServerService.class));
+ serverServices.setEventServerService(context.mock(EventServerService.class));
+ serverServices.setMeasurementServerService(context.mock(MeasurementServerService.class));
+ serverServices.setOperationServerService(context.mock(OperationServerService.class));
+ serverServices.setResourceFactoryServerService(context.mock(ResourceFactoryServerService.class));
+
+ conf.setServerServices(serverServices);
+
+ return conf;
+ }
+
+ private void deployPlugins(Object testObject, File destination, PluginContainerSetup setup) throws IOException {
+ for(String plugin : setup.plugins()) {
+ copyPluginToDestination(testObject, plugin, destination);
+ }
+ }
+
+ private void deletePlugins(File deployDirectory) throws IOException {
+ if (deployDirectory.exists()) {
+ FileUtils.cleanDirectory(deployDirectory);
+ }
+ }
+
+ private static File createTemporaryDirectory(PluginContainerSetup setup) {
+ String name = null;
+ boolean mustBeNew = true;
+ if (setup.sharedGroup().length() > 0) {
+ name = setup.sharedGroup();
+ mustBeNew = false;
+ } else {
+ name = Long.toString(System.currentTimeMillis());
+ }
+
+ File ret = new File(ROOT, name);
+
+ while (mustBeNew && (ret.exists() || !ret.mkdir())) {
+ ret = new File(ROOT, Long.toString(System.currentTimeMillis()));
+ }
+
+ return ret;
+ }
+
+ private File copyPluginToDestination(Object testObject, String plugin, File destination) throws IOException {
+ URI pluginUri = URI.create(plugin);
+ URL pluginUrl = null;
+ if ("classpath".equals(pluginUri.getScheme())) {
+ String path = pluginUri.getPath();
+ pluginUrl = testObject.getClass().getResource(path);
+ } else {
+ pluginUrl = pluginUri.toURL();
+ }
+
+
+ String pluginFileName = pluginUri.getPath().substring(pluginUri.getPath().lastIndexOf('/') + 1);
+
+ File pluginJar = new File(destination, pluginFileName);
+ FileUtils.copyURLToFile(pluginUrl, pluginJar);
+
+ return pluginJar;
+ }
+}
diff --git a/modules/plugins/pom.xml b/modules/plugins/pom.xml
index f51a2ed..d1863d4 100644
--- a/modules/plugins/pom.xml
+++ b/modules/plugins/pom.xml
@@ -55,6 +55,21 @@
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>${rhq.groupId}</groupId>
+ <artifactId>rhq-core-plugin-container</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>${rhq.groupId}</groupId>
+ <artifactId>test-utils</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
<!--
TODO: This is a fix for the Javac bug requiring annotations to be available when compiling dependent classes.
It is fixed in JDK 6.
diff --git a/modules/test-utils/pom.xml b/modules/test-utils/pom.xml
index 89fbc3c..3ed6856 100644
--- a/modules/test-utils/pom.xml
+++ b/modules/test-utils/pom.xml
@@ -75,7 +75,13 @@
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-testng</artifactId>
- <version>3.1</version>
+ <version>3.1</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
diff --git a/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java b/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
index f3add4e..2088460 100644
--- a/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
+++ b/modules/test-utils/src/main/java/org/rhq/test/JMockTest.java
@@ -23,29 +23,145 @@
package org.rhq.test;
+import java.lang.reflect.Method;
+
import org.jmock.Mockery;
import org.testng.IHookCallBack;
import org.testng.IHookable;
+import org.testng.IInvokedMethod;
+import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Listeners;
-public class JMockTest implements IHookable {
+/**
+ * This class can either be used as a base class for tests using JMock
+ * or it also can be used as a TestNG listener to provide the JMock
+ * context to test classes that need to inherit from another class.
+ * <p>
+ * In the former case, the JMock context is accessible through the {@link #context} protected
+ * field, while in the latter case (when JMockTest is specified as a {@link Listeners listener}
+ * of a test class), the JMock context is accessible using the {@link #getCurrentMockContext()}
+ * static method.
+ *
+ * @author John Sanda
+ * @author Lukas Krejci
+ */
+public class JMockTest implements IHookable, IInvokedMethodListener {
protected Mockery context;
- @BeforeMethod
- public void initContext() {
- context = new Mockery();
+ private static final ThreadLocal<Mockery> STATICALLY_ACCESSIBLE_CONTEXT = new ThreadLocal<Mockery>();
+
+ private boolean initRan;
+ private boolean tearDownRan;
+
+ /**
+ * @return the JMock context of the current test or null if the calling test class doesn't have
+ * this class set as a listener or doesn't inherit from this class.
+ */
+ public static Mockery getCurrentMockContext() {
+ return STATICALLY_ACCESSIBLE_CONTEXT.get();
}
- public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {
+ @BeforeMethod
+ public void initMockContext(Method testMethod) {
+ if (!initRan) {
+ initBeforeTest(this, testMethod);
+ }
+ tearDownRan = false;
+ initRan = true;
+ }
+
+ @AfterMethod
+ public void tearDownMockContext(ITestResult testResult) {
+ if (!tearDownRan) {
+ tearDownAfterTest(testResult);
+ }
+ tearDownRan = true;
+ initRan = false;
+ }
+
+ /**
+ * This method runs {@link #initBeforeTest(ITestResult)}, followed by the actual test,
+ * followed by {@link #tearDownAfterTest(ITestResult)}.
+ * <p>
+ * If you want to modify the behavior of this method, override the above mentioned
+ * methods.
+ *
+ * @see IHookable#run(IHookCallBack, ITestResult)
+ */
+ public final void run(IHookCallBack iHookCallBack, ITestResult iTestResult) {
iHookCallBack.runTestMethod(iTestResult);
+ }
+
+ /**
+ * Runs {@link #initBeforeTest(ITestResult)}.
+ *
+ * @see IInvokedMethodListener#beforeInvocation(IInvokedMethod, ITestResult)
+ */
+ public final void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
+ if (!initRan) {
+ initBeforeTest(testResult.getInstance(), testResult.getMethod().getMethod());
+ }
+ initRan = true;
+ tearDownRan = false;
+ }
+
+ /**
+ * Runs {@link #tearDownAfterTest(ITestResult)}.
+ *
+ * @see IInvokedMethodListener#afterInvocation(IInvokedMethod, ITestResult)
+ */
+ public final void afterInvocation(IInvokedMethod method, ITestResult testResult) {
+ if (!tearDownRan) {
+ tearDownAfterTest(testResult);
+ }
+ initRan = false;
+ tearDownRan = true;
+ }
+
+ /**
+ * Does whatever needs done before the test is invoked.
+ * <p>
+ * If you override this method, be sure to call this method <b>before</b>
+ * your code so that you gain access to the {@link #context}.
+ *
+ * @param testResult
+ */
+ protected void initBeforeTest(Object testObject, Method testMethod) {
+ initContext();
+ }
+
+ /**
+ * Does whatever needs done after the test has been invoked.
+ * <p>
+ * This method calls {@link Mockery#assertIsSatisfied()} and nulls out the {@link #context}.
+ * <p>
+ * If you override this method, call this implmentation as the last call in your code.
+ * @param result
+ */
+ protected void tearDownAfterTest(ITestResult result) {
try {
context.assertIsSatisfied();
+ } catch (Throwable t) {
+ result.setStatus(ITestResult.FAILURE);
+ result.setThrowable(t);
+ } finally {
+ tearDownContext();
}
- catch (Throwable t) {
- iTestResult.setStatus(ITestResult.FAILURE);
- iTestResult.setThrowable(t);
- }
+ }
+
+ private void initContext() {
+ context = new Mockery();
+ STATICALLY_ACCESSIBLE_CONTEXT.set(context);
+ }
+
+ private void tearDownContext() {
+ context = null;
+ //null out the static field so that the GC can
+ //collect the no-longer used context.
+ STATICALLY_ACCESSIBLE_CONTEXT.set(null);
}
}
12 years, 11 months
[rhq] 2 commits - modules/core modules/enterprise
by Jay Shaughnessy
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceFactoryManager.java | 84 +++++++---
modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html | 2
2 files changed, 60 insertions(+), 26 deletions(-)
New commits:
commit 68414c5dda7381a72816a8754151c62e4ad29541
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Wed May 25 17:11:35 2011 -0400
Add missing element terminator.
diff --git a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html
index d589fa8..94d9621 100644
--- a/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html
+++ b/modules/enterprise/gui/coregui/src/main/webapp/CoreGUI.html
@@ -8,7 +8,7 @@
Note, when building the app, you must include the "ie6" gwt.userAgent since we're emulating IE7 (which
requires the "ie6" userAgent.
-->
- <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
+ <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<!-- support internationalized characters -->
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
commit c4432f792961c2ce406cf0f9a0be4847842260f7
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Wed May 25 17:11:05 2011 -0400
[BZ 707759 - Deployment of new WAR to EAP server fails due to thread timeout - Need configurable thread timeout]
Provide overrides for the default 60 second timeout of create and
delete child actions.
In general 60s may be enough but for applications that need time to deploy,
or perhaps to shut down gracefully, this can be too short. The overrides
are blunt in that they affect all types. And it should be noted that while
creating(deploying) or deleting the child resource, the parent resource will
be write-locked, meaning deferred metric reporting etc. So, it it recommended
that when possible fast create and delete is performed for these facet
implementations.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceFactoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceFactoryManager.java
index 161596e..cd0bfcc 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceFactoryManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/ResourceFactoryManager.java
@@ -1,25 +1,25 @@
- /*
- * RHQ Management Platform
- * Copyright (C) 2005-2008 Red Hat, Inc.
- * All rights reserved.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License, 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.
- */
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License, 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.pc.inventory;
import java.util.Set;
@@ -62,7 +62,41 @@ import org.rhq.core.pluginapi.inventory.DeleteResourceFacet;
* @author Jason Dobies
*/
public class ResourceFactoryManager extends AgentService implements ContainerService, ResourceFactoryAgentService {
- private static final int FACET_METHOD_TIMEOUT = 60 * 1000; // 60 seconds
+
+ // This used to be a single value fixed at 60 seconds. But create and delete actions can very well exceed 1 minute
+ // depending on the type of resource being created, or perhaps graceful shutdown of a resource being deleted. So,
+ // allow the timeout value to be overriden by editing rhq-agent-env.sh with new -D settings. Also, create separate
+ // timeouts for create and delete, as their execution times really are not related. The properties are set in
+ // milliseconds:
+ // rhq.agent.plugins.facet.create-child-resource.timeout
+ // rhq.agent.plugins.facet.delete-resource.timeout
+ //
+ // The default is still 60s. Note that increasing this value affects all types across all plugins and should not
+ // be raised unless a successful create or delete action requires the higher limit. Realize that while a
+ // create or delete is in progress that the resource is write-locked, so no other actions can take place (like
+ // metric collection).
+ //
+ // TODO: Add a timeout to the create resource wizard that can be set as an override for a single create action.
+ private static final int FACET_CREATE_TIMEOUT;
+ private static final int FACET_DELETE_TIMEOUT;
+
+ static {
+ int timeout;
+ try {
+ timeout = Integer.parseInt(System.getProperty("rhq.agent.plugins.facet.create-child-resource.timeout",
+ "60000"));
+ } catch (Throwable t) {
+ timeout = 60 * 1000;
+ }
+ FACET_CREATE_TIMEOUT = timeout;
+
+ try {
+ timeout = Integer.parseInt(System.getProperty("rhq.agent.plugins.facet.delete-resource.timeout", "60000"));
+ } catch (Throwable t) {
+ timeout = 60 * 1000;
+ }
+ FACET_DELETE_TIMEOUT = timeout;
+ }
// Attributes --------------------------------------------
@@ -235,7 +269,7 @@ public class ResourceFactoryManager extends AgentService implements ContainerSer
*/
private DeleteResourceFacet getDeleteResourceFacet(int resourceId) throws PluginContainerException {
DeleteResourceFacet facet = ComponentUtil.getComponent(resourceId, DeleteResourceFacet.class,
- FacetLockType.WRITE, FACET_METHOD_TIMEOUT, false, true);
+ FacetLockType.WRITE, FACET_DELETE_TIMEOUT, false, true);
return facet;
}
@@ -251,7 +285,7 @@ public class ResourceFactoryManager extends AgentService implements ContainerSer
*/
private CreateChildResourceFacet getCreateChildResourceFacet(int parentResourceId) throws PluginContainerException {
CreateChildResourceFacet facet = ComponentUtil.getComponent(parentResourceId, CreateChildResourceFacet.class,
- FacetLockType.WRITE, FACET_METHOD_TIMEOUT, false, true);
+ FacetLockType.WRITE, FACET_CREATE_TIMEOUT, false, true);
return facet;
}
12 years, 11 months
[rhq] modules/core
by John Sanda
modules/core/dbutils/pom.xml | 16 +++++++---------
1 file changed, 7 insertions(+), 9 deletions(-)
New commits:
commit f594ce268fdcb8e111ccc4e125bf91640e3a6862
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed May 25 16:21:30 2011 -0400
Refactoring logic in dbreset script for use with upgrade db
The database name comes from settings.xml for hudson builds. If you want
to develop/test against a database on which you have run dbupgrade, then
you can run maven with -Dupgrade.db and it will use the rhqupgrade
database.
diff --git a/modules/core/dbutils/pom.xml b/modules/core/dbutils/pom.xml
index 063f2ce..800cb87 100644
--- a/modules/core/dbutils/pom.xml
+++ b/modules/core/dbutils/pom.xml
@@ -105,21 +105,19 @@
server = project.properties['rhq.dev.ds.server-name'] ?: '127.0.0.1'
rhqUser = project.properties['rhq.dev.ds.user-name'] ?: 'rhqadmin'
}
- // This is a bit of a temporary hack to work around
- // https://cvs.codehaus.org/browse/GMAVEN-46 which results in
- // groovy scripts not being able to get the correct values of
- // build properties that are overridden on the command line.
- // This is being done in support of the hudson job which is
- // trying to use a database named rhqupgrade.
- else if (project.properties['upgrade.db']) {
- database = 'rhqupgrade'
- }
else {
database = project.properties['rhq.test.ds.db-name']
server = project.properties['rhq.test.ds.server-name'] ?: '127.0.0.1'
rhqUser = project.properties['rhq.test.ds.user-name'] ?: 'rhqadmin'
}
+ // The upgrade.db property should be set for local builds when you
+ // need to test upgrade changes. Hudson builds will specify the
+ // database to use in settings.xml
+ if (project.properties['upgrade.db']) {
+ database = 'rhqupgrade'
+ }
+
adminUsername = project.properties['rhq.db.admin.username'] ?: 'postgres'
adminPassword = project.properties['rhq.db.admin.password'] ?: 'postgres'
project.properties.dbsetup = 'true'
12 years, 11 months
[rhq] Branch 'drift' - modules/core
by John Sanda
modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java | 4
modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java | 129 +++++++---
2 files changed, 103 insertions(+), 30 deletions(-)
New commits:
commit b148b2b2ee623c6c6527271e5d6cdf609b5d664c
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed May 25 14:07:35 2011 -0400
Updating tests to avoid transaction timeouts
loadMultipleSnapshotsWithoutLoadingData() was loading all of the
snapshots in a single transaction which was timing out. This isn't
surprising giving the size and number of snapshots. I have refactored
the test to persist and load each snapshot in a separate transaction.
Adding the test updateSnapshotData(). This method first persists a new
snapshot, then loads it from the database, then updates the blob, and
then finally writes it back to the database.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java
index 6fee160..48c64f1 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/Snapshot.java
@@ -57,6 +57,10 @@ public class Snapshot implements Serializable {
// this.data = data;
// }
+ public Blob getBlob() {
+ return data;
+ }
+
public InputStream getData() throws SQLException {
return data.getBinaryStream();
}
diff --git a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java
index 3e85479..4c476ff 100644
--- a/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java
+++ b/modules/core/domain/src/test/java/org/rhq/core/domain/drift/SnapshotTest.java
@@ -5,18 +5,18 @@ import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
-import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
-import java.sql.Connection;
+import java.sql.Blob;
import java.util.ArrayList;
import java.util.List;
-import javax.print.URIException;
+import javax.transaction.SystemException;
import org.apache.commons.io.IOUtils;
import org.hibernate.Hibernate;
-import org.hibernate.Session;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;
import org.rhq.core.domain.test.AbstractEJB3Test;
@@ -25,48 +25,117 @@ import static org.apache.commons.io.IOUtils.toInputStream;
public class SnapshotTest extends AbstractEJB3Test {
- @Test(groups = "integration.ejb3")
- public void loadSnapshotWithoutData() throws Exception {
- String content = "This is a test";
+ static interface TransactionCallback {
+ void execute() throws Exception;
+ }
- getTransactionManager().begin();
- Snapshot snapshot = new Snapshot();
- snapshot.setDataSize(content.length());
- snapshot.setData(Hibernate.createBlob(toInputStream(content), content.length()));
+ @BeforeGroups(groups = {"snapshot"})
+ public void resetDB() throws Exception {
+ executeInTransaction(new TransactionCallback() {
+ @Override
+ public void execute() throws Exception {
+ getEntityManager().createQuery("delete from Snapshot").executeUpdate();
+ }
+ });
+ }
- getEntityManager().persist(snapshot);
- getTransactionManager().commit();
+ @Test(groups = {"integration.ejb3", "snapshot"})
+ public void updateSnapshotData() throws Exception {
+ String content = "snapshot data";
- getTransactionManager().begin();
- snapshot = getEntityManager().find(Snapshot.class, snapshot.getId());
- getTransactionManager().commit();
+ // Create the initial snapshot
+ final Snapshot s1 = new Snapshot();
+ s1.setDataSize(content.length());
+ s1.setData(Hibernate.createBlob(toInputStream(content), content.length()));
- System.out.println("data size = " + snapshot.getDataSize());
+ executeInTransaction(new TransactionCallback() {
+ @Override
+ public void execute() {
+ getEntityManager().persist(s1);
+ }
+ });
+
+ // Make the update
+ final String newContent = "snapshot data updated...";
+ executeInTransaction(new TransactionCallback() {
+ @Override
+ public void execute() {
+ Snapshot s2 = getEntityManager().find(Snapshot.class, s1.getId());
+ s2.setData(Hibernate.createBlob(toInputStream(newContent), newContent.length()));
+ getEntityManager().merge(s2);
+ }
+ });
+
+ // Fetch the snapshot to verify that the update was persisted
+ executeInTransaction(new TransactionCallback() {
+ @Override
+ public void execute() {
+ try {
+ Snapshot s3 = getEntityManager().find(Snapshot.class, s1.getId());
+ String expected = newContent;
+ String actual = IOUtils.toString(s3.getData());
+
+ assertEquals("Failed to update snapshot data", expected, actual);
+ } catch (Exception e) {
+ fail("Failed to load snapshot data: " + e.getMessage());
+ }
+ }
+ });
}
- @Test(groups = "integration.ejb3")
+ // The purpose of this test is to store a large amount of data and then
+ // load the snapshots to verify that the snapshot data is not also loaded.
+ // Because of the amount data involved is very large the test is long
+ // running and should be moved to an integration test suite.
+ @Test(groups = {"integration.ejb3", "snapshot"})
public void loadMultipleSnapshotsWithoutLoadingData() throws Exception {
File dataFile = createDataFile("test_data.txt", 100);
int numSnapshots = 25;
- List<Integer> snapshotIds = new ArrayList<Integer>();
+ final List<Integer> snapshotIds = new ArrayList<Integer>();
- getTransactionManager().begin();
- for (int i = 0; i < numSnapshots; ++i) {
- Snapshot snapshot = new Snapshot();
+ for (int i = 0; i <numSnapshots; ++i) {
+ final Snapshot snapshot = new Snapshot();
snapshot.setDataSize(dataFile.length());
snapshot.setData(Hibernate.createBlob(new BufferedInputStream(new FileInputStream(dataFile))));
- getEntityManager().persist(snapshot);
- snapshotIds.add(snapshot.getId());
+ executeInTransaction(new TransactionCallback() {
+ @Override
+ public void execute() {
+ getEntityManager().persist(snapshot);
+ snapshotIds.add(snapshot.getId());
+ }
+ });
}
- getTransactionManager().commit();
- getTransactionManager().begin();
- List<Snapshot> snapshots = new ArrayList<Snapshot>();
- for (Integer id : snapshotIds) {
- snapshots.add(getEntityManager().find(Snapshot.class, id));
+ final List<Blob> blobs = new ArrayList<Blob>();
+ final List<Snapshot> snapshots = new ArrayList<Snapshot>();
+ for (final Integer id : snapshotIds) {
+ executeInTransaction(new TransactionCallback() {
+ @Override
+ public void execute() {
+ Snapshot snapshot = getEntityManager().find(Snapshot.class, id);
+ blobs.add(snapshot.getBlob());
+ snapshots.add(snapshot);
+ }
+ });
+ }
+
+ assertEquals("Failed to save or load " + numSnapshots + " snapshots", numSnapshots, snapshots.size());
+ }
+
+ void executeInTransaction(TransactionCallback callback) {
+ try {
+ getTransactionManager().begin();
+ callback.execute();
+ getTransactionManager().commit();
+ } catch (Throwable t) {
+ try {
+ getTransactionManager().rollback();
+ } catch (SystemException e) {
+ throw new RuntimeException("Failed to rollback transaction", e);
+ }
+ throw new RuntimeException(t.getCause());
}
- getTransactionManager().commit();
}
File snapshotDir() throws URISyntaxException {
12 years, 11 months
[rhq] modules/enterprise
by mazz
modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java | 8 ++++++++
1 file changed, 8 insertions(+)
New commits:
commit b2fa19f030d49a99c9449871b03def42d6165bfc
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Wed May 25 12:02:37 2011 -0400
add javadoc
diff --git a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java
index a349f0c..d23dd0a 100644
--- a/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java
+++ b/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java
@@ -45,7 +45,15 @@ import org.hibernate.Hibernate;
import org.hibernate.proxy.HibernateProxy;
/**
+ * This is a single static utility that is used to process any object just prior to sending it over the wire
+ * to remote clients (like GWT clients or remote web service clients).
+ *
+ * Essentially this utility scrubs the object of all Hibernate proxies, cleaning it such that it
+ * can be serialized over the wire successfully.
+ *
* @author Greg Hinkle
+ * @author Jay Shaughnessy
+ * @author John Mazzitelli
*/
@SuppressWarnings("unchecked")
public class HibernateDetachUtility {
12 years, 11 months
[rhq] Branch 'as7plugin' - 5 commits - modules/core modules/plugins
by Heiko W. Rupp
modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventContextImpl.java | 6
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java | 2
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java | 17
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/Domain2Descriptor.java | 140 ++-
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/LoggerComponent.java | 69 +
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/SubsystemDiscovery.java | 5
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 375 +++++++++-
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java | 78 ++
8 files changed, 599 insertions(+), 93 deletions(-)
New commits:
commit 461ef8d5b0b2ec61584dd72b1aae39eef031ec3f
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 25 12:00:20 2011 +0200
Support for the logging subsystem and make deployments available for standalone mode too.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java
index 5c0a499..d86b365 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java
@@ -135,7 +135,7 @@ public class ASConnection {
else {
outcome="- no response from server -";
}
- System.out.println("==> " + outcome);
+// System.out.println("==> " + outcome);
return operationResult;
}
else {
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
index cbc2893..f35720e 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java
@@ -281,8 +281,11 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
}
else {
- propertySimple = new PropertySimple(key,entry.findValue(key).getValueAsText());
- map.put(propertySimple);
+ JsonNode value = entry.findValue(key);
+ if (value!=null){
+ propertySimple = new PropertySimple(key, value.getValueAsText());
+ map.put(propertySimple);
+ }
}
}
@@ -367,9 +370,9 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
return ret;
}
+
PropertySimple putProperty(JsonNode value, PropertyDefinition def) {
String name = def.getName();
- PropertySimpleType type = ((PropertyDefinitionSimple) def).getType();
PropertySimple ps;
if (value==null) {
@@ -380,6 +383,7 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
else
return new PropertySimple(name,null);
}
+ PropertySimpleType type = ((PropertyDefinitionSimple) def).getType();
switch (type) {
case BOOLEAN:
@@ -572,7 +576,12 @@ public class BaseComponent implements ResourceComponent, MeasurementFacet, Confi
resourceKey = addressToPath(serverGroupAddress);
}
else {
- resourceKey = addressToPath(step1.getAddress());
+
+ List<PROPERTY_VALUE> address = step1.getAddress();
+ Operation step3 = new Operation("deploy",address);
+ cop.addStep(step3);
+
+ resourceKey = addressToPath(address);
}
JsonNode result = connection.executeRaw(cop);
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/LoggerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/LoggerComponent.java
new file mode 100644
index 0000000..f0d5e89
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/LoggerComponent.java
@@ -0,0 +1,69 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2011 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.modules.plugins.jbossas7;
+
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.tools.ant.taskdefs.Sleep;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.operation.OperationResult;
+import org.rhq.modules.plugins.jbossas7.json.ComplexResult;
+import org.rhq.modules.plugins.jbossas7.json.Operation;
+
+/**
+ * Component class that deals with the Logging subsystem
+ * @author Heiko W. Rupp
+ */
+public class LoggerComponent extends BaseComponent {
+
+ private final Log log = LogFactory.getLog(LoggerComponent.class);
+
+ @Override
+ public OperationResult invokeOperation(String name,
+ Configuration parameters) throws InterruptedException, Exception {
+
+ Operation op = new Operation(name,pathToAddress(getPath()));
+
+ Map<String,Property> propertyMap = parameters.getAllProperties();
+ for (Map.Entry<String,Property> entry : propertyMap.entrySet()) {
+ PropertySimple ps = (PropertySimple) entry.getValue();
+ op.addAdditionalProperty(entry.getKey(),ps.getStringValue());
+ }
+
+
+ ASConnection conn = getASConnection();
+ ComplexResult result = conn.executeComplex(op);
+
+ if (result.isSuccess()) {
+ return new OperationResult("ok");
+ }
+ else {
+ OperationResult failure = new OperationResult();
+ failure.setErrorMessage(result.getFailureDescription().toString());
+ return failure;
+ }
+
+
+ }
+}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/SubsystemDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/SubsystemDiscovery.java
index a50ea45..a3ab676 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/SubsystemDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/SubsystemDiscovery.java
@@ -134,8 +134,11 @@ public class SubsystemDiscovery implements ResourceDiscoveryComponent<BaseCompon
if (path==null||path.isEmpty())
resKey = newPath;
- else
+ else {
+ if (path.startsWith(","))
+ path = path.substring(1);
resKey = path + "," +childType + "=" + val;
+ }
PropertySimple pathProp = new PropertySimple("path",resKey);
config2.put(pathProp);
diff --git a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
index d7055a3..75484c8 100644
--- a/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
+++ b/modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml
@@ -162,24 +162,6 @@
<c:simple-property name="jvm" required="false"/>
</resource-configuration>
- <service name="Deployment"
- class="BaseComponent"
- discovery="SubsystemDiscovery"
- createDeletePolicy="both"
- creationDataType="content">
- <plugin-configuration>
- <c:simple-property name="path" default="deployment" readOnly="true"/>
- </plugin-configuration>
-
- <content name="file" category="deployable" isCreationType="true" description="Deployments on this server group">
- <configuration>
- <c:group name="deployment" displayName="Deployment Options">
- <c:simple-property name="runtimeName" required="true"/>
- </c:group>
- </configuration>
- </content>
-
- </service>
</server>
<server name="Host"
description="Host involved in this domain"
@@ -375,6 +357,7 @@
<c:simple-property name="journal-type" />
</resource-configuration>
+ <!-- this is no child resource TODO
<service name="Acceptor"
discovery="SubsystemDiscovery"
@@ -392,7 +375,6 @@
<c:simple-property name="path" readOnly="true" default="connector"/>
</plugin-configuration>
</service>
-<!-- this is no child resource
<service name="HQueue"
discovery="SubsystemDiscovery"
class="BaseComponent"
@@ -512,9 +494,9 @@
<metric property="bytesSent" measurementType="trendsup"/>
<metric property="bytesReceived" measurementType="trendsup"/>
- <metric property="processingTime" measurementType="trendsup"/>
+ <metric property="processingTime" measurementType="trendsup" units="milliseconds"/>
<metric property="errorCount" measurementType="trendsup" displayType="summary"/>
- <metric property="maxTime" />
+ <metric property="maxTime" units="milliseconds"/>
<metric property="requestCount" measurementType="trendsup" displayType="summary"/>
<resource-configuration>
@@ -819,6 +801,305 @@
<plugin-configuration>
<c:simple-property name="path" readOnly="true" default="subsystem=logging"/>
</plugin-configuration>
+
+ <operation name="change-root-log-level" description="Change the root logger level.">
+ <parameters>
+ <c:simple-property name="level" required="true" type="string" readOnly="false"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded.">
+ <c:property-options>
+ <c:option value="FATAL"/>
+ <c:option value="ERROR"/>
+ <c:option value="WARN"/>
+ <c:option value="INFO"/>
+ <c:option value="DEBUG"/>
+ <c:option value="TRACE"/>
+ </c:property-options>
+ </c:simple-property>
+ </parameters>
+ </operation>
+
+ <operation name="remove-root-logger" description="Remove the root logger.">
+ </operation>
+
+ <operation name="set-root-logger" description="Set the root logger.">
+ <parameters>
+ <c:simple-property name="level" required="true" type="string" readOnly="false"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded.">
+ <c:property-options>
+ <c:option value="FATAL"/>
+ <c:option value="ERROR"/>
+ <c:option value="WARN"/>
+ <c:option value="INFO"/>
+ <c:option value="DEBUG"/>
+ <c:option value="TRACE"/>
+ </c:property-options>
+ </c:simple-property>
+
+ <c:list-property name="handlers" required="true" readOnly="false"
+ description="The Handlers associated with this Logger.">
+ <c:simple-property name="handler" type="string"/>
+ </c:list-property>
+ </parameters>
+ </operation>
+
+ <resource-configuration>
+ <c:map-property name="root-logger" description="The root logger for this log context.">
+ <c:simple-property name="level" readOnly="true"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded." />
+ <c:list-property name="handlers" readOnly="true">
+ <c:simple-property name="handler" readOnly="true" description="The Handlers associated with this Logger."/>
+ </c:list-property>
+ </c:map-property>
+ </resource-configuration>
+
+
+ <service name="ConsoleHandler"
+ discovery="SubsystemDiscovery"
+ class="LoggerComponent"
+ >
+ <plugin-configuration>
+ <c:simple-property name="path" readOnly="true" default="console-handler"/>
+ </plugin-configuration>
+
+ <operation name="change-log-level" description="Change the logging level for a handler.">
+ <parameters>
+ <c:simple-property name="level" required="true" type="string" readOnly="false"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded.">
+ <c:property-options>
+ <c:option value="FATAL"/>
+ <c:option value="ERROR"/>
+ <c:option value="WARN"/>
+ <c:option value="INFO"/>
+ <c:option value="DEBUG"/>
+ <c:option value="TRACE"/>
+ </c:property-options>
+ </c:simple-property>
+ </parameters>
+ </operation>
+
+ <operation name="disable" description="Disable a logging handler.">
+ </operation>
+
+ <operation name="enable" description="Enable a logging handler.">
+ </operation>
+
+ <resource-configuration>
+ <c:simple-property name="name" required="false" type="string" readOnly="true" description="The handler's name."/>
+ <c:simple-property name="level" required="false" type="string" readOnly="true"
+ description="The log level specifying which message levels will be logged by this. Message levels lower than this value will be discarded. "/>
+ <c:simple-property name="encoding" required="false" type="string" readOnly="true"
+ description="The character encoding used by this Handler."/>
+ <c:simple-property name="filter" required="false" type="string" readOnly="true" description="Defines a simple filter type."/>
+ <c:simple-property name="formatter" required="false" type="string" readOnly="true" description="Defines a formatter."/>
+ <c:simple-property name="autoflush" required="false" type="boolean" readOnly="true" description="Automatically flush after each write."/>
+ <c:simple-property name="target" required="false" type="string" readOnly="true"
+ description="Defines the target of the console handler. The value can either be SYSTEM_OUT or SYSTEM_ERR.">
+ <c:property-options>
+ <c:option value="SYSTEM_OUT"/>
+ <c:option value="SYSTEM_ERR"/>
+ </c:property-options>
+ </c:simple-property>
+ </resource-configuration>
+ </service>
+
+ <service name="FileHandler"
+ discovery="SubsystemDiscovery"
+ class="LoggerComponent"
+ >
+ <plugin-configuration>
+ <c:simple-property name="path" readOnly="true" default="file-handler"/>
+ </plugin-configuration>
+
+ <operation name="change-log-level" description="Change the logging level for a handler.">
+ <parameters>
+ <c:simple-property name="level" required="true" type="string" readOnly="false"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded.">
+ <c:property-options>
+ <c:option value="FATAL"/>
+ <c:option value="ERROR"/>
+ <c:option value="WARN"/>
+ <c:option value="INFO"/>
+ <c:option value="DEBUG"/>
+ <c:option value="TRACE"/>
+ </c:property-options>
+ </c:simple-property>
+ </parameters>
+ </operation>
+
+ <operation name="disable" description="Disable a logging handler.">
+ </operation>
+
+ <operation name="enable" description="Enable a logging handler.">
+ </operation>
+
+ <operation name="change-file" description="Change the file for a handler.">
+ <parameters>
+ <c:simple-property name="path" required="true" type="string" readOnly="false" description="The filesystem path."/>
+ <c:simple-property name="relative-to" required="false" type="string" readOnly="false"
+ description="The name of another previously named path, or of one of the standard paths provided by the system.
+ If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
+ The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
+ distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
+ working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
+ root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
+ use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
+ log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
+ storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
+ working area for individual server instances</li></ul>"/>
+ </parameters>
+ </operation>
+ <resource-configuration>
+ <c:simple-property name="name" required="false" type="string" readOnly="true" description="The handler's name."/>
+ <c:simple-property name="level" required="false" type="string" readOnly="true"
+ description="The log level specifying which message levels will be logged by this. Message levels lower than this value will be discarded. "/>
+ <c:simple-property name="encoding" required="false" type="string" readOnly="true"
+ description="The character encoding used by this Handler."/>
+ <c:simple-property name="filter" required="false" type="string" readOnly="true" description="Defines a simple filter type."/>
+ <c:simple-property name="formatter" required="false" type="string" readOnly="true" description="Defines a formatter."/>
+ <c:simple-property name="autoflush" required="false" type="boolean" readOnly="true" description="Automatically flush after each write."/>
+ <c:simple-property name="target" required="false" type="string" readOnly="true"
+ description="Defines the target of the console handler. The value can either be SYSTEM_OUT or SYSTEM_ERR.">
+ <c:property-options>
+ <c:option value="SYSTEM_OUT"/>
+ <c:option value="SYSTEM_ERR"/>
+ </c:property-options>
+ </c:simple-property>
+ </resource-configuration>
+ </service>
+ <service name="PeriodicRotatingFileHandler"
+ discovery="SubsystemDiscovery"
+ class="LoggerComponent"
+ >
+ <plugin-configuration>
+ <c:simple-property name="path" readOnly="true" default="periodic-rotating-file-handler"/>
+ </plugin-configuration>
+
+ <operation name="change-log-level" description="Change the logging level for a handler.">
+ <parameters>
+ <c:simple-property name="level" required="true" type="string" readOnly="false"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded.">
+ <c:property-options>
+ <c:option value="FATAL"/>
+ <c:option value="ERROR"/>
+ <c:option value="WARN"/>
+ <c:option value="INFO"/>
+ <c:option value="DEBUG"/>
+ <c:option value="TRACE"/>
+ </c:property-options>
+ </c:simple-property>
+ </parameters>
+ </operation>
+
+ <operation name="disable" description="Disable a logging handler.">
+ </operation>
+
+ <operation name="enable" description="Enable a logging handler.">
+ </operation>
+
+ <operation name="change-file" description="Change the file for a handler.">
+ <parameters>
+ <c:simple-property name="path" required="true" type="string" readOnly="false" description="The filesystem path."/>
+ <c:simple-property name="relative-to" required="false" type="string" readOnly="false"
+ description="The name of another previously named path, or of one of the standard paths provided by the system.
+ If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
+ The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
+ distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
+ working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
+ root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
+ use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
+ log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
+ storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
+ working area for individual server instances</li></ul>"/>
+ </parameters>
+ </operation>
+ <resource-configuration>
+ <c:simple-property name="name" required="false" type="string" readOnly="true" description="The handler's name."/>
+ <c:simple-property name="level" required="false" type="string" readOnly="true" description="The log level specifying which message levels will be logged by this.
+ Message levels lower than this value will be discarded. "/>
+ <c:simple-property name="encoding" required="false" type="string" readOnly="true" description="The character encoding used by this Handler."/>
+ <c:simple-property name="filter" required="false" type="string" readOnly="true" description="Defines a simple filter type."/>
+ <c:simple-property name="formatter" required="false" type="string" readOnly="true" description="Defines a formatter."/>
+ <c:simple-property name="autoflush" required="false" type="boolean" readOnly="true" description="Automatically flush after each write."/>
+ <c:simple-property name="append" required="false" type="boolean" readOnly="true" description="Specify whether to append to the target file."/>
+ <c:map-property name="file" description="null" >
+ <c:simple-property name="relative-to" required="false" type="string" readOnly="true" description="The name of another previously named path, or of one of the standard paths
+ provided by the system. If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path
+ specified by this attribute. The standard paths provided by the system include:<ul><li>jboss.home - the root directory
+ of the JBoss AS distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current working
+ directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir - root directory for an
+ individual server instance</li><li>jboss.server.data.dir - directory the server will use for persistent data file
+ storage</li><li>jboss.server.log.dir - directory the server will use for log file storage</li><li>jboss.server.tmp.dir -
+ directory the server will use for temporary file storage</li><li>jboss.domain.servers.dir - directory under which a host controller
+ will create the working area for individual server instances</li></ul>"/>
+ <c:simple-property name="path" required="false" type="string" readOnly="true" description="The filesystem path."/>
+ </c:map-property>
+ <c:simple-property name="suffix" required="false" type="string" readOnly="true" description="Set the suffix string. The string is in a format which
+ can be understood by java.text.SimpleDateFormat. The period of the rotation is automatically calculated based on the suffix."/>
+ </resource-configuration>
+ </service>
+ <service name="SizeRotatingFileHandler"
+ discovery="SubsystemDiscovery"
+ class="LoggerComponent"
+ >
+ <plugin-configuration>
+ <c:simple-property name="path" readOnly="true" default="size-rotating-file-handler"/>
+ </plugin-configuration>
+
+ <operation name="change-log-level" description="Change the logging level for a handler.">
+ <parameters>
+ <c:simple-property name="level" required="true" type="string" readOnly="false"
+ description="The log level specifying which message levels will be logged by this logger. Message levels lower than this value will be discarded.">
+ <c:property-options>
+ <c:option value="FATAL"/>
+ <c:option value="ERROR"/>
+ <c:option value="WARN"/>
+ <c:option value="INFO"/>
+ <c:option value="DEBUG"/>
+ <c:option value="TRACE"/>
+ </c:property-options>
+ </c:simple-property>
+ </parameters>
+ </operation>
+
+ <operation name="disable" description="Disable a logging handler.">
+ </operation>
+
+ <operation name="enable" description="Enable a logging handler.">
+ </operation>
+
+ <operation name="change-file" description="Change the file for a handler.">
+ <parameters>
+ <c:simple-property name="path" required="true" type="string" readOnly="false" description="The filesystem path."/>
+ <c:simple-property name="relative-to" required="false" type="string" readOnly="false"
+ description="The name of another previously named path, or of one of the standard paths provided by the system.
+ If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute.
+ The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS
+ distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current
+ working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir -
+ root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will
+ use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for
+ log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file
+ storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the
+ working area for individual server instances</li></ul>"/>
+ </parameters>
+ </operation>
+ <resource-configuration>
+ <c:simple-property name="name" required="false" type="string" readOnly="true" description="The handler's name."/>
+ <c:simple-property name="level" required="false" type="string" readOnly="true" description="The log level specifying which message levels will be logged by this. Message levels lower than this value will be discarded. "/>
+ <c:simple-property name="encoding" required="false" type="string" readOnly="true" description="The character encoding used by this Handler."/>
+ <c:simple-property name="filter" required="false" type="string" readOnly="true" description="Defines a simple filter type."/>
+ <c:simple-property name="formatter" required="false" type="string" readOnly="true" description="Defines a formatter."/>
+ <c:simple-property name="autoflush" required="false" type="boolean" readOnly="true" description="Automatically flush after each write."/>
+ <c:simple-property name="append" required="false" type="boolean" readOnly="true" description="Specify whether to append to the target file."/>
+ <c:map-property name="file" description="null" >
+ <c:simple-property name="relative-to" required="false" type="string" readOnly="true" description="The name of another previously named path, or of one of the standard paths provided by the system. If 'relative-to' is provided, the value of the 'path' attribute is treated as relative to the path specified by this attribute. The standard paths provided by the system include:<ul><li>jboss.home - the root directory of the JBoss AS distribution</li><li>user.home - user's home directory</li><li>user.dir - user's current working directory</li><li>java.home - java installation directory</li><li>jboss.server.base.dir - root directory for an individual server instance</li><li>jboss.server.data.dir - directory the server will use for persistent data file storage</li><li>jboss.server.log.dir - directory the server will use for log file storage</li><li>jboss.server.tmp.dir - directory the server will use for temporary file storage</li><li>jboss.domain.servers.dir - directory under which a host controller will create the working area for individual server instances</li></ul>"/>
+ <c:simple-property name="path" required="false" type="string" readOnly="true" description="The filesystem path."/>
+ </c:map-property>
+ <c:simple-property name="rotate-size" required="false" description="The size at which to rotate the log file." type="long" units="bytes"/>
+ <c:simple-property name="max-backup-index" required="false" description="The maximum number of backups to keep." type="integer" />
+ </resource-configuration>
+ </service>
+
</server>
<server name="Security"
@@ -965,6 +1246,32 @@
<c:simple-property name="webservice-secure-port" type="integer" readOnly="true"
description="The non-secure port that will be used for rewriting the SOAP address. If absent the port will be identified by querying the list of installed connectors."/>
</resource-configuration>
+
+ <service name="Endpoint"
+ discovery="SubsystemDiscovery"
+ class="BaseComponent"
+ >
+ <plugin-configuration>
+ <c:simple-property name="path" readOnly="true" default="endpoint"/>
+ </plugin-configuration>
+
+ <metric property="average-processing-time" description="Average endpoint processing time." displayType="summary" units="milliseconds"/>
+ <metric property="min-processing-time" description="Minimal endpoint processing time." units="milliseconds"/>
+ <metric property="max-processing-time" description="Maximal endpoint processing time." units="milliseconds"/>
+ <metric property="total-processing-time" description="Total endpoint processing time." measurementType="trendsup" units="milliseconds"/>
+ <metric property="request-count" description="Count of requests the endpoint processed." displayType="summary" measurementType="trendsup"/>
+ <metric property="response-count" description="Count of responses the endpoint generated." measurementType="trendsup"/>
+ <metric property="fault-count" description="Count of faults the endpoint generated." displayType="summary" measurementType="trendsup"/>
+
+ <resource-configuration>
+ <c:simple-property name="name" required="true" type="string" readOnly="true" description="Webservice endpoint name."/>
+ <c:simple-property name="context" required="true" type="string" readOnly="true" description="Webservice endpoint context."/>
+ <c:simple-property name="class" required="false" type="string" readOnly="true" description="Webservice endpoint class."/>
+ <c:simple-property name="type" required="false" type="string" readOnly="true" description="Webservice endpoint type."/>
+ <c:simple-property name="wsdl-url" required="false" type="string" readOnly="true" description="Webservice endpoint WSDL URL."/>
+ </resource-configuration>
+
+ </service>
</server>
<service name="NetworkInterface"
@@ -1018,4 +1325,30 @@
</service>
+ <service name="Deployment"
+ class="BaseComponent"
+ discovery="SubsystemDiscovery"
+ createDeletePolicy="both"
+ creationDataType="content">
+
+
+ <runs-inside>
+ <parent-resource-type name="ServerGroup" plugin="jboss-as-7"/>
+ <parent-resource-type name="JBossAS7-Standalone" plugin="jboss-as-7"/>
+ </runs-inside>
+ <plugin-configuration>
+ <c:simple-property name="path" default="deployment" readOnly="true"/>
+ </plugin-configuration>
+
+ <content name="file" category="deployable" isCreationType="true" description="Deployments on this server group">
+ <configuration>
+ <c:group name="deployment" displayName="Deployment Options">
+ <c:simple-property name="runtimeName" required="true"/>
+ </c:group>
+ </configuration>
+ </content>
+
+ </service>
+
+
</plugin>
commit dd328eac2660aa3b2d4f0d95aa6f031d08ed09cf
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 25 11:34:19 2011 +0200
Changes and optimizations to operations handling and description elements.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/Domain2Descriptor.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/Domain2Descriptor.java
index 6d4a0e2..8011628 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/Domain2Descriptor.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/Domain2Descriptor.java
@@ -23,14 +23,20 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
+import org.omg.CosNaming._BindingIteratorImplBase;
+
import org.rhq.modules.plugins.jbossas7.json.ComplexResult;
import org.rhq.modules.plugins.jbossas7.json.Operation;
import org.rhq.modules.plugins.jbossas7.json.PROPERTY_VALUE;
/**
- * Generate properties from a domain dump
+ * Generate properties, metrics and operation templates for the
+ * plugin descriptor from a domain dump (server can run in domain
+ * or standalone mode).
+ *
* @author Heiko W. Rupp
*/
+@SuppressWarnings("unchecked")
public class Domain2Descriptor {
public static void main(String[] args) throws Exception {
@@ -48,15 +54,15 @@ public class Domain2Descriptor {
private void run(String[] args) {
- Mode mode = null;
+ D2DMode mode = null;
int pos = 0;
if (args[0].startsWith("-")) {
if (args[0].equals("-m"))
- mode = Domain2Descriptor.Mode.METRICS;
+ mode = D2DMode.METRICS;
else if (args[0].equals("-p"))
- mode = Domain2Descriptor.Mode.PROPERTIES;
+ mode = D2DMode.PROPERTIES;
else if (args[0].equals("-o"))
- mode = Domain2Descriptor.Mode.OPERATION;
+ mode = D2DMode.OPERATION;
else {
usage();
return;
@@ -75,12 +81,12 @@ public class Domain2Descriptor {
Operation op = new Operation("read-resource-description",address);
op.addAdditionalProperty("recursive","true");
- if (mode==Domain2Descriptor.Mode.OPERATION)
+ if (mode== D2DMode.OPERATION)
op.addAdditionalProperty("operations",true);
- if (mode == Domain2Descriptor.Mode.METRICS)
+ if (mode == D2DMode.METRICS)
op.addAdditionalProperty("include-runtime",true);
- ComplexResult res = (ComplexResult) conn.execute(op,true);
+ ComplexResult res = conn.executeComplex(op);
if (!res.isSuccess()) {
System.err.println("Failure: " + res.getFailureDescription());
return;
@@ -88,39 +94,44 @@ public class Domain2Descriptor {
Map<String,Object> resMap = res.getResult();
- if (mode==Domain2Descriptor.Mode.OPERATION) {
- Map<String,Object> operationsMap = (Map<String, Object>) resMap.get("operations");
- for (Map.Entry<String,Object> entry : operationsMap.entrySet()) {
+ String what;
+ if (mode== D2DMode.OPERATION)
+ what="operations";
+ else
+ what="attributes";
+
+ Map<String,Object> attributesMap;
+ if (childType!=null) {
+ Map childMap = (Map) resMap.get("children");
+ Map <String,Object> typeMap = (Map<String, Object>) childMap.get(childType);
+ Map descriptionMap = (Map) typeMap.get("model-description");
+ if (descriptionMap==null) {
+ System.err.println("No model description found");
+ return;
+ }
+ Map starMap = (Map) descriptionMap.get("*");
+ attributesMap = (Map<String, Object>) starMap.get(what);
+ }
+ else {
+ attributesMap = (Map<String, Object>) resMap.get(what);
+ }
+
+ if (mode==D2DMode.OPERATION) {
+ for (Map.Entry<String,Object> entry : attributesMap.entrySet()) {
if (entry.getKey().startsWith("read-"))
continue;
if (entry.getKey().equals("write-attribute"))
continue;
- createOperation((Map<String,Object>)entry.getValue());
+ createOperation(entry.getKey(), (Map<String,Object>)entry.getValue());
}
-
- } else {
- Map<String,Object> attributesMap;
- if (childType!=null) {
- Map childMap = (Map) resMap.get("children");
- Map <String,Object> typeMap = (Map<String, Object>) childMap.get(childType);
- Map descriptionMap = (Map) typeMap.get("model-description");
- if (descriptionMap==null) {
- System.err.println("No model description found");
- return;
- }
- Map starMap = (Map) descriptionMap.get("*");
- attributesMap = (Map<String, Object>) starMap.get("attributes");
- }
- else {
- attributesMap = (Map<String, Object>) resMap.get("attributes");
- }
-
- createProperties(mode, attributesMap, 0);
}
+ else
+ createProperties(mode, attributesMap, 0);
+// }
}
- private void createProperties(Mode mode, Map<String, Object> attributesMap, int indent) {
+ private void createProperties(D2DMode mode, Map<String, Object> attributesMap, int indent) {
if (attributesMap==null)
return;
@@ -161,16 +172,13 @@ public class Domain2Descriptor {
}
- if (ptype== Type.LIST && mode!=Domain2Descriptor.Mode.METRICS) {
+ if (ptype== Type.LIST && mode!= D2DMode.METRICS) {
StringBuilder sb = new StringBuilder("<c:list-property name=\"");
sb.append(entryName);
sb.append("\"");
- if (props.containsKey("description")) {
- sb.append(" description=\"");
- sb.append(props.get("description"));
- sb.append("\"");
- }
+ String description = (String) props.get("description");
+ appendDescription(sb,description);
sb.append(" >\n");
if (!props.containsKey("attributes"))
sb.append(" <c:simple-property name=\"").append(entryName).append("\" />\n");
@@ -192,7 +200,7 @@ public class Domain2Descriptor {
}
String accessType = getAccessType(props);
- if (mode==Domain2Descriptor.Mode.METRICS) {
+ if (mode== D2DMode.METRICS) {
if (!accessType.equals("metric"))
continue;
@@ -204,11 +212,7 @@ public class Domain2Descriptor {
sb.append(" dataType=\"trait\"");
String description = (String) props.get("description");
- if (description!=null) {
- if (sb.length()+description.length() > 120)
- sb.append("\n ");
- sb.append(" description=\"").append(description).append('"');
- }
+ appendDescription(sb,description);
sb.append("/>");
System.out.println(sb.toString());
@@ -224,32 +228,27 @@ public class Domain2Descriptor {
}
}
- private void createOperation(Map<String,Object> operationMap) {
+ private void createOperation(String name, Map<String, Object> operationMap) {
StringBuilder builder = new StringBuilder("<operation name=\"");
- String name = (String) operationMap.get("operation-name");
builder.append(name).append('"');
String description = (String) operationMap.get("description");
- if (description!=null && !description.isEmpty()) {
- builder.append(" description=\"").append(description).append('"');
- }
+ appendDescription(builder, description);
builder.append(">\n");
-
-
- if (!((Map)operationMap.get("request-properties")).isEmpty()) {
- Map<String,Object> map = (Map<String, Object>) operationMap.get("request-properties");
+ Map<String,Object> reqMap = (Map<String, Object>) operationMap.get("request-properties");
+ if (reqMap!=null && !reqMap.isEmpty()) {
builder.append(" <parameters>\n");
- generatePropertiesForMap(builder, map, true);
+ generatePropertiesForMap(builder, reqMap, true);
builder.append(" </parameters>\n");
}
- if (!((Map)operationMap.get("reply-properties")).isEmpty()){
- Map<String,Object> map = (Map<String, Object>) operationMap.get("reply-properties"); // TODO not sure -- perhaps for the java code?
+ Map replyMap = (Map) operationMap.get("reply-properties");
+ if (replyMap!=null && !replyMap.isEmpty()){
builder.append(" <results>\n");
- generatePropertiesForMap(builder, map, true);
+ generatePropertiesForMap(builder, replyMap, true);
builder.append(" </results>\n");
}
@@ -258,6 +257,21 @@ public class Domain2Descriptor {
System.out.println(builder.toString());
}
+ private void appendDescription(StringBuilder builder, String description) {
+ if (description!=null && !description.isEmpty()) {
+ if (builder.length()>120)
+ builder.append("\n ");
+ builder.append(" description=\"");
+
+ description = description.replace("<","<");
+ description = description.replace(">",">");
+ description = description.replace("\"","\\\"");
+
+ builder.append(description);
+ builder.append('"');
+ }
+ }
+
private void generatePropertiesForMap(StringBuilder builder, Map<String, Object> map, boolean forceReadWrite) {
for (Map.Entry<String,Object> entry : map.entrySet()) {
@@ -334,11 +348,7 @@ public class Domain2Descriptor {
}
String description = (String) props.get("description");
- if (description!=null) {
- if (sb.length()+description.length() > 120)
- sb.append("\n ");
- sb.append(" description=\"").append(description).append('"');
- }
+ appendDescription(sb,description);
sb.append("/>");
return sb;
}
@@ -350,6 +360,9 @@ public class Domain2Descriptor {
private Type getTypeFromProps(Map<String, Object> props) {
Map<String,String> tMap = (Map<String, String>) props.get("type");
+ if (tMap==null)
+ return Type.OBJECT;
+
String type = tMap.get("TYPE_MODEL_VALUE");
Type ret = Type.valueOf(type);
@@ -391,6 +404,7 @@ public class Domain2Descriptor {
System.out.println(" path is of kind 'key=value[,key=value]+");
System.out.println(" -p create properties (default)");
System.out.println(" -m create metrics");
+ System.out.println(" -o create operations");
}
public enum Type {
@@ -405,7 +419,7 @@ public class Domain2Descriptor {
;
}
- private enum Mode {
+ private enum D2DMode {
METRICS,
PROPERTIES,
OPERATION
commit 895f8fd65dd46327a171ecb96d498baecc2afffc
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed May 25 11:23:09 2011 +0200
Add a test for AS7-853
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java
index 1ef3761..57ec4f3 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java
@@ -153,6 +153,81 @@ public class UploadAndDeployTest {
}
+ // Test for AS7-853
+ @Test(timeOut = 60*1000L, enabled = true)
+ public void testUploadIndividualSteps2() throws Exception {
+
+ String bytes_value = prepare();
+
+ System.out.println("sha: " + bytes_value);
+
+ System.out.println();
+ ASConnection connection = new ASConnection(DC_HOST, DC_HTTP_PORT);
+
+ List<PROPERTY_VALUE> deploymentsAddress = new ArrayList<PROPERTY_VALUE>(1);
+ deploymentsAddress.add(new PROPERTY_VALUE("deployment", TEST_WAR));
+ Operation op = new Operation("add",deploymentsAddress);
+ List<Object> content = new ArrayList<Object>(1);
+ Map<String,Object> contentValues = new HashMap<String,Object>();
+ contentValues.put("hash",new PROPERTY_VALUE("BYTES_VALUE",bytes_value));
+ content.add(contentValues);
+ op.addAdditionalProperty("content",content);
+ op.addAdditionalProperty("name", TEST_WAR); // this needs to be unique per upload
+ op.addAdditionalProperty("runtime-name", TEST_WAR);
+ System.out.flush();
+ JsonNode ret = connection.executeRaw(op);
+ op = null;
+ System.out.println("Add to /deploy done " + ret);
+ System.out.flush();
+
+ assert ret.toString().contains("success") : ret;
+
+
+ List<PROPERTY_VALUE> serverGroupAddress = new ArrayList<PROPERTY_VALUE>(1);
+ serverGroupAddress.add(new PROPERTY_VALUE("server-group", "main-server-group"));
+ serverGroupAddress.add(new PROPERTY_VALUE("deployment", TEST_WAR));
+
+ Operation attach = new Operation("add",serverGroupAddress,"enabled",true);
+ System.out.flush();
+ ret = connection.executeRaw(attach);
+ System.out.println("Add to server group done: " + ret);
+ System.out.flush();
+
+ assert ret.has("outcome") : "Ret not valid " + ret.toString();
+ assert ret.get("outcome").getTextValue().equals("success") : "add to sg was no success " + ret.getTextValue();
+
+
+ Result depRes;// = connection.execute(deploy);
+
+ Thread.sleep(500);
+
+ Operation undeploy = new Operation("undeploy",serverGroupAddress);
+ depRes = connection.execute(undeploy);
+
+ assert depRes.isSuccess() : "Undeploy went wrong: " + depRes.getFailureDescription();
+ undeploy = null;
+
+ // Now tear down stuff again
+
+ Operation unattach = new Operation("remove",serverGroupAddress);
+ ret = connection.executeRaw(unattach);
+
+ assert ret.has("outcome") : "Ret not valid " + ret.toString();
+ assert ret.get("outcome").getTextValue().equals("success") : "remove from sg was no success " + ret.getTextValue();
+
+
+ // remove from domain
+
+ Operation remove = new Operation("remove",deploymentsAddress);
+ ret = connection.executeRaw(remove);
+
+ assert ret.has("outcome") : "Ret not valid " + ret.toString();
+ assert ret.get("outcome").getTextValue().equals("success") : "remove from domain was no success " + ret.getTextValue();
+
+ System.out.flush();
+
+ }
+
@Test(timeOut = 60*1000L, enabled = true)
public void testUploadComposite() throws Exception {
commit 3dbd7b89c98c52007fecc64c79a403de1170f68c
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Tue May 24 15:26:53 2011 +0200
Add a comment that tests need to run against domain mode.
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java
index f2a4d54..1ef3761 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/UploadAndDeployTest.java
@@ -36,7 +36,8 @@ import org.rhq.modules.plugins.jbossas7.json.Result;
/**
* Test uploading and deploying to the domain
- * To use it, domain server must be up and running locally and
+ * To use it, a server in <b>domain mode</b> must be up and have it's
+ * <b>DomainController</b> running <b>locally</b> and
* the UPLOAD_FILE must point to a valid archive in the resources directory.
* @author Heiko W. Rupp
*/
commit 506c0dbaf78a349cebeb34f99b96befb57ec1c07
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Fri May 20 11:56:14 2011 +0200
Prevent NPE on container shutdown.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventContextImpl.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventContextImpl.java
index 64a6ff7..b0b37ec 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventContextImpl.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/event/EventContextImpl.java
@@ -103,7 +103,7 @@ public class EventContextImpl implements EventContext {
public SigarProxy getSigar() {
return getEventManager().getSigar();
}
-
+
private void registerEventPollerInternal(final EventPoller poller, int pollingInterval,
final String sourceLocation) {
EventDefinition eventDefinition = EventUtility.getEventDefinition(poller.getEventType(), this.resource.getResourceType());
@@ -124,6 +124,8 @@ public class EventContextImpl implements EventContext {
EventDefinition eventDefinition = EventUtility.getEventDefinition(eventType, this.resource.getResourceType());
if (eventDefinition == null)
throw new IllegalArgumentException("Unknown event type - no EventDefinition exists with name '" + eventType + "'.");
- getEventManager().unregisterEventPoller(this.resource, eventType, sourceLocation);
+ EventManager eventManager = getEventManager();
+ if (eventManager!=null)
+ eventManager.unregisterEventPoller(this.resource, eventType, sourceLocation);
}
}
12 years, 11 months