[rhq] modules/core modules/plugins
by ips
modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java | 10 +
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java | 3
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java | 69 ++++------
3 files changed, 41 insertions(+), 41 deletions(-)
New commits:
commit db608e3eeb24f87078e5008f563ce1f334c99457
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Mar 29 11:03:12 2012 -0400
bugfix: homeDir was being used in a couple places where baseDir should have been used; use the PropertiesFileUpdate utility to update the mgmt users props file; minor: add a constant for the char encoding in PropertiesFileUpdate
diff --git a/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java b/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
index 2389268..595fda2 100644
--- a/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
+++ b/modules/core/util/src/main/java/org/rhq/core/util/PropertiesFileUpdate.java
@@ -47,6 +47,9 @@ import java.util.Properties;
* @author John Mazzitelli
*/
public class PropertiesFileUpdate {
+
+ private static final String CHAR_ENCODING_8859_1 = "8859_1";
+
private File file;
/**
@@ -80,7 +83,7 @@ public class PropertiesFileUpdate {
if (!existingProps.containsKey(key)) {
FileOutputStream fos = new FileOutputStream(file, true);
try {
- PrintStream ps = new PrintStream(fos, true, "8859_1");
+ PrintStream ps = new PrintStream(fos, true, CHAR_ENCODING_8859_1);
try {
ps.println(key + "=" + value);
} finally {
@@ -127,8 +130,8 @@ public class PropertiesFileUpdate {
// Now go line-by-line in the properties file, updating property values as we go along.
// When we get to the end of the existing file, append any new props that didn't exist before.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream out = new PrintStream(baos, true, "8859_1");
- InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "8859_1");
+ PrintStream out = new PrintStream(baos, true, CHAR_ENCODING_8859_1);
+ InputStreamReader isr = new InputStreamReader(new FileInputStream(file), CHAR_ENCODING_8859_1);
BufferedReader in = new BufferedReader(isr);
for (String line = in.readLine(); line != null; line = in.readLine()) {
@@ -210,4 +213,5 @@ public class PropertiesFileUpdate {
return ((start > 0) || (end < str.length())) ? str.substring(start, end) : str;
}
+
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 67f70cd..4b421c4 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -117,7 +117,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
pluginConfig.put(new PropertySimple("configDir", configDir));
pluginConfig.put(new PropertySimple("startScript", getMode().getStartScript()));
pluginConfig.put(new PropertySimple("domainHost", findHost(getHostXmlFile(process, configDir))));
- fillUserPassFromFile(pluginConfig, getMode(), homeDir);
+ fillUserPassFromFile(pluginConfig, getMode(), baseDir);
File logFile = getLogFile(getLogDir(process, baseDir));
initLogEventSourcesConfigProp(logFile.getPath(), pluginConfig);
HostPort managementHostPort = getManagementPortFromHostXml(commandLine);
@@ -317,7 +317,6 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
}
private void fillUserPassFromFile(Configuration config, AS7Mode mode, File baseDir) {
- // String configDir = baseDir + File.separator + mode + File.separator + "configuration";
String realm = getManagementSecurityRealmFromHostXml();
String fileName = getSecurityPropertyFileFromHostXml(baseDir, mode, realm);
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
index bdf8a66..68a78c0 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
@@ -19,11 +19,7 @@
package org.rhq.modules.plugins.jbossas7;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
import java.net.ConnectException;
-import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
@@ -47,6 +43,7 @@ import org.rhq.core.pluginapi.operation.OperationResult;
import org.rhq.core.pluginapi.util.ProcessExecutionUtility;
import org.rhq.core.system.ProcessExecution;
import org.rhq.core.system.ProcessExecutionResults;
+import org.rhq.core.util.PropertiesFileUpdate;
import org.rhq.modules.plugins.jbossas7.json.Address;
import org.rhq.modules.plugins.jbossas7.json.ComplexResult;
import org.rhq.modules.plugins.jbossas7.json.Operation;
@@ -74,7 +71,7 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
* @throws Exception If anything goes wrong
*/
protected OperationResult restartServer(Configuration parameters, AS7Mode mode) throws Exception {
- OperationResult tmp = invokeOperation("shutdown",parameters);
+ OperationResult tmp = invokeOperation("shutdown", parameters);
if (tmp.getErrorMessage()!=null) {
tmp.setErrorMessage("Restart failed while failing to shut down: " + tmp.getErrorMessage());
@@ -116,12 +113,12 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
protected OperationResult startServer(AS7Mode mode) {
OperationResult operationResult = new OperationResult();
String startScript = pluginConfiguration.getSimpleValue("startScript", mode.getStartScript());
- String baseDir = pluginConfiguration.getSimpleValue("baseDir","");
- if (baseDir.isEmpty()) {
- operationResult.setErrorMessage("No base directory provided");
+ String homeDir = pluginConfiguration.getSimpleValue("homeDir", "");
+ if (homeDir.isEmpty()) {
+ operationResult.setErrorMessage("No home directory provided.");
return operationResult;
}
- String script = baseDir + File.separator + startScript;
+ String script = homeDir + File.separator + startScript;
ProcessExecution processExecution;
processExecution = ProcessExecutionUtility.createProcessExecution(new File("/bin/sh"));
@@ -148,7 +145,7 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
}
}
- processExecution.setWorkingDirectory(baseDir);
+ processExecution.setWorkingDirectory(homeDir);
processExecution.setCaptureOutput(true);
processExecution.setWaitForCompletion(15000L); // 15 seconds // TODO: Should we wait longer than 15 seconds?
processExecution.setKillOnTimeout(false);
@@ -274,12 +271,12 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
return result;
}
- String homeDirString = pluginConfig.getSimpleValue("homeDir", "");
- if (homeDirString.isEmpty()) {
- result.setErrorMessage("No homeDir found - cannot continue.");
+ String baseDirString = pluginConfig.getSimpleValue("baseDir", "");
+ if (baseDirString.isEmpty()) {
+ result.setErrorMessage("No baseDir found - cannot continue.");
return result;
}
- File homeDir = new File(homeDirString);
+ File baseDir = new File(baseDirString);
String configFile;
BaseProcessDiscovery processDiscovery;
@@ -298,30 +295,31 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
processDiscovery.readStandaloneOrHostXmlFromFile(configFile);
String realm = pluginConfig.getSimpleValue("realm", "ManagementRealm");
- String propertiesFilePath = processDiscovery.getSecurityPropertyFileFromHostXml(homeDir, mode, realm);
+ String propertiesFilePath = processDiscovery.getSecurityPropertyFileFromHostXml(baseDir, mode, realm);
- Properties p = new Properties();
+ String encryptedPassword;
try {
- UsernamePasswordHashUtil util = new UsernamePasswordHashUtil();
- String value = util.generateHashedHexURP(user, realm, password.toCharArray());
-
- FileInputStream fis = new FileInputStream(propertiesFilePath);
- p.load(fis);
- fis.close();
- p.setProperty(user,value);
- FileOutputStream fos = new FileOutputStream(propertiesFilePath);
- p.store(fos,null);
- fos.flush();
- fos.close();
- } catch (IOException e) {
- log.error(e.getMessage());
- result.setErrorMessage(e.getMessage());
- } catch (NoSuchAlgorithmException nsae) {
- log.error(nsae.getMessage());
- result.setErrorMessage(nsae.getMessage());
+ UsernamePasswordHashUtil hashUtil = new UsernamePasswordHashUtil();
+ encryptedPassword = hashUtil.generateHashedHexURP(user, realm, password.toCharArray());
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to encrypt password.", e);
}
- result.setSimpleResult("Management user [" + user + "] added or updated.");
- log.info("Added or updated management user [" + user + "].");
+
+ boolean userAlreadyExisted;
+ try {
+ PropertiesFileUpdate propsFileUpdate = new PropertiesFileUpdate(propertiesFilePath);
+ Properties existingProps = propsFileUpdate.loadExistingProperties();
+ userAlreadyExisted = existingProps.containsKey(user);
+ propsFileUpdate.update(user, encryptedPassword);
+ } catch (Exception e) {
+ throw new RuntimeException("Failed to update management users properties file [" + propertiesFilePath
+ + "].", e);
+ }
+
+ String verb = (userAlreadyExisted) ? "updated" : "added";
+ result.setSimpleResult("Management user [" + user + "] " + verb + ".");
+ log.info("Management user [" + user + "] " + verb + " for " + context.getResourceType().getName()
+ + " server with key [" + context.getResourceKey() + "].");
context.getAvailabilityContext().requestAvailabilityCheck();
@@ -329,7 +327,6 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
}
public void getValues(MeasurementReport report, Set metrics) throws Exception {
-
Set<MeasurementScheduleRequest> requests = metrics;
Set<MeasurementScheduleRequest> leftovers = new HashSet<MeasurementScheduleRequest>(requests.size());
12 years, 1 month
[rhq] modules/enterprise
by mazz
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/MeasurementConverterClient.java | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
New commits:
commit d11cc40698ac1fd9891ef8a6cac77d0e5e50ef99
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Thu Mar 29 10:21:31 2012 -0400
[BZ 806281] put space between value and unit
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/MeasurementConverterClient.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/MeasurementConverterClient.java
index 47e2598..2cb9d59 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/MeasurementConverterClient.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/util/MeasurementConverterClient.java
@@ -76,7 +76,8 @@ public class MeasurementConverterClient {
if (targetUnits == null) {
return value;
} else {
- return value + getMeasurementUnitAbbreviation(targetUnits);
+ String abbr = getMeasurementUnitAbbreviation(targetUnits);
+ return (abbr.length() > 0) ? (value + " " + abbr) : value;
}
}
12 years, 1 month
[rhq] Branch 'feature/export-reports' - modules/enterprise
by mike thompson
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/AlertDefinitionHandler.java | 31 +--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ConfigurationHistoryHandler.java | 27 +-
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/InventorySummaryHandler.java | 35 +--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java | 43 +---
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentDriftHandler.java | 34 +--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java | 34 +--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportFormatHelper.java | 96 ++++++++++
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportHelper.java | 88 ---------
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/SuspectMetricHandler.java | 19 -
9 files changed, 196 insertions(+), 211 deletions(-)
New commits:
commit 46804facb6bcad383d8b82b8b4c78426824bc47f
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Thu Mar 29 07:06:18 2012 -0700
[BZ 800453] Export Csv Reports. Changed ReportHelper to ReportFormatHelper. Added proper handling of null dates.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/AlertDefinitionHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/AlertDefinitionHandler.java
index c84c446..1dc8641 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/AlertDefinitionHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/AlertDefinitionHandler.java
@@ -1,19 +1,5 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Map;
-import java.util.TreeMap;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.UriInfo;
-
import org.rhq.core.domain.alert.AlertDefinition;
import org.rhq.core.domain.criteria.AlertDefinitionCriteria;
import org.rhq.core.domain.criteria.ResourceCriteria;
@@ -26,7 +12,20 @@ import org.rhq.enterprise.server.rest.SetCallerInterceptor;
import org.rhq.enterprise.server.util.CriteriaQuery;
import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.cleanForCSV;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.interceptor.Interceptors;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.StreamingOutput;
+import javax.ws.rs.core.UriInfo;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.Map;
+import java.util.TreeMap;
+
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.cleanForCSV;
@Interceptors(SetCallerInterceptor.class)
@Stateless
@@ -81,7 +80,7 @@ public class AlertDefinitionHandler extends AbstractRestBean implements AlertDef
+ alertDefinition.getEnabled() + ","
+ alertDefinition.getPriority() + ","
+ cleanForCSV(getParentName(resource)) + ","
- + cleanForCSV(ReportHelper.parseAncestry(resource.getAncestry())) + ","
+ + cleanForCSV(ReportFormatHelper.parseAncestry(resource.getAncestry())) + ","
+ getDetailsURL(alertDefinition);
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ConfigurationHistoryHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ConfigurationHistoryHandler.java
index 39a25d9..05e1f6c 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ConfigurationHistoryHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ConfigurationHistoryHandler.java
@@ -1,8 +1,14 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
+import org.rhq.core.domain.configuration.ResourceConfigurationUpdate;
+import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria;
+import org.rhq.core.domain.util.PageList;
+import org.rhq.enterprise.server.configuration.ConfigurationManagerLocal;
+import org.rhq.enterprise.server.rest.AbstractRestBean;
+import org.rhq.enterprise.server.rest.SetCallerInterceptor;
+import org.rhq.enterprise.server.util.CriteriaQuery;
+import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
import javax.ejb.EJB;
import javax.ejb.Stateless;
@@ -12,19 +18,12 @@ import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.UriInfo;
-
-import org.rhq.core.domain.configuration.ResourceConfigurationUpdate;
-import org.rhq.core.domain.criteria.ResourceConfigurationUpdateCriteria;
-import org.rhq.core.domain.util.PageList;
-import org.rhq.enterprise.server.configuration.ConfigurationManagerLocal;
-import org.rhq.enterprise.server.rest.AbstractRestBean;
-import org.rhq.enterprise.server.rest.SetCallerInterceptor;
-import org.rhq.enterprise.server.util.CriteriaQuery;
-import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
+import java.io.IOException;
+import java.io.OutputStream;
import static org.rhq.core.domain.util.PageOrdering.ASC;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.cleanForCSV;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.cleanForCSV;
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.formatDateTime;
@Interceptors(SetCallerInterceptor.class)
@Stateless
@@ -68,7 +67,7 @@ public class ConfigurationHistoryHandler extends AbstractRestBean implements Con
+ formatDateTime(configurationUpdate.getCreatedTime())+","
+ formatDateTime(configurationUpdate.getModifiedTime())+","
+ configurationUpdate.getStatus()+","
- + cleanForCSV(ReportHelper.parseAncestry(configurationUpdate.getResource().getAncestry())) + ","
+ + cleanForCSV(ReportFormatHelper.parseAncestry(configurationUpdate.getResource().getAncestry())) + ","
+ getDetailsURL(configurationUpdate);
//@todo: check dates, user, update-type
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/InventorySummaryHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/InventorySummaryHandler.java
index d1d0d37..55ee582 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/InventorySummaryHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/InventorySummaryHandler.java
@@ -18,27 +18,6 @@
*/
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Request;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.UriInfo;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-
import org.rhq.core.domain.criteria.ResourceCriteria;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.composite.ResourceInstallCount;
@@ -49,6 +28,18 @@ import org.rhq.enterprise.server.rest.SetCallerInterceptor;
import org.rhq.enterprise.server.util.CriteriaQuery;
import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.interceptor.Interceptors;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.*;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.*;
+
import static org.rhq.core.domain.resource.InventoryStatus.COMMITTED;
import static org.rhq.core.domain.util.PageOrdering.ASC;
@@ -178,7 +169,7 @@ public class InventorySummaryHandler extends AbstractRestBean implements Invento
}
protected String toCSV(Resource resource) {
- return resource.getName() + "," + ReportHelper.parseAncestry(resource.getAncestry()) + "," +
+ return resource.getName() + "," + ReportFormatHelper.parseAncestry(resource.getAncestry()) + "," +
resource.getDescription() + "," + resource.getResourceType().getName() + "," + resource.getVersion() +
"," + resource.getCurrentAvailability().getAvailabilityType();
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java
index a68cb82..f4687db 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java
@@ -1,29 +1,8 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.UriInfo;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
-import org.rhq.core.domain.alert.Alert;
-import org.rhq.core.domain.alert.AlertCondition;
-import org.rhq.core.domain.alert.AlertConditionCategory;
-import org.rhq.core.domain.alert.AlertConditionLog;
-import org.rhq.core.domain.alert.AlertConditionOperator;
-import org.rhq.core.domain.alert.AlertPriority;
+import org.rhq.core.domain.alert.*;
import org.rhq.core.domain.criteria.AlertCriteria;
import org.rhq.core.domain.measurement.MeasurementUnits;
import org.rhq.core.domain.util.PageList;
@@ -33,8 +12,22 @@ import org.rhq.enterprise.server.rest.SetCallerInterceptor;
import org.rhq.enterprise.server.util.CriteriaQuery;
import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.cleanForCSV;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.interceptor.Interceptors;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.StreamingOutput;
+import javax.ws.rs.core.UriInfo;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.cleanForCSV;
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.formatDateTime;
@Interceptors(SetCallerInterceptor.class)
@Stateless
@@ -87,7 +80,7 @@ public class RecentAlertHandler extends AbstractRestBean implements RecentAlertL
alert.getAlertDefinition().getPriority() + "," +
getStatus(alert) + "," +
cleanForCSV(alert.getAlertDefinition().getResource().getName()) + "," +
- cleanForCSV(ReportHelper.parseAncestry(alert.getAlertDefinition().getResource().getAncestry()))
+ cleanForCSV(ReportFormatHelper.parseAncestry(alert.getAlertDefinition().getResource().getAncestry()))
+ "," + getDetailsURL(alert);
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentDriftHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentDriftHandler.java
index 6a56fb9..fb30273 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentDriftHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentDriftHandler.java
@@ -1,22 +1,7 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.UriInfo;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
import org.rhq.core.domain.criteria.DriftCriteria;
import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.DriftCategory;
@@ -28,8 +13,21 @@ import org.rhq.enterprise.server.rest.SetCallerInterceptor;
import org.rhq.enterprise.server.util.CriteriaQuery;
import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.cleanForCSV;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.interceptor.Interceptors;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.StreamingOutput;
+import javax.ws.rs.core.UriInfo;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.cleanForCSV;
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.formatDateTime;
@Interceptors(SetCallerInterceptor.class)
@Stateless
@@ -108,7 +106,7 @@ public class RecentDriftHandler extends AbstractRestBean implements RecentDriftL
drift.getDrift().getCategory() + "," +
drift.getDrift().getPath() + "," +
cleanForCSV(drift.getResource().getName()) +","+
- cleanForCSV(ReportHelper.parseAncestry(drift.getResource().getAncestry())) + "," +
+ cleanForCSV(ReportFormatHelper.parseAncestry(drift.getResource().getAncestry())) + "," +
getDetailsURL(drift);
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java
index 0431735..3ce9a93 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java
@@ -1,22 +1,7 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.UriInfo;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
import org.rhq.core.domain.criteria.ResourceOperationHistoryCriteria;
import org.rhq.core.domain.operation.OperationRequestStatus;
import org.rhq.core.domain.operation.ResourceOperationHistory;
@@ -27,8 +12,21 @@ import org.rhq.enterprise.server.rest.SetCallerInterceptor;
import org.rhq.enterprise.server.util.CriteriaQuery;
import org.rhq.enterprise.server.util.CriteriaQueryExecutor;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.cleanForCSV;
-import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.interceptor.Interceptors;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.StreamingOutput;
+import javax.ws.rs.core.UriInfo;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.cleanForCSV;
+import static org.rhq.enterprise.server.rest.reporting.ReportFormatHelper.formatDateTime;
@Interceptors(SetCallerInterceptor.class)
@Stateless
@@ -79,7 +77,7 @@ public class RecentOperationsHandler extends AbstractRestBean implements RecentO
operation.getSubjectName() + "," +
operation.getStatus() + "," +
cleanForCSV(operation.getResource().getName()) +","+
- cleanForCSV(ReportHelper.parseAncestry(operation.getResource().getAncestry())) + "," +
+ cleanForCSV(ReportFormatHelper.parseAncestry(operation.getResource().getAncestry())) + "," +
getDetailsURL(operation);
}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportFormatHelper.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportFormatHelper.java
new file mode 100644
index 0000000..9e0f533
--- /dev/null
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportFormatHelper.java
@@ -0,0 +1,96 @@
+/*
+ *
+ * * RHQ Management Platform
+ * * Copyright (C) 2005-2012 Red Hat, Inc.
+ * * All rights reserved.
+ * *
+ * * This program is free software; you can redistribute it and/or modify
+ * * it under the terms of the GNU General Public License as published by
+ * * the Free Software Foundation version 2 of the License.
+ * *
+ * * This program is distributed in the hope that it will be useful,
+ * * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * * GNU General Public License for more details.
+ * *
+ * * You should have received a copy of the GNU General Public License
+ * * along with this program; if not, write to the Free Software
+ * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ *
+ */
+package org.rhq.enterprise.server.rest.reporting;
+
+import org.rhq.core.domain.resource.Resource;
+
+import java.text.DateFormat;
+import java.util.Date;
+
+/**
+ * Formatting tools for rest reporting.
+ */
+public class ReportFormatHelper {
+
+ private ReportFormatHelper(){
+ // This is just a static utility class
+ }
+
+ /**
+ * Strip out any invalid characters from CSV data.
+ * @param input
+ * @return Cleaned String suitable for inclusion in CSV file
+ */
+ public static String cleanForCSV(String input){
+ if (input == null) {
+ return " ";
+ }
+ return input.replace(',',' ').replace('\n', ' ');
+ }
+
+ /**
+ * Standard Date/time format for CSV files
+ * @param epochMillis
+ * @return String formatted string (i.e. '11/4/03 8:14 PM')
+ */
+ public static String formatDateTime(long epochMillis){
+ if(epochMillis != 0){
+ Date date = new Date(epochMillis);
+ return DateFormat.getInstance().format(date);
+ }else {
+ return " ";
+ }
+ }
+
+
+ /**
+ * Standard Date/time format for CSV files
+ * @param epochMillis
+ * @return String formatted string (i.e. '11/4/03')
+ */
+ public static String formatDate(long epochMillis){
+ if(epochMillis != 0){
+ Date date = new Date(epochMillis);
+ return DateFormat.getDateInstance().format(date);
+ }else {
+ return " ";
+ }
+ }
+
+ public static String parseAncestry(String ancestry) {
+ if (null == ancestry) {
+ return "";
+ }
+
+ StringBuilder builder = new StringBuilder();
+ String[] ancestryEntries = ancestry.split(Resource.ANCESTRY_DELIM);
+ for (int i = 0; i < ancestryEntries.length; ++i) {
+ String[] entryTokens = ancestryEntries[i].split(Resource.ANCESTRY_ENTRY_DELIM);
+ String ancestorName = entryTokens[2];
+ builder.append((i > 0) ? " < " : "");
+ builder.append(ancestorName);
+
+ }
+
+ return builder.toString();
+ }
+
+}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportHelper.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportHelper.java
deleted file mode 100644
index 8b0b043..0000000
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportHelper.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- *
- * * RHQ Management Platform
- * * Copyright (C) 2005-2012 Red Hat, Inc.
- * * All rights reserved.
- * *
- * * This program is free software; you can redistribute it and/or modify
- * * it under the terms of the GNU General Public License as published by
- * * the Free Software Foundation version 2 of the License.
- * *
- * * This program is distributed in the hope that it will be useful,
- * * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * * GNU General Public License for more details.
- * *
- * * You should have received a copy of the GNU General Public License
- * * along with this program; if not, write to the Free Software
- * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- *
- */
-package org.rhq.enterprise.server.rest.reporting;
-
-import java.text.DateFormat;
-import java.util.Date;
-
-import org.rhq.core.domain.resource.Resource;
-
-/**
- * Formatting tools for rest reporting.
- */
-public class ReportHelper {
-
- private ReportHelper(){
- // This is just a static utility class
- }
-
- /**
- * Strip out any invalid characters from CSV data.
- * @param input
- * @return Cleaned String suitable for inclusion in CSV file
- */
- public static String cleanForCSV(String input){
- if (input == null) {
- return " ";
- }
- return input.replace(',',' ').replace('\n', ' ');
- }
-
- /**
- * Standard Date/time format for CSV files
- * @param epochMillis
- * @return String formatted string (i.e. '11/4/03 8:14 PM')
- */
- public static String formatDateTime(long epochMillis){
- Date date = new Date(epochMillis);
- return DateFormat.getInstance().format(date);
- }
-
-
- /**
- * Standard Date/time format for CSV files
- * @param epochMillis
- * @return String formatted string (i.e. '11/4/03')
- */
- public static String formatDate(long epochMillis){
- Date date = new Date(epochMillis);
- return DateFormat.getDateInstance().format(date);
- }
-
- public static String parseAncestry(String ancestry) {
- if (null == ancestry) {
- return "";
- }
-
- StringBuilder builder = new StringBuilder();
- String[] ancestryEntries = ancestry.split(Resource.ANCESTRY_DELIM);
- for (int i = 0; i < ancestryEntries.length; ++i) {
- String[] entryTokens = ancestryEntries[i].split(Resource.ANCESTRY_ENTRY_DELIM);
- String ancestorName = entryTokens[2];
- builder.append((i > 0) ? " < " : "");
- builder.append(ancestorName);
-
- }
-
- return builder.toString();
- }
-
-}
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/SuspectMetricHandler.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/SuspectMetricHandler.java
index 607183f..c2b4726 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/SuspectMetricHandler.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/SuspectMetricHandler.java
@@ -1,16 +1,7 @@
package org.rhq.enterprise.server.rest.reporting;
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
import org.rhq.core.domain.measurement.composite.MeasurementOOBComposite;
import org.rhq.core.domain.util.PageControl;
import org.rhq.core.domain.util.PageList;
@@ -19,6 +10,14 @@ import org.rhq.enterprise.server.measurement.MeasurementOOBManagerLocal;
import org.rhq.enterprise.server.rest.AbstractRestBean;
import org.rhq.enterprise.server.rest.SetCallerInterceptor;
+import javax.ejb.EJB;
+import javax.ejb.Stateless;
+import javax.interceptor.Interceptors;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
@Interceptors(SetCallerInterceptor.class)
@Stateless
public class SuspectMetricHandler extends AbstractRestBean implements SuspectMetricLocal {
@@ -53,7 +52,7 @@ public class SuspectMetricHandler extends AbstractRestBean implements SuspectMet
for (MeasurementOOBComposite oobComposite : comps) {
sb.append( oobComposite.getResourceName());
sb.append(",");
- sb.append(ReportHelper.parseAncestry(oobComposite.getResourceAncestry()));
+ sb.append(ReportFormatHelper.parseAncestry(oobComposite.getResourceAncestry()));
sb.append(",");
sb.append( oobComposite.getUnits()); // Metric
sb.append(",");
12 years, 1 month
[rhq] modules/plugins
by Heiko W. Rupp
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java | 27 ++
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 115 ++++++++--
2 files changed, 118 insertions(+), 24 deletions(-)
New commits:
commit ef475f431b3d6e4c356a72c2fb4198a632c10fa4
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Thu Mar 29 15:18:15 2012 +0200
BZ 802561 - fix display of resource configuration. Add system-properties.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java
index c5a17a8..139fdff 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ServerGroupComponent.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2011 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -29,6 +29,7 @@ import java.util.Set;
import org.codehaus.jackson.JsonNode;
+import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.content.PackageDetailsKey;
import org.rhq.core.domain.content.PackageType;
import org.rhq.core.domain.content.transfer.ContentResponseResult;
@@ -41,6 +42,8 @@ import org.rhq.core.pluginapi.content.ContentContext;
import org.rhq.core.pluginapi.content.ContentFacet;
import org.rhq.core.pluginapi.content.ContentServices;
import org.rhq.core.pluginapi.inventory.CreateChildResourceFacet;
+import org.rhq.core.pluginapi.operation.OperationFacet;
+import org.rhq.core.pluginapi.operation.OperationResult;
import org.rhq.modules.plugins.jbossas7.json.Address;
import org.rhq.modules.plugins.jbossas7.json.CompositeOperation;
import org.rhq.modules.plugins.jbossas7.json.Operation;
@@ -53,12 +56,32 @@ import org.rhq.modules.plugins.jbossas7.json.Result;
* @author Heiko W. Rupp
*/
@SuppressWarnings("unused")
-public class ServerGroupComponent extends ManagedASComponent implements ContentFacet, CreateChildResourceFacet {
+public class ServerGroupComponent extends BaseComponent implements ContentFacet, CreateChildResourceFacet,
+ OperationFacet {
private static final String SUCCESS = "success";
private static final String OUTCOME = "outcome";
@Override
+ public OperationResult invokeOperation(String name,
+ Configuration parameters) throws InterruptedException, Exception {
+
+ Operation op = new Operation(name,getAddress());
+ Result res = getASConnection().execute(op);
+
+ OperationResult result = new OperationResult();
+
+ if (res.isSuccess()) {
+ result.setSimpleResult(SUCCESS);
+ }
+ else {
+ result.setErrorMessage(res.getFailureDescription());
+ }
+ return result;
+
+ }
+
+ @Override
public List<DeployPackageStep> generateInstallationSteps(ResourcePackageDetails packageDetails) {
return null; // TODO: Customise this generated block
}
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 8436761..40c49c0 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
@@ -147,6 +147,12 @@
<c:map-property name="*:name" displayName="Name" readOnly="true">
<c:simple-property name="name" displayName="Property-Name" readOnly="true"/>
<c:simple-property name="value" displayName="Value"/>
+ <c:simple-property name="boot-time" defaultValue="true" description="If true the system property is passed on the command-line to the started server jvm. If false, it will be pushed to the server as part of the startup sequence.">
+ <c:property-options>
+ <c:option value="true"/>
+ <c:option value="false"/>
+ </c:property-options>
+ </c:simple-property>
</c:map-property>
</c:list-property>
</c:group>
@@ -222,9 +228,54 @@
</c:simple-property>
<c:simple-property name="socket-binding-port-offset" required="false" defaultValue="0" type="integer"
description="The default offset to be added to the port values given by the socket binding group."/>
- <c:simple-property name="jvm" required="false"/> <!-- TODO -->
- </resource-configuration>
+
+ <c:group name="children:system-property:name+" displayName="System-properties">
+ <c:list-property name="*2" displayName="Properties" required="false" readOnly="false">
+ <c:map-property name="*:name" displayName="Name" readOnly="true">
+ <c:simple-property name="name" displayName="Property-Name" readOnly="true"/>
+ <c:simple-property name="value" displayName="Value"/>
+ <c:simple-property name="boot-time" defaultValue="true" description="If true the system property is passed on the command-line to the started server jvm. If false, it will be pushed to the server as part of the startup sequence.">
+ <c:property-options>
+ <c:option value="true"/>
+ <c:option value="false"/>
+ </c:property-options>
+ </c:simple-property>
+ </c:map-property>
+ </c:list-property>
+ </c:group>
+<!-- TODO commented out as it makes the whole config not show in the UI - fetch from AS works ok
+ <c:group name="children:jvm:name+" displayName="JVMs">
+ <c:list-property name="*3" displayName="JVM" required="false" description="JVM properties">
+ <c:map-property name="*:name" displayName="Name" readOnly="false">
+ <c:simple-property name="name" required="true" type="string" readOnly="true" description="Name of this JVM definition"/>
+ <c:simple-property name="agent-lib" required="false" type="string" readOnly="false" description="The JVM agent lib."/>
+ <c:simple-property name="agent-path" required="false" type="string" readOnly="false" description="The JVM agent path."/>
+ <c:simple-property name="env-classpath-ignored" required="false" type="boolean" readOnly="false" description="Ignore the environment classpath."/>
+ <c:list-property name="environment-variables" description="The JVM environment variables." >
+ <c:simple-property name="environment-variable" />
+ </c:list-property>
+ <c:simple-property name="heap-size" required="false" type="string" readOnly="false" description="The initial heap size allocated by the JVM."/>
+ <c:simple-property name="java-agent" required="false" type="string" readOnly="false" description="The java agent."/>
+ <c:simple-property name="java-home" required="false" type="string" readOnly="false" description="The java home"/>
+ <c:list-property name="jvm-options" description="The JVM options." >
+ <c:simple-property name="jvm-option" />
+ </c:list-property>
+ <c:simple-property name="max-heap-size" required="false" type="string" readOnly="false" description="The maximum heap size that can be allocated by the JVM."/>
+ <c:simple-property name="max-permgen-size" required="false" type="string" readOnly="false" description="The maximum size of the permanent generation."/>
+ <c:simple-property name="permgen-size" required="false" type="string" readOnly="false" description="The initial permanent generation size."/>
+ <c:simple-property name="stack-size" required="false" type="string" readOnly="false" description="The JVM stack size settings."/>
+ <c:simple-property name="type" required="false" type="string" readOnly="true" description="The JVM type can be either SUN or IBM" default="SUN">
+ <c:property-options>
+ <c:option value="SUN"/>
+ <c:option value="IBM"/>
+ </c:property-options>
+ </c:simple-property>
+ </c:map-property>
+ </c:list-property>
+ </c:group>
+-->
+ </resource-configuration>
</server>
<server name="Host"
description="Host involved in this domain"
@@ -236,29 +287,28 @@
</plugin-configuration>
-
<resource-configuration>
<c:group name="children:system-property:name+" displayName="System-properties">
- <c:list-property name="*2" displayName="Properties" required="false" readOnly="false">
- <c:map-property name="*:name" displayName="Name" readOnly="true">
- <c:simple-property name="name" displayName="Property-Name" readOnly="true"/>
- <c:simple-property name="value" displayName="Value"/>
- </c:map-property>
- </c:list-property>
- </c:group>
+ <c:list-property name="*2" displayName="Properties" required="false" readOnly="false">
+ <c:map-property name="*:name" displayName="Name" readOnly="true">
+ <c:simple-property name="name" displayName="Property-Name" readOnly="true"/>
+ <c:simple-property name="value" displayName="Value"/>
+ </c:map-property>
+ </c:list-property>
+ </c:group>
<c:group name="children:path:name+" displayName="Path">
- <c:list-property name="*3" displayName="Path" required="false"
- description="The standard paths provided by the system include: jboss.home - the root directory of the JBoss AS distribution; user.home - user's home directory; user.dir - user's current working directory; java.home - java installation directory; jboss.server.base.dir - root directory for an individual server instance; jboss.server.data.dir - directory the server will use for persistent data file storage; jboss.server.log.dir - directory the server will use for log file storage; jboss.server.tmp.dir - directory the server will use for temporary file storage; jboss.domain.servers.dir - directory under which a host controller will create the working area for individual server instances">
- <c:map-property name="*" displayName="Entry">
- <c:simple-property name="name" required="true" type="string" readOnly="false"
- description="The name of the path. Cannot be one of the standard fixed paths provided by the system"/>
- <c:simple-property name="path" required="true" type="string" readOnly="false"
- description="The actual filesystem path. Treated as an absolute path, unless the 'relative-to' attribute is specified, in which case the value is treated as relative to that 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."/>
- </c:map-property>
- </c:list-property>
- </c:group>
+ <c:list-property name="*3" displayName="Path" required="false"
+ description="The standard paths provided by the system include: jboss.home - the root directory of the JBoss AS distribution; user.home - user's home directory; user.dir - user's current working directory; java.home - java installation directory; jboss.server.base.dir - root directory for an individual server instance; jboss.server.data.dir - directory the server will use for persistent data file storage; jboss.server.log.dir - directory the server will use for log file storage; jboss.server.tmp.dir - directory the server will use for temporary file storage; jboss.domain.servers.dir - directory under which a host controller will create the working area for individual server instances">
+ <c:map-property name="*" displayName="Entry">
+ <c:simple-property name="name" required="true" type="string" readOnly="false"
+ description="The name of the path. Cannot be one of the standard fixed paths provided by the system"/>
+ <c:simple-property name="path" required="true" type="string" readOnly="false"
+ description="The actual filesystem path. Treated as an absolute path, unless the 'relative-to' attribute is specified, in which case the value is treated as relative to that 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."/>
+ </c:map-property>
+ </c:list-property>
+ </c:group>
</resource-configuration>
</server>
@@ -313,6 +363,21 @@
<c:simple-property name="auto-start" displayName="Autostart" default="false" type="boolean" />
+ <c:group name="children:system-property:name+" displayName="System-properties">
+ <c:list-property name="*2" displayName="Properties" required="false" readOnly="false">
+ <c:map-property name="*:name" displayName="Name" readOnly="true">
+ <c:simple-property name="name" displayName="Property-Name" readOnly="true"/>
+ <c:simple-property name="value" displayName="Value"/>
+ <c:simple-property name="boot-time" defaultValue="true" description="If true the system property is passed on the command-line to the started server jvm. If false, it will be pushed to the server as part of the startup sequence.">
+ <c:property-options>
+ <c:option value="true"/>
+ <c:option value="false"/>
+ </c:property-options>
+ </c:simple-property>
+ </c:map-property>
+ </c:list-property>
+ </c:group>
+
</resource-configuration>
</server>
@@ -441,6 +506,12 @@
<c:map-property name="*:name" displayName="Name" readOnly="true">
<c:simple-property name="name" displayName="Property-Name" readOnly="true"/>
<c:simple-property name="value" displayName="Value"/>
+ <c:simple-property name="boot-time" defaultValue="true" description="If true the system property is passed on the command-line to the started server jvm. If false, it will be pushed to the server as part of the startup sequence.">
+ <c:property-options>
+ <c:option value="true"/>
+ <c:option value="false"/>
+ </c:property-options>
+ </c:simple-property>
</c:map-property>
</c:list-property>
</c:group>
12 years, 1 month
[rhq] modules/enterprise
by Heiko W. Rupp
modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties | 411 +++++-----
1 file changed, 231 insertions(+), 180 deletions(-)
New commits:
commit a09e1a53f366224e567af3e42b93adbba43d5033
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Thu Mar 29 12:10:56 2012 +0200
Copy over rev 280095f47b from translations project. Relates to BZ 806281
diff --git a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
index 81535f4..c183707 100644
--- a/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
+++ b/modules/enterprise/gui/coregui/src/main/resources/org/rhq/enterprise/gui/coregui/client/Messages_de.properties
@@ -1,3 +1,4 @@
+# suppress inspection "UnusedProperty" for whole file
#
# RHQ GUI i18n Messages - Locale: DE
#
@@ -35,8 +36,8 @@ common_button_new = Neu
common_button_next = Weiter
common_button_ok = OK
common_button_previous = Zurück
-common_button_purge = Löschen
-common_button_purgeAll = Alle löschen
+common_button_purge = Bereinigen
+common_button_purgeAll = Alle bereinigen
common_button_refresh = Neu laden
common_button_reset = Zurücksetzen
common_button_save = Speichern
@@ -80,7 +81,7 @@ common_label_users = Benutzer
common_label_week = Woche
common_label_yesterday = Gestern
common_msg_areYouSure = Sind Sie sicher?
-##common_msg_asyncTimeout = {0}. This occurred because the server is taking a long time to complete this request. Please be aware that the server may still be processing your request and it may complete shortly. You can check the server logs to see if any abnormal errors occurred.
+common_msg_asyncTimeout = {0}. Dies ist aufgetreten weil der Server lange Zeit für die Bearbeitung der Anfrage benötigt. Bitte beachten Sie, dass der Serer eventuell Ihre Anfrage immer noch bearbeitet und bald fertig sein kann. Sie können die Server-Logs überprüfen, um zu sehen, ob abnormale Bedingungen aufgetreten sind.
common_msg_changeAutoDetected = Änderungen gefunden
##common_msg_deleteConfirm = Are you sure you want to delete the # selected {0}?
common_msg_emphasizedNotePrefix = Achtung:
@@ -152,7 +153,7 @@ common_title_id_parent = ID des Vaters
common_title_interval = Intervall
common_title_inventory = Inventar
common_title_inventorySummary = Inventar Zusammenfassung
-common_title_kind = Kind
+common_title_kind = Art
common_title_lastUpdated = Zuletzt aktualisiert
common_title_lastUpdatedBy = Zuletzt aktualisiert durch
common_title_ldapGroups = LDAP-Gruppen
@@ -179,7 +180,7 @@ common_title_platform = Plattform
common_title_platform_total = Anzahl Platformen
common_title_plugin = Plugin
common_title_port = Port
-##common_title_providers = Providers
+common_title_providers = Anbieter
common_title_recent_alerts = Kürzlich ausgelöste Alarme
common_title_recent_bundle_deployments = Kürzliche Bundle-Deployments
common_title_recent_configuration_updates = Frische Konfigurationsaktualisierungen
@@ -188,7 +189,7 @@ common_title_recent_event_counts = Anzahl frischer Ereignisse
common_title_recent_measurements = Frische Messwerte
common_title_recent_oob_metrics = Kürzlich aus dem Ruder gelaufene Metriken
common_title_recent_operations = Kürzlich ausgeführte Operationen
-##common_title_recent_pkg_history = Recent Package History
+common_title_recent_pkg_history = Kürzlich geänderte Pakete
common_title_recently_added = Kürzlich hinzugefügte Ressourcen
common_title_remove_column = Spalte löschen
##common_title_repositories = Repositories
@@ -233,30 +234,30 @@ common_title_version = Version
common_title_view_mode = Anzeigemodus
common_title_web_address = Webaddresse
common_title_welcome = Willkommen
-##common_unit_abbrev_bits = b
-##common_unit_abbrev_bytes = B
-##common_unit_abbrev_celsius = C
-##common_unit_abbrev_days = d
-##common_unit_abbrev_fahrenheight = F
-##common_unit_abbrev_gigabits = Gb
-##common_unit_abbrev_gigabytes = GB
-##common_unit_abbrev_hours = h
-##common_unit_abbrev_jiffys = j
-##common_unit_abbrev_kelvin = K
-##common_unit_abbrev_kilobits = Kb
-##common_unit_abbrev_kilobytes = KB
-##common_unit_abbrev_megabits = Mb
-##common_unit_abbrev_megabytes = MB
-##common_unit_abbrev_microseconds = us
-##common_unit_abbrev_milliseconds = ms
-##common_unit_abbrev_minutes = m
-##common_unit_abbrev_nanoseconds = ns
-##common_unit_abbrev_percentage = %
-##common_unit_abbrev_petabits = Pb
-##common_unit_abbrev_petabytes = PB
-##common_unit_abbrev_seconds = s
-##common_unit_abbrev_terabits = Tb
-##common_unit_abbrev_terabytes = TB
+common_unit_abbrev_bits = b
+common_unit_abbrev_bytes = B
+common_unit_abbrev_celsius = C
+common_unit_abbrev_days = d
+common_unit_abbrev_fahrenheight = F
+common_unit_abbrev_gigabits = Gbit
+common_unit_abbrev_gigabytes = GiB
+common_unit_abbrev_hours = h
+common_unit_abbrev_jiffys = j
+common_unit_abbrev_kelvin = K
+common_unit_abbrev_kilobits = kbit
+common_unit_abbrev_kilobytes = KiB
+common_unit_abbrev_megabits = Mbit
+common_unit_abbrev_megabytes = MiB
+common_unit_abbrev_microseconds = us
+common_unit_abbrev_milliseconds = ms
+common_unit_abbrev_minutes = min
+common_unit_abbrev_nanoseconds = ns
+common_unit_abbrev_percentage = %
+common_unit_abbrev_petabits = Pbit
+common_unit_abbrev_petabytes = PiB
+common_unit_abbrev_seconds = s
+common_unit_abbrev_terabits = Tbit
+common_unit_abbrev_terabytes = TiB
common_unit_days = Tage
common_unit_days2 = Tagen
common_unit_hours = Stunden
@@ -281,7 +282,7 @@ common_val_nth = {0}er
common_val_yes = Ja
common_val_yes_lower = ja
dataSource_ContentRepoTree_error_load = Konnte die Datenquellen nicht laden
-##dataSource_ContentRepoTree_field_parentId = Parent ID
+dataSource_ContentRepoTree_field_parentId = Vater-ID
dataSource_bundle_loadFailed = Konnte die Bundle-Daten nicht laden
dataSource_configurationHistory_error_fetchFailure = Konnte den Verlauf der Ressourcen-Konfiguration nicht laden.
dataSource_configurationHistory_field_createdTime = Angelegt
@@ -293,7 +294,7 @@ dataSource_measurementOob_error_fetchFailure = Konnte die Informationen über Au
dataSource_measurementOob_field_factor = Ausreißer-Faktor (%)
dataSource_measurementOob_field_formattedBaseband = Band
dataSource_measurementOob_field_formattedOutlier = Ausreißer
-##dataSource_measurementOob_field_parentName = Parent
+dataSource_measurementOob_field_parentName = Übergeordnete Ressource
dataSource_measurementOob_field_resourceName = Ressource
dataSource_measurementOob_field_scheduleName = Metrik
dataSource_operationHistory_error_fetchFailure = Konnte den Verlauf der Operationen nicht laden.
@@ -319,15 +320,15 @@ dataSource_recentOperations_field_resource = Ressource
dataSource_recentOperations_field_status = Status
dataSource_resourceErrors_clickStatusIcon = Für mehr Details auf das Icon klicken
dataSource_resourceErrors_deleteFailure = Konnte die Ressourcen-Fehler nicht löschen
-dataSource_resourceErrors_deleteSuccess = Sie haben erfolgreich [{0}] Ressourcen-Fehlermeldungen gelöscht.
+dataSource_resourceErrors_deleteSuccess = Sie haben [{0}] Ressourcen-Fehlermeldungen erfolgreich gelöscht.
dataSource_resourceErrors_error_fetchFailure = Konnte die spezifischen Fehler für die Ressource mit id [{0}] nicht laden.
dataSource_resourceErrors_field_errorType = Fehlertyp
dataSource_resourceErrors_field_summary = Zsuammenfassung
dataSource_resourceErrors_field_timeOccured = Zeitpunkt
dataSource_resourceGroups_loadFailed = Konnte die Ressourcen-Gruppe nicht laden
dataSource_rpc_error_transformRequestFailure = Fehler in der (GWT)-Datenquelle bei der Bearbeitung der {0} Anfrage.
-##dataSource_rpc_error_unsupportedArrayFilterType = No support for passing array filters of type {0}.
-##dataSource_rpc_error_unsupportedEnumType = Please add an appropriate code block for enum {0} to RPCDataSource.getEnumArray(Class)
+dataSource_rpc_error_unsupportedArrayFilterType = Es gibt keine Unterstützung für die Übergabe von Feld-Filtern des Typs {0}. Bitte melden Sie einen Bug.
+dataSource_rpc_error_unsupportedEnumType = Es wird ein Code-Block für enum {0} in RPCDataSource.getEnumArray(Class) benötigt. Bitte melden Sie einen Bug.
dataSource_rpc_no = nein
dataSource_rpc_yes = ja
dataSource_scheduledOperations_error_fetchFailure = Konnte die Liste der geplanten Operationen nicht laden.
@@ -428,7 +429,7 @@ view_adminRoles_permissions_isWrite = Schreiben?
view_adminRoles_permissions_permDesc_manageBundles = Kann Bundles anlegen, aktualisieren und löschen (Ansehen ist für alle implizit erlaubt).
view_adminRoles_permissions_permDesc_manageInventory = Hat alle Rechte auf alle Ressourcen, wie unten beschrieben. Kann Gruppen anlegen, aktualisieren und löschen. Kann Ressourcen in das Inventar aufnehmen.
view_adminRoles_permissions_permDesc_manageSecurity = Kann Benutzer und Rollen anlegen, aktualisieren oder löschen (Anschauen ist für alle implizit erlaubt)
-##view_adminRoles_permissions_permDesc_manageSettings = Kann die Konfiguration des RHQ-Servers ändern und jegliche Server-bezogene Funktionalität ausführen.
+view_adminRoles_permissions_permDesc_manageSettings = Kann die Konfiguration des {0}-Servers ändern und jegliche Server-bezogene Funktionalität ausführen.
view_adminRoles_permissions_permReadDesc_configure = Ansehen der Ressourcen-Konfiguration und des Verlaufs derselben.
view_adminRoles_permissions_permReadDesc_control = (IMPLIZIT) Ansehen der verfügbaren Operationen und des Verlaufs der ausgeführen Operationen
view_adminRoles_permissions_permReadDesc_createChildResources = (IMPLIZIT) Ansehen des Verlaufs des Anlegens von Kind-Ressourcen
@@ -493,32 +494,32 @@ view_admin_content = Inhalte
view_admin_downloads_agent_buildNumber = Build-Nummer des Agents
view_admin_downloads_agent_md5 = MD5 Prüfsumme des Agents
view_admin_downloads_agent_version = Version des Agents
-##view_admin_downloads_cliAlertScriptsDownload = CLI Alert Scripts Download
-##view_admin_downloads_cliAlertScripts_help = CLI alert scripts are pre-canned scripts that can be used as templates for creating actual scripted alert notifications. The scripts will usually require some tweaking before they can be used as a notification on a particular alert definition.
-##view_admin_downloads_cliAlertScripts_loadError = Cannot get info on available CLI alert scripts for download
-##view_admin_downloads_cliAlertScripts_none = No CLI alert scripts are available for download
+view_admin_downloads_cliAlertScriptsDownload = Download von CLI-Alarm-Skripten
+view_admin_downloads_cliAlertScripts_help = CLI-Alarm-Skripte sind vorefertigete Skripte, die als Vorlagen für die Erstellung von Alert-Skripten genutzt werden können. Die Skripte benötigen üblicherweise einiger Anpassungen bevore sie zur Benachrichtigun für eine spezifische Alarm-Definition genutzt werden können.
+view_admin_downloads_cliAlertScripts_loadError = Kann keine Infromationen über CLI-Alarm-Skripte für den Download lesen
+view_admin_downloads_cliAlertScripts_none = Es liegen keine CLI-Alarm-Skripte für den Download vor
view_admin_downloads_cli_md5 = MD5 Prüfsumme des CLI
view_admin_downloads_cli_version = Version des CLI
view_admin_landing = In dieser Sektion können die globalen Einstellungen für {0} verwaltet werden. Dies schließt Sicherheitseinstellungen und Plugins ein, sowie die Verwaltung der {0} Server- und Agentplugins.
-##view_admin_measTemplates_updateExisting_title = Update Existing Schedules
+view_admin_measTemplates_updateExisting_title = Existierende Zeitpläne aktualisieren
##view_admin_measTemplates_updateExisting_tooltip = Check this box to update the collection schedules for the selected metrics on all existing resources of this type. If this is not checked, the template schedules will only be applied to new resources of this type that are added to inventory in the future.
-##view_admin_plugins_agent = Agent
+view_admin_plugins_agent = Agent
##view_admin_plugins_agentDeleteConfirm = <b>Warning!</b><br/>\nThe following agent plugins are about to be deleted:<br/>\n{0}<br/>\nAre you sure you want to delete these?
##view_admin_plugins_agentDisableConfirm = <b>Warning!</b><br/>\nThe following agent plugins are about to be disabled:<br/>\n{0}<br/>\nAre you sure you want to disable these?
view_admin_plugins_deletedAgentPlugins = Diese Agent-Plugins wurden gelöscht: {0}
view_admin_plugins_deletedAgentPluginsFailure = Konnte die Agent-Plugins nicht löschen.
-##view_admin_plugins_deployed = Deployed?
-##view_admin_plugins_disabledAgentPlugins = Disabled agent plugins: {0}
-##view_admin_plugins_disabledAgentPluginsFailure = Failed to disable agent plugins.
-##view_admin_plugins_disabledServerPlugins = Disabled server plugins: {0}
-##view_admin_plugins_disabledServerPluginsFailure = Failed to disable server plugins.
-##view_admin_plugins_enabledAgentPlugins = Enabled agent plugins: {0}
-##view_admin_plugins_enabledAgentPluginsFailure = Failed to enable agent plugins.
-##view_admin_plugins_enabledServerPlugins = Enabled server plugins: {0}
-##view_admin_plugins_enabledServerPluginsFailure = Failed to enable server plugins.
+view_admin_plugins_deployed = Deployed?
+view_admin_plugins_disabledAgentPlugins = Agent-Plugins {0} deaktiviert
+view_admin_plugins_disabledAgentPluginsFailure = Konnte die Agent-Plugins nicht deaktivieren.
+view_admin_plugins_disabledServerPlugins = Server-Plugins {0} deaktiviert
+view_admin_plugins_disabledServerPluginsFailure = Konnte die Server-Plugins nicht deaktivieren.
+view_admin_plugins_enabledAgentPlugins = Agent-Plugins {0} aktviert
+view_admin_plugins_enabledAgentPluginsFailure = Konnte die Agent-Plugins nicht aktivieren.
+view_admin_plugins_enabledServerPlugins = Server-Plugis {0} aktiviert
+view_admin_plugins_enabledServerPluginsFailure = Konnte die Server-Plugins nicht aktivieren.
view_admin_plugins_hideDeleted = Gelöschte verbergen
-##view_admin_plugins_hideUndeployed = Hide Undeployed
-##view_admin_plugins_loadFailure = Failed to load plugin data
+view_admin_plugins_hideUndeployed = Nicht-deployte verbergen
+view_admin_plugins_loadFailure = Konnte die Plugin-Daten nicht laden
##view_admin_plugins_purgedAgentPlugins = Preparing to purge agent plugins {0}. This may take a few minutes since all type definitions from the plugins must first be purged from the system. The plugins will still be visible on this page until they have been purged. Please note that you must not re-install the plugin while the purge is running, otherwise failures will occur. Therefore, please wait before attempting to re-install the plugin into the system until this purge is complete.
##view_admin_plugins_purgedAgentPluginsFailure = Failed to purge agent plugins.
##view_admin_plugins_purgedServerPlugins = Purged server plugins: {0}.
@@ -528,8 +529,8 @@ view_admin_plugins_hideDeleted = Gelöschte verbergen
##view_admin_plugins_restartMasterPCFailure = Failed to restart the master plugin container
##view_admin_plugins_restartMasterPCStarted = Restarting the master plugin container...
view_admin_plugins_scan = Updates suchen
-##view_admin_plugins_scanComplete = Finished scanning for updated plugins
-##view_admin_plugins_scanFailure = Failed to scan for updated plugins.
+view_admin_plugins_scanComplete = Die Suche nach aktualisierten Plugins ist beendet
+view_admin_plugins_scanFailure = Die Suche nach aktualisierten Plugins ist fehlgeschlagen
view_admin_plugins_server = Server
view_admin_plugins_serverConfig = Plugin-Konfiguration
view_admin_plugins_serverConfig_badSettings = Bitte geben Sie gültige Daten ein
@@ -554,12 +555,12 @@ view_admin_plugins_upload = Plugin hochladen
view_admin_security = Sicherheit
##view_admin_systemSettings_ActiveDriftServerPlugin_desc = The drift server plugin that manages the persistence of drift-related entities and content.
view_admin_systemSettings_ActiveDriftServerPlugin_name = Aktives Drift-Server-Plugin
-view_admin_systemSettings_AlertPurge_name = Lösche Alarme, die älter sind als
+view_admin_systemSettings_AlertPurge_name = Bereinigen der Alarme, die älter sind als
view_admin_systemSettings_AvailabilityPurge_name = Lösche Verfügbarkeitsdaten, die älter sind als
##view_admin_systemSettings_DriftFilePurge_desc = How old unused and orphaned drift files must be before being purged from backend storage. This is specified in days.
-view_admin_systemSettings_DriftFilePurge_name = Lösche ungenutzte Drift-Dateine, die älter sind als
+view_admin_systemSettings_DriftFilePurge_name = Bereinige ungenutzte Drift-Dateine, die älter sind als
view_admin_systemSettings_LDAPBindPW_name = Passwort
-view_admin_systemSettings_TraitPurge_name = Lösche Trait-Daten, die älter sind als
+view_admin_systemSettings_TraitPurge_name = Bereinigen der Trait-Daten, die älter sind als
view_admin_systemSettings_dumpToLogFailed = Schreiben der Systeminformation in die Server-Log-Datei ist fehlgeschlagen
view_admin_systemSettings_dumpedToLog = System informationen wurden erfolgreich in die Server-Log-Datei geschrieben
##view_admin_systemSettings_group_drift = Drift Server Configuration Settings
@@ -581,15 +582,15 @@ view_alert_common_tab_conditions_expression = Alarm auslösen wenn
##view_alert_common_tab_conditions_expression_tooltip = Determines if ANY or ALL of the conditions must evaluate to true in order for the entire condition set to be considered true.
view_alert_common_tab_conditions_modal_title = Bedingung hinzufügen
view_alert_common_tab_conditions_recovery_disabled = Dieser Alarm hat seine Definition deaktiviert.
-##view_alert_common_tab_conditions_recovery_enabled = Triggered ''{0}'' to be re-enabled
+view_alert_common_tab_conditions_recovery_enabled = Ausgelöst, dass ''{0}'' wieder aktiviert wurde
view_alert_common_tab_conditions_text = Bedingung
view_alert_common_tab_conditions_type_availability = Änderung der Verfügbarkeit
view_alert_common_tab_conditions_type_availability_down = Wurde unverfügbar
view_alert_common_tab_conditions_type_availability_up = Wurde wieder verfügbar
view_alert_common_tab_conditions_type_drift = Drift-Erkennung
-##view_alert_common_tab_conditions_type_drift_configpaths = Drift Detection for files that match "{0}" and for drift definition [{1}]
-##view_alert_common_tab_conditions_type_drift_onlyconfig = Drift Detection for drift definition [{0}]
-##view_alert_common_tab_conditions_type_drift_onlypaths = Drift Detection for files that match "{0}"
+view_alert_common_tab_conditions_type_drift_configpaths = Drift-Erkennung für Dateien die mit "{0}" übereinstimmen und für die Drift-Definition [{1}]
+view_alert_common_tab_conditions_type_drift_onlyconfig = Drift-Erkennung für die Drift-Definition [{0}]
+view_alert_common_tab_conditions_type_drift_onlypaths = Drift-Erkennung für Dateien die mit "{0}" übereinstimmen
view_alert_common_tab_conditions_type_event = Erkennung von Ereignissen
view_alert_common_tab_conditions_type_event_matching = mit Ereignisquellen, auf die folgendes zutrifft
view_alert_common_tab_conditions_type_metric_baseline = Metrik überschreitet Referenzband
@@ -602,10 +603,10 @@ view_alert_common_tab_conditions_type_metric_calltime_delta_shrinks = Schrumpft
##view_alert_common_tab_conditions_type_metric_calltime_destination = with call destination matching
view_alert_common_tab_conditions_type_metric_calltime_threshold = Call-Time überschreitet Schwellwert
view_alert_common_tab_conditions_type_metric_change = Wert der Metrik ändert sich
-##view_alert_common_tab_conditions_type_metric_range_inside_exclusive = Metric Value Range: [{0}] between [{1}] and [{2}], exclusive
-##view_alert_common_tab_conditions_type_metric_range_inside_inclusive = Metric Value Range: [{0}] between [{1}] and [{2}], inclusive
-##view_alert_common_tab_conditions_type_metric_range_outside_exclusive = Metric Value Range: [{0}] outside [{1}] and [{2}], exclusive
-##view_alert_common_tab_conditions_type_metric_range_outside_inclusive = Metric Value Range: [{0}] outside [{1}] and [{2}], inclusive
+view_alert_common_tab_conditions_type_metric_range_inside_exclusive = Wertbereich der Metrik: [{0}] zwischen [{1}] und [{2}], exklusiv
+view_alert_common_tab_conditions_type_metric_range_inside_inclusive = Wertbereich der Metrik: [{0}] zwischen [{1}] und [{2}], inklusiv
+view_alert_common_tab_conditions_type_metric_range_outside_exclusive = Wertbereich der Metrik: [{0}] ausserhalb [{1}] und [{2}], exklusiv
+view_alert_common_tab_conditions_type_metric_range_outside_inclusive = Wertbereich der Metrik: [{0}] ausserhalb [{1}] und [{2}], inklusiv
view_alert_common_tab_conditions_type_metric_threshold = Metrik überschreitet Schwellwert
view_alert_common_tab_conditions_type_metric_trait_change = Trait-Änderung
view_alert_common_tab_conditions_type_operation = Ausführung der Operation
@@ -641,15 +642,20 @@ view_alert_common_tab_notifications_status = Status
view_alert_common_tab_recovery = Erholung
view_alert_definition_condition_editor_avilability_option_down = Wird unverfügbar
view_alert_definition_condition_editor_avilability_option_up = Wird verfügbar
-##view_alert_definition_condition_editor_avilability_tooltip = Specify the availability state change that will trigger the condition.
+view_alert_definition_condition_editor_avilability_tooltip = Geben Sie die Änderung der Verfügbarkeit an, die die Bedingung auslösen soll.
view_alert_definition_condition_editor_avilability_value = Verfügbarkeit
+view_alert_definition_condition_editor_availabilityDuration = Dauer der Verfügbarkeit
+view_alert_definition_condition_editor_availabilityDuration_tooltip = Geben Sie die Änderung der Verfügbarkeit und die Länge der Dauer des Zustandes an damit die Bedingung zutrifft. Die Dauer ist in Minuten und sollte lang genug sein (mehrere Minuten), um dem Agent Zeit zugeben eine potentielle Änderung des Zustands zu erkennen.
+view_alert_definition_condition_editor_availabilityDuration_tooltip_duration = Die Anzahl der Minuten in der die Ressource die gegeben Verfügbarkeit haben muss, bevor die Bedingung zutrifft.
+view_alert_definition_condition_editor_availability_tooltip = Geben Sie die Änderung des Verfügbarkeitszustandes an, um die Bedingung auszulösen.
+view_alert_definition_condition_editor_availability_value = Verfügbarkeit
view_alert_definition_condition_editor_common_avg = Durchschnitt
view_alert_definition_condition_editor_common_max = Maximum
view_alert_definition_condition_editor_common_min = Minimum
view_alert_definition_condition_editor_delete_confirm = Die ausgewählte(n) Alarm-Bedingung(en) löschen?
view_alert_definition_condition_editor_drift_configname_regex = Name der Drift-Definition
##view_alert_definition_condition_editor_drift_configname_regex_tooltip = If specified, this is the drift definition name that was responsible for the drift that was detected. This can optionally be a regular expression if you wish to match multiple drift definition names.
-##view_alert_definition_condition_editor_drift_pathname_regex = Pathname Regular Expression
+view_alert_definition_condition_editor_drift_pathname_regex = Regulärer Ausdruck für den Pfadnamen
##view_alert_definition_condition_editor_drift_pathname_regex_tooltip = If specified, this is a regular expression that must match the pathnames of those files that drifted.
##view_alert_definition_condition_editor_drift_tooltip = This condition is triggered when drift has been detected.
view_alert_definition_condition_editor_event_regex = Regulärer Ausdruck
@@ -660,7 +666,7 @@ view_alert_definition_condition_editor_event_severity = Schwere des Ereignisses
##view_alert_definition_condition_editor_metric_baseline_percentage_tooltip = A collected metric value will trigger this condition when compared to this percentage of the selected baseline value using the selected comparator
##view_alert_definition_condition_editor_metric_baseline_tooltip = Specify the baseline value that must be violated to trigger the condition. The value you specify is a percentage of the given baseline value.
view_alert_definition_condition_editor_metric_baseline_value = Referenzband
-##view_alert_definition_condition_editor_metric_calltime_change_percentage = Percentage Change
+view_alert_definition_condition_editor_metric_calltime_change_percentage = Änderung des Prozentsatzes
##view_alert_definition_condition_editor_metric_calltime_change_percentage_tooltip = A collected calltime value will trigger this condition when it differs by at least this percentage of the selected calltime limit value
##view_alert_definition_condition_editor_metric_calltime_change_tooltip = Specify the calltime value that, when changed at least a specified amount, triggers the condition. You must specify which calltime limit to check (minimum, maximum or average calltime value) and the percentage of change that must occur.
view_alert_definition_condition_editor_metric_calltime_common_comparator = Komparator
@@ -712,7 +718,7 @@ view_alert_definition_condition_editor_option_metric_baseline = Schwelle des Ref
view_alert_definition_condition_editor_option_metric_calltime_change = Änderung des Call-Time-Werts
##view_alert_definition_condition_editor_option_metric_calltime_threshold = Call Time Value Threshold
view_alert_definition_condition_editor_option_metric_change = Wert der Metrik ändert sich
-##view_alert_definition_condition_editor_option_metric_range = Measurement Value Range
+view_alert_definition_condition_editor_option_metric_range = Wertebereich
view_alert_definition_condition_editor_option_metric_threshold = Absoluter Metrikschwellwert
view_alert_definition_condition_editor_option_metric_trait_change = Änderung des Trait-Werts
view_alert_definition_condition_editor_option_operation = Ausführung der Operation
@@ -816,7 +822,7 @@ view_alerts_field_modified_time = Zuletzt geändert
view_alerts_field_parent = Eltern
view_alerts_field_priority = Priorität
view_alerts_field_protected = Geschützt
-##view_alerts_field_protected_tooltip = If true, this definition is protected from being changed by the parent definition. In other words, the parent definition settings will not override this definition.
+view_alerts_field_protected_tooltip=Wenn diese Option gewählt ist, kann diese Definition nicht durch ihre übergeordnete Definition geändert werden. Anders gesagt\: die Einstellungen der übergeordneten Definition können diese nicht überschreiben.
view_alerts_loadFailed = Konnte die Daten für die Alarme nicht laden
view_alerts_table_filter_priority = Filter nach Priorität
view_alerts_table_title_group = Verlauf Gruppen-Alarme
@@ -867,12 +873,12 @@ view_bundle_bundles = Bundles
view_bundle_createWizard_provideBundleDistro = Stellen Sie eine Bundle-Distribution bereit
##view_bundle_createWizard_recipeOption = Recipe
view_bundle_createWizard_title = Bundle anlegen
-##view_bundle_createWizard_uploadInProgress = Upload is in progress... This can take several minutes for large files
+view_bundle_createWizard_uploadInProgress = Datei wird hochgeladen ... Dies kann für große Dateien mehrere Minuten dauern
view_bundle_createWizard_uploadOption = Hochladen
view_bundle_createWizard_uploadStepName = Bundle-Dateien hochladen
view_bundle_createWizard_urlOption = URL
-##view_bundle_createWizard_windowTitle = Bundle Creation Wizard
-##view_bundle_createWizard_youMustChooseOne = You must choose one option in order to create a bundle!
+view_bundle_createWizard_windowTitle = Assistent zum Anlegen von Bundles
+view_bundle_createWizard_youMustChooseOne = Sie müssen eine Option auswählen, um ein Bundle anlegen zu können!
##view_bundle_deleteConfirm = Are you sure you want to delete this bundle? All versions, destinations and deployments for this bundle will also be deleted. However, this will not remove any content from remote machines.
view_bundle_deploy = Deploy
view_bundle_deployDir = Deploy-Verzeichnis
@@ -917,10 +923,10 @@ view_bundle_deployWizard_getOptions_deployTime = Deployment-Zeitpunkt
##view_bundle_deployWizard_selectBundleStep = Select Deployment Bundle
##view_bundle_deployWizard_selectBundle_single = Select only a single bundle for deployment.
##view_bundle_deployWizard_selectVersionStep = Select Deployment Bundle Version
-##view_bundle_deployWizard_selectVersion_latest = Latest Version [{0}]
-##view_bundle_deployWizard_selectVersion_live = Live Version [{0}]
-##view_bundle_deployWizard_selectVersion_select = Select Version from List:
-##view_bundle_deployWizard_title = Bundle Deployment Wizard
+view_bundle_deployWizard_selectVersion_latest=Letze Version [{0}]
+view_bundle_deployWizard_selectVersion_live=Aktuelle deployte Version [{0}]
+view_bundle_deployWizard_selectVersion_select=Wählen Sie die Version aus der Liste
+view_bundle_deployWizard_title = Bundle Deployment Wizard
view_bundle_deploy_action = Aktion
view_bundle_deploy_backButton = Zurück zum Ziel
##view_bundle_deploy_clickForError = Click the icon for the error message
@@ -973,7 +979,7 @@ view_bundle_list_error3 = Konnte das Bundle nicht laden
##view_bundle_list_tagUpdateFailure = Failed to update bundle tags
##view_bundle_list_tagUpdateSuccessful = You have successfully updated the bundle tags
view_bundle_list_versionsCount = Anzahl Versionen
-##view_bundle_purge = Purge
+view_bundle_purge = Bereinigen
##view_bundle_recipe = Recipe
##view_bundle_resDeployDS_loadFailure = Failed to load bundle resource deployments
view_bundle_revert = Zurückrollen
@@ -1023,10 +1029,10 @@ view_configEdit_jumpToSection = Zum Abschnitt springen
##view_configEdit_msg_1 = Added property [{0}] to the set.
##view_configEdit_msg_2 = Removed properties from the set.
##view_configEdit_msg_3 = [{0} {1}] deleted from list.
-##view_configEdit_msg_4 = Item added to list.
+view_configEdit_msg_4 = Eintrag zur Liste hinzugefügt.
view_configEdit_properties = Eigenschaften
-##view_configEdit_tooltip_1 = Delete the selected items from the list.
-##view_configEdit_tooltip_2 = Add an item to the list.
+view_configEdit_tooltip_1 = Die ausgewählten Einträge aus der Liste löschen.
+view_configEdit_tooltip_2 = Einen Eintrag zur Liste hinzufügen.
##view_configurationDetails_allPropertiesValid = All configuration properties have valid values, so the configuration can now be saved.
view_configurationDetails_error_updateFailure = Konnte die Konfiguration nicht aktualisieren
view_configurationDetails_messageConcise = Konfiguration aktualisiert - aktuelle Version is {0}
@@ -1047,15 +1053,15 @@ view_configurationHistoryList_title = Konfigurationsänderungen
view_core_loggedOut = Ausgeloggt
view_core_noRecentAlerts = Es liegen keine frischen Alarme vor
view_core_recentAlerts = [{0}] frische Alarme
-##view_core_serverUnreachable = The server is unreachable and may be down
+view_core_serverUnreachable = Kann den Server nicht erreichen. Er abgeschaltet sein.
view_core_uncaught = Es ist eine nicht abgefangene Ausnahme aufgetreten.
view_dashboardManager_deleteFail = Konnte das Dashboard nicht löschen.
-##view_dashboardManager_deleted = Successfully deleted dashboard {0}
-##view_dashboardManager_error = Failed to save dashboard to server
-##view_dashboardManager_saved = Saved dashboard {0} to server
+view_dashboardManager_deleted = Dashboard {0} erfolgreich gelöscht
+view_dashboardManager_error = Konnte das Dashboard nicht auf dem Server sichern
+view_dashboardManager_saved = Das Dashboard {0} wurde auf dem Server geichert
view_dashboardManager_success = Dashboard gespeichert
-##view_dashboard_favorites_error1 = Failed to load favorite Resources.
-##view_dashboardsManager_error1 = Failed to add new dashboard
+view_dashboard_favorites_error1 = Konnte die Ressoucen-Lesezeichen nicht laden
+view_dashboardsManager_error1 = Konnte das neue Dashboard nicht hinzufügen
##view_dashboardsManager_message_title_details = <h1>Willkommen bei RHQ</h1>\n<p>Das RHQ-Projekt is an abstraction and plug-in based systems management suite that provides extensible and integrated systems management for multiple products and platforms across a set of core features. The project is designed with layered modules that provide a flexible architecture for deployment. It delivers a core user interface that delivers audited and historical management across an entire enterprise. A Server/Agent architecture provides remote management and plugins implement all specific support for managed products.</p>\n <p>This default dashboard can be edited by clicking the (edit mode) button above.</p>
view_dashboards_confirm1 = Sind Sie sicher, dass Sie löschen möchten
view_dashboards_title = Dashboard
@@ -1066,10 +1072,10 @@ view_dashboards_title = Dashboard
##view_drift_button_pinToTemplate_confirm = After pinning, this snapshot will be set to the initial snapshot for all definitions created using the template. If pinned to an existing template then the template''s existing definitions will be pinned to the new initial snapshot and their existing snapshots will be removed. Continue to template selection?
##view_drift_carousel_sizeFilterLabel = Snapshot Display Max
##view_drift_carousel_startFilterLabel = Snapshot Start
-##view_drift_category_fileAdded = File Added
-##view_drift_category_fileChanged = File Changed
+view_drift_category_fileAdded = Datei hinzugefügt
+view_drift_category_fileChanged = Datei geändert
##view_drift_category_fileNew = Newly Detected
-##view_drift_category_fileRemoved = File Removed
+view_drift_category_fileRemoved = Datei gelöscht
##view_drift_confirm_deleteAllDefs = Delete all drift detection definitions?
##view_drift_confirm_deleteDefs = Delete the selected drift detection definition(s)?
##view_drift_confirm_deleteTemplate = Warning! Deleting this template will also cause all attached drift definitions to be deleted as well. Those attached definitions along with all of their snapshots will be permanently removed from the system. Detached definitions will not be removed. Are you sure you want to continue?
@@ -1088,8 +1094,8 @@ view_dashboards_title = Dashboard
##view_drift_table_attached = Attached?
##view_drift_table_baseDir = Base Directory
##view_drift_table_driftHandlingMode = Drift Handling
-##view_drift_table_driftHandlingMode_normal = normal
-##view_drift_table_driftHandlingMode_plannedChanges = planned changes
+view_drift_table_driftHandlingMode_normal = normal
+view_drift_table_driftHandlingMode_plannedChanges = geplante Änderungen
##view_drift_table_hover_defNotPinned = The drift definition is not pinned Click to view the initial snapshot.
##view_drift_table_hover_defPinned = The drift definition is pinned to its initial snapshot. Click to view the initial snapshot.
##view_drift_table_hover_edit = Click to view or edit the drift definition or template properties.
@@ -1097,8 +1103,8 @@ view_dashboards_title = Dashboard
##view_drift_table_hover_outOfCompliance_noBaseDir = The base directory does not exist
##view_drift_table_hover_templateNotPinned = The drift template is not pinned to a snapshot.
##view_drift_table_hover_templatePinned = The drift template is pinned to a snapshot. Click to view the pinned snapshot.
-##view_drift_table_newFile = New File
-##view_drift_table_oldFile = Old File
+view_drift_table_newFile = Neue Datei
+view_drift_table_oldFile = Alte Datei
##view_drift_table_pinned = Pinned?
##view_drift_table_resourceDef = Resource Drift Detection Definition
##view_drift_table_resourceHistory = Resource Drift History
@@ -1138,41 +1144,65 @@ view_dashboards_title = Dashboard
##view_drift_wizard_pinTemplate_windowTitle = Pin Drift Definition Template Wizard
##view_dynagroup_children = DynaGroup Children
view_dynagroup_compatible = Kompatible
-##view_dynagroup_definitionAlreadyExists = A group definition already exists with this name
-##view_dynagroup_definitionCreated = You have successfully created a group definition named [{0}]
-##view_dynagroup_definitionLoadFailure = Failed to load group definitions
+view_dynagroup_definitionAlreadyExists=Eine Gruppendefinition mit diesem Namen besteht bereits
+view_dynagroup_definitionCreated=Sie haben erfolgreich eine Gruppendefinition mit Namen [{0}] angelegt
+view_dynagroup_definitionLoadFailure=Konnte die Gruppendefinitionen nicht laden
view_dynagroup_definitions = DynaGroup-Definitionen
-##view_dynagroup_deleteFailureSelection = Failed to delete the selected group definitions
-##view_dynagroup_deleteSuccessfulSelection = You have successfully deleted [{0}] group definitions
-##view_dynagroup_editing = Editing [{0}]
-##view_dynagroup_exprBuilder_savedExpression = Saved Expression
+view_dynagroup_deleteFailureSelection = Konnte die ausgewählten Gruppendefinitionen nicht löschen
+view_dynagroup_deleteSuccessfulSelection = Sie haben erfoglreich [{0}] Gruppendefinitionen gelöscht
+view_dynagroup_editing = Bearbeite [{0}]
+view_dynagroup_exprBuilder_addExpression=Ausdruck hinzufügen
+view_dynagroup_exprBuilder_comparisonType=Art des Vergleichs
+view_dynagroup_exprBuilder_comparisonType_contains=enthält
+view_dynagroup_exprBuilder_comparisonType_endsWith=endet mit
+view_dynagroup_exprBuilder_comparisonType_equals=ist gleich
+view_dynagroup_exprBuilder_comparisonType_startsWith=beginnt mit
+view_dynagroup_exprBuilder_comparisonType_tooltip=Art des Vergleichs
+view_dynagroup_exprBuilder_definingPlugin=Plugin
+view_dynagroup_exprBuilder_definingPlugin_tooltip=Das Plugin nach dem gesucht werden soll
+view_dynagroup_exprBuilder_expression=Ausdruck
+view_dynagroup_exprBuilder_expressionType=Art des Ausdrucks
+view_dynagroup_exprBuilder_expressionType_pluginConfig=Plugin-Konfiguration
+view_dynagroup_exprBuilder_expressionType_resource=Ressource
+view_dynagroup_exprBuilder_expressionType_resourceCategory=Ressourcen-Kategorie
+view_dynagroup_exprBuilder_expressionType_resourceConfig=Ressourcen-Konfiguration
+view_dynagroup_exprBuilder_expressionType_resourceType=Ressourcen-Typ
+view_dynagroup_exprBuilder_expressionType_trait=Trait
+view_dynagroup_exprBuilder_groupBy=Gruppieren nach
+view_dynagroup_exprBuilder_noPlugins=--Keine Plugins--
+view_dynagroup_exprBuilder_noProperties=--Keine Eigenschaften--
+view_dynagroup_exprBuilder_noResourceTypes=--Keine Ressourcen-Typen--
+view_dynagroup_exprBuilder_pluginLoadFailure=Kann die Liste der Plugins nicht laden
+view_dynagroup_exprBuilder_propLoadFailure=Kann die Liste der Eigenschaften nicht laden
+view_dynagroup_exprBuilder_propertyName=Name der Eigenschaft
+view_dynagroup_exprBuilder_savedExpression = Gespeicherter Ausdruck
view_dynagroup_expression = Ausdruck
-##view_dynagroup_expressionSet = Expression Set
+view_dynagroup_expressionSet = Ausdruck
view_dynagroup_lastCalculationTime = Zeitpunkt letzte Berechnung
-view_dynagroup_loadDefinitionFailure = Konnte die Gruppen-Definition [{0}] nicht laden
-##view_dynagroup_loadDefinitionMissing = There is no group definition with the ID of [{0}]
+view_dynagroup_loadDefinitionFailure = Konnte die Gruppendefinition [{0}] nicht laden
+view_dynagroup_loadDefinitionMissing = Es gibt keine Gruppendefinition mit id [{0}]
view_dynagroup_mixed = Gemischt
view_dynagroup_newGroupDefinition = Neue Gruppen-Definition
view_dynagroup_nextCalculationTime = Zeitpunkt nächste Berechnung
view_dynagroup_permDenied = Sie haben nicht das Recht die Gruppen Definitionen anzusehen
-##view_dynagroup_recalcFailure = Failed to recalculated this group definition
-##view_dynagroup_recalcFailureSelection = Failed to recalculated the selected group definitions
-##view_dynagroup_recalcSuccessful = You have successfully recalculated this group definition
-##view_dynagroup_recalcSuccessfulSelection = You have successfully recalculated [{0}] group definitions
+view_dynagroup_recalcFailure = Fehler beim Neuberechnen dieser Gruppendefinition
+view_dynagroup_recalcFailureSelection = Fehler beim Neuberechnen der ausgewählten Gruppendefinitionen
+view_dynagroup_recalcSuccessful = Neuberechnung der Gruppendefinitionen war erfolgreich
+view_dynagroup_recalcSuccessfulSelection = Sie haben erfolgreich [{0}] Gruppendefinitionen neu berechnet
view_dynagroup_recalculate = Neu berechnen
-##view_dynagroup_recalculationInterval = Recalculation Interval
+view_dynagroup_recalculationInterval = Intervall für die Neuberechnung
view_dynagroup_recursive = Rekursiv
view_dynagroup_saveAndRecalculate = Speichern & neu berechnen
-##view_dynagroup_saveFailure = Failed to save the group definition named [{0}]
-##view_dynagroup_saveSuccessful = You have successfully saved the group definition named [{0}]
-##view_dynagroup_singleSaveFailure = An error occurred - there should have been one created, but instead there were [{0}] created
+view_dynagroup_saveFailure = Speichern der Gruppendefiniton mit Namen [{0}] ist fehlgeschlagen
+view_dynagroup_saveSuccessful = Sie haben die Gruppendefinition mit Namen [{0}] erfolgreich gespeichert
+view_dynagroup_singleSaveFailure = Ein Fehler ist aufgetreten - es hätte eine angelegt werden sonne, anstatt wurden [{0}] angelegt
view_groupConfigEdit_member = Mitglied
##view_groupConfigEdit_noListProps = List properties are not currently supported for group configurations.
-##view_groupConfigEdit_saveReminder = You changed some settings - do not forget to save those changes or they will be lost.\n
+view_groupConfigEdit_saveReminder = Sie haben einige Werte geändert. Vergessen Sie nicht diese zu speichern damit die Änderungen nicht verloren gehen.\n
view_groupConfigEdit_setAll = Alle Werte setzen auf:
##view_groupConfigEdit_tooltip_1 = Member values differ - click icon to edit them.
view_groupConfigEdit_unset = Ungesetzt
-##view_groupConfigEdit_valsDiff = member values differ
+view_groupConfigEdit_valsDiff = Werte der Gruppenmitglieder sind unterschiedlich
##view_groupConfigEdit_valsDiffForProp = Member Values for Property [{0}]
view_groupCreateWizard_createFailure = Konnte die Ressourcen-Gruppe [{0}] nicht anlegen : {1}
view_groupCreateWizard_createStepName = Einstellungen für die Gruppe
@@ -1264,7 +1294,7 @@ view_inventory_eventHistory_sourceFilter = Filter für Quelle
##view_inventory_eventHistory_sourceLocation = Source Location
view_inventory_eventHistory_timestamp = Zeitunkt
view_inventory_groups = Gruppen
-##view_inventory_groups_children = Children
+view_inventory_groups_children = Kinder
##view_inventory_groups_deleteFailed = Failed to delete the selected resource groups
##view_inventory_groups_deleteSuccessful = You have successfully deleted the selected resource groups
##view_inventory_groups_descendants = Descendants
@@ -1386,8 +1416,8 @@ view_operationScheduleDetails_enterParametersBelow = Geben Sie die Parameter unt
view_operationScheduleDetails_field_description = Beschreibung
view_operationScheduleDetails_field_parameters = Parameter
view_operationScheduleDetails_noParameters = Diese Operation benötigt keine Parameter.
-##view_portlet_autodiscovery_config_platform_selection = Number of platforms to display
-##view_portlet_autodiscovery_help_msg = This portlet offers the ability to import newly discovered resources into the inventory for monitoring and management or to ignore them from further action.
+view_portlet_autodiscovery_config_platform_selection = Anzahl der Plattformen, die angezeigt werden sollen
+view_portlet_autodiscovery_help_msg = Dieses Portlet bietet die Möglichkeit, neu gefundene Ressourcen zum Inventar hinzuzufügen oder sie für zu ignorieren.
view_portlet_autodiscovery_title = Discovery-Warteschlange
view_portlet_defaultName_inventorySummary = Inventarübersicht
##view_portlet_defaultName_mashup = Mashup
@@ -1401,8 +1431,8 @@ view_portlet_favoriteResources_msg = Dieses Potlet zeigt Ihre gemerkten Ressourc
view_portlet_favoriteResources_title = Gemerkete Resourcen
view_portlet_generic_help = Für dieses Portlet liegt keine Hilfe vor
view_portlet_generic_unconfigured = Für dieses Portlet sind keine Einstellungen möglich
-##view_portlet_graph_configure_metricDefinition_graph = The metric definition id to graph
-##view_portlet_graph_configure_resource_graph = The resource to graph
+view_portlet_graph_configure_metricDefinition_graph = Die ID der Metrik, die dargestellt werden soll
+view_portlet_graph_configure_resource_graph = Die Ressource deren Metrik dargestellt werden soll
##view_portlet_graph_configure_title = Graph Config
##view_portlet_graph_configure_title_desc = Configuration of the graph portlet
##view_portlet_graph_help_msg = This Portlet supports the graphing of a resource metric.
@@ -1420,10 +1450,10 @@ view_portlet_inventory_tooltip_expand = Klicken, um mehr Details für diese Ress
##view_portlet_mashup_unconfigured = Page address not yet configured, click the settings button to setup this portlet.
##view_portlet_message_config_title = MessagePortlet Configuration
##view_portlet_message_config_title_desc = The configuration settings for the message portlet.
-##view_portlet_message_help = This portlet can display an HTML message on the dashboard.
+view_portlet_message_help = Dieses Portlet kann beliebige Nachrichten auf dem Dashboard darstellen.
view_portlet_message_title = Nachricht
##view_portlet_message_unconfigured = Message not yet configured, click the settings button to setup this portlet.
-##view_portlet_operations_config_completed = completed operations
+view_portlet_operations_config_completed = Fertiggestellte Operationen
##view_portlet_operations_config_completed_enable = Whether to enable completed operations results grouping for dashboard.
##view_portlet_operations_config_completed_maximum = Maximum number of Completed operations to display.
##view_portlet_operations_config_scheduled_enable = Whether to enable scheduled operations results grouping for dashboard.
@@ -1436,7 +1466,7 @@ view_portlet_operations_config_show_next = nächste anzeigen
##view_portlet_operations_help_msg = This portlet displays both operations that have occurred and are scheduled to occur.
##view_portlet_platform_help_msg = This portlet displays information about platforms in inventory.
##view_portlet_platform_platform_error_1 = Failed to load platform metrics
-##view_portlet_platform_title = Platforms Summary
+view_portlet_platform_title = Zusammenfassung der Platformen
##view_portlet_platform_type_error_1 = Could not load type data
##view_portlet_problem_resources_config_display_maximum = Maximum number of Problem resources to display.
##view_portlet_problem_resources_config_display_range = Show problem resources going back this many hours.
@@ -1444,7 +1474,7 @@ view_portlet_problem_resources_config_display_range2 = Von {0} bis {1}
##view_portlet_problem_resources_config_problem_label = problem resources on dashboard.
##view_portlet_problem_resources_config_title = ProblemResourcesPortlet Configuration
##view_portlet_problem_resources_config_title_desc = The configuration settings for the Problem resources portlet.
-##view_portlet_problem_resources_help = This portlet displays resources that have reported alerts or Down availability.
+view_portlet_problem_resources_help = Dieses Portlet zeigt Ressourcen, die nicht verfügbar sind oder für die Alarme ausgelöst wurden
view_portlet_problem_resources_title = Hat Alarme oder ist nicht verfügbar
##view_portlet_recentAlerts_config_members = Select Members
##view_portlet_recentAlerts_config_priority_label = priority Alerts,
@@ -1488,41 +1518,41 @@ view_remoteAgentInstall_stopAgent = Agent anhalten
view_reportsTop_description = Dieser Abschnitt bietet Zugang zu applikationsweiten Berichten
view_reportsTop_title = Berichte
view_reports_alertDefinitions = Alarmierungskriterien
-##view_reports_alertDefinitions_parentHover = Click to go to the parent alert definition
+view_reports_alertDefinitions_parentHover = Klicken, um zur übergeordneten Alarm-Definition zu gelangen
##view_reports_alertDefinitions_resTypeLoadError = Cannot get the template resource type - unable to view the alert template.
-##view_reports_driftCompliance = Drift Compliance
-##view_reports_inventorySummary_failFetch = Failed to get inventory summary
+view_reports_driftCompliance = Drift-Übereinstimmung
+view_reports_inventorySummary_failFetch = Konnte die Inventar-Zusammenfassung nicht laden
view_reports_platforms = Cpu- und Speicherauslastung
view_reports_subsystems = Subsysteme
##view_resourceResourceGroupList_error_fetchFailure = Failed to fetch Resource''s groups.
##view_resourceResourceGroupList_error_updateFailure = Failed to update assigned Resource groups.
##view_resourceResourceGroupList_message_updateSuccess = Group membership updated for [{0}].
-##view_resource_monitor_availability_availability = Availability
-##view_resource_monitor_availability_availability_tooltip = Percentage of time the resource has been UP compared to the times it was down and disabled
-##view_resource_monitor_availability_currentAsOf = This data is current as of {0}
-##view_resource_monitor_availability_currentStatus = Current Status
-##view_resource_monitor_availability_currentStatus_value = This resource has been {0} since {1}
-##view_resource_monitor_availability_disabled = Disabled
-##view_resource_monitor_availability_disabledTime = Disabled Time
-##view_resource_monitor_availability_disabledTime_tooltip = The cumulative amount of time the resource has been DISABLED
-##view_resource_monitor_availability_disabled_tooltip = Percentage of time the resource has been DISABLED compared to the times it was up and down
-##view_resource_monitor_availability_down = Down
-##view_resource_monitor_availability_down_tooltip = Percentage of time the resource has been DOWN compared to the times it was up and disabled
-##view_resource_monitor_availability_downtime = Downtime
-##view_resource_monitor_availability_downtime_tooltip = The cumulative amount of time the resource has been DOWN
-##view_resource_monitor_availability_loadFailed = Failed to load availability history
-##view_resource_monitor_availability_mtbf = MTBF
-##view_resource_monitor_availability_mtbf_tooltip = Mean Time Before Failure - in short, this indicates the average time spent in the UP state prior to going DOWN
-##view_resource_monitor_availability_mttr = MTTR
-##view_resource_monitor_availability_mttr_tooltip = Mean Time To Recovery - in short, this indicates the average time spent in the DOWN state prior to going UP again
-##view_resource_monitor_availability_numDisabled = Number of Times Disabled
-##view_resource_monitor_availability_numDisabled_tooltip = The total number of times this resource has entered the DISABLED state
-##view_resource_monitor_availability_numFailures = Number of Failures
-##view_resource_monitor_availability_numFailures_tooltip = The total number of times this resource has entered the DOWN state
-##view_resource_monitor_availability_summaryError = Failed to load resource availability summary
-##view_resource_monitor_availability_unknown = This resource was in an unknown state for {0}
-##view_resource_monitor_availability_uptime = Uptime
-##view_resource_monitor_availability_uptime_tooltip = The cumulative amount of time the resource has been UP
+view_resource_monitor_availability_availability = Verfügbarkeit
+view_resource_monitor_availability_availability_tooltip = Prozentsatz der Zeit in der die Ressource verfügbar war verglichen mit der Zeit in der sie nicht verfügbar war
+view_resource_monitor_availability_currentAsOf = Die angezeigten Daten sind Stand {0}
+view_resource_monitor_availability_currentStatus = Aktueller Stand
+view_resource_monitor_availability_currentStatus_value = Die Ressource ist seit {1} [{0}]
+view_resource_monitor_availability_disabled = Deaktiviert
+view_resource_monitor_availability_disabledTime = Zeit deaktiviert
+view_resource_monitor_availability_disabledTime_tooltip = Die aufsummierte Zeit in der die Ressource deaktiviert war
+view_resource_monitor_availability_disabled_tooltip = Prozentsatz der Zeit in der die Ressource deaktiviert war verglichen mit der Zeit in der sie verfügbar oder nicht verfügbar war
+view_resource_monitor_availability_down = Ncht-verfügbar
+view_resource_monitor_availability_down_tooltip = Prozentsatz der Zeit in der die Ressource nicht verfügbar war verglichen mit der Zeit in der sie verfügbar oder deaktiviert war
+view_resource_monitor_availability_downtime = Downtime
+view_resource_monitor_availability_downtime_tooltip = Die aufsummierte Zeit in der die Ressource nicht verfügbar war
+view_resource_monitor_availability_loadFailed = Konnte den Verlauf der Verfügbarkeit nicht laden
+view_resource_monitor_availability_mtbf = MTBF
+view_resource_monitor_availability_mtbf_tooltip = Mean Time Between Failure - kurz: durchschnittliche Zeit in der die Ressource verfügbar war, bevor sie unverfügbar wurde
+view_resource_monitor_availability_mttr = MTTR
+view_resource_monitor_availability_mttr_tooltip = Mean Time To Recovery - kurz: durchschnittliche Zeit in der die Ressource nicht verfügbar war, bevor sie wieder verfügbar wurde
+view_resource_monitor_availability_numDisabled = Anzahl Deaktivierungen
+view_resource_monitor_availability_numDisabled_tooltip = Summe der Deaktivierunen der Ressource (durch den Administrator)
+view_resource_monitor_availability_numFailures = Anahl Fehler
+view_resource_monitor_availability_numFailures_tooltip = Anzah der Übergäng der Ressource in den Zusatand ''unverfügbar''
+view_resource_monitor_availability_summaryError = Konnte die Zusammenfassung der Verfügbarkeit nicht laden
+view_resource_monitor_availability_unknown = Die Verfügbarkeit war für {0} unbekannt
+view_resource_monitor_availability_uptime = Uptime
+view_resource_monitor_availability_uptime_tooltip = Aufsummierte Zeit in der die Ressource verfügbar war
view_resource_monitor_calltime_average = Durchschnitt
view_resource_monitor_calltime_count = Anzahl
##view_resource_monitor_calltime_destination = Call Destination
@@ -1545,24 +1575,24 @@ view_resource_monitor_table_max = Maximum
view_resource_monitor_table_min = Minimum
view_resource_title_component_errors_tooltip = Zeigt Fehler der gemanagten Ressource. Klicken für Details
view_resource_title_tagUpdateFailed = Fehler beim Aktualisieren der Ressourcen-Tags
-##view_searchBar_defaultPattern = name your pattern
-##view_searchBar_instructional_failSuggest = Failed to generate suggestions, see server log for possible errors
-##view_searchBar_instructional_noSuggest = No matches, enter a different pattern
-##view_searchBar_instructional_refresh = Failed to retrieve saved searches, please refresh page
-##view_searchBar_savedSearch_delete = Successfully deleted saved search [{0}]
-##view_searchBar_savedSearch_failDelete = Failed to delete saved search with name [{0}]
-##view_searchBar_savedSearch_failFind = Failed to find saved search with name [{0}]
-##view_searchBar_savedSearch_failRename = Failed to rename saved search with name [{0}]
-##view_searchBar_savedSearch_failSave = Failed to create saved search with name [{0}]
-##view_searchBar_savedSearch_rename = Successfully renamed saved search to [{0}]
-##view_searchBar_savedSearch_save = Successfully created saved search [{0}]
+view_searchBar_defaultPattern = benennen Sie Ihr Suchmuster
+view_searchBar_instructional_failSuggest = Konnte keine Vorschläge generieren. Bitte schauen Sie in das Server-Log für mögliche Fehler
+view_searchBar_instructional_noSuggest = Keine Treffer. Bitte geben Sie ein anderes Suchmuster ein
+view_searchBar_instructional_refresh = Konnte die gespeicherten Suchen nicht laden. Bitte laden Sie die Seite neu
+view_searchBar_savedSearch_delete = Gespeicherte Suche [{0}] erflogreich gelöscht
+view_searchBar_savedSearch_failDelete = Konnte die gespeicherte Suche mit Namen [{0}] nicht löschen
+view_searchBar_savedSearch_failFind = Konnte die gespeicherte Suche mit Namen [{0}] nicht finden
+view_searchBar_savedSearch_failRename = Konnte die gespeicherte Suche mit Namen [{0}] nicht umbenennen
+view_searchBar_savedSearch_failSave = Konnte die gespeicherte Suche mit Namen [{0}] nicht speichern
+view_searchBar_savedSearch_rename = Die gespeicherte Suche wurde erfolgreich nach [{0}] umbenannt
+view_searchBar_savedSearch_save = Die gespeicherte Suche [{0}] wurde erfolgreich angelegt
##view_searchGUI_loginStatus = Unable to determine login status, check server status
view_selector_assigned = Zugewiesen {0}
view_selector_available = Verfügbar {0}
view_subTab_error_disabled = Kann den deaktivierten Unter-Reiter [{0}] nicht anwählen.
-##view_summaryOverviewForm_error_descriptionChangeFailure = Failed to change description of Resource with id {0} from [{1}] to [{2}].
-##view_summaryOverviewForm_error_locationChangeFailure = Failed to change location of Resource with id {0} from [{1}] to [{2}].
-##view_summaryOverviewForm_error_nameChangeFailure = Failed to change name of Resource with id {0} from [{1}] to [{2}].
+view_summaryOverviewForm_error_descriptionChangeFailure = Konnte die Beschreibung der Ressource mit der id {0} nicht von [{1}] auf [{2}] ändern.
+view_summaryOverviewForm_error_locationChangeFailure = Konnte den Ort der Ressource mit der id {0} nicht von [{1}] auf [{2}] ändern.
+view_summaryOverviewForm_error_nameChangeFailure = Konnte den Namen der Ressource mit der id {0} nicht von [{1}] auf [{2}] ändern.
view_summaryOverviewForm_error_traitsLoadFailure = Konnte die Traits für {0} nicht laden.
view_summaryOverviewForm_field_description = Beschreibung
view_summaryOverviewForm_field_location = Ort
@@ -1572,9 +1602,9 @@ view_summaryOverviewForm_field_type = Typ
view_summaryOverviewForm_field_version = Version
view_summaryOverviewForm_header_summary = Zusammenfassung
view_summaryOverviewForm_label_plugin = Plugin:
-##view_summaryOverviewForm_message_descriptionChangeSuccess = "Description of Resource with id {0} was changed from [{1}] to [{2}].
-##view_summaryOverviewForm_message_locationChangeSuccess = "Location of Resource with id {0} was changed from [{1}] to [{2}].
-##view_summaryOverviewForm_message_nameChangeSuccess = "Name of Resource with id {0} was changed from [{1}] to [{2}].
+view_summaryOverviewForm_message_descriptionChangeSuccess = "Die Beschreibung der Ressource mit der id {0} wurde von [{1}] auf [{2}] geändert.
+view_summaryOverviewForm_message_locationChangeSuccess = "Der Ort der Ressource mit der id {0} wurde von [{1}] auf [{2}] geändert.
+view_summaryOverviewForm_message_nameChangeSuccess = "Der Name der Ressource mit der id {0} wurde von [{1}] auf [{2}] geändert.
##view_summaryOverview_header_detectedErrors = Detected Errors
view_summaryOverview_title_errorDetailsWindow = Fehler-Details
view_summaryOverview_tooltip_detectedErrors = Klicken Sie auf eine Reihe, um die Fehler-Details zu sehen.
@@ -1588,8 +1618,8 @@ view_tabs_common_activity = Aktivität
view_tabs_common_agent = Agent
view_tabs_common_availability = Verfügbarkeit
##view_tabs_common_calltime = Calltime
-##view_tabs_common_child_history = Child History
-##view_tabs_common_child_resources = Child Resources
+view_tabs_common_child_history = Verlauf d. Kind-Ressourcen
+view_tabs_common_child_resources = Kind-Ressourcen
view_tabs_common_connectionSettings = Verbindungs-Einstellungen
view_tabs_common_connectionSettingsHistory = Verlauf der Verbindungs-E.
view_tabs_common_content = Inhalte
@@ -1653,7 +1683,7 @@ view_tree_common_contextMenu_pluginConfiguration = Plugin-Konfiguration
view_tree_common_contextMenu_saveChartToDashboardFailure = Speichern des Dashboards fehlgeschlagen
view_tree_common_contextMenu_saveChartToDashboardSuccessful = Sie haben das Dashboard [{0}] gesichert
view_tree_common_contextMenu_type_name_label = Typ: {0}
-##view_tree_common_loadFailed_children = Failed to load children for node
+view_tree_common_loadFailed_children = Konnte die Kinder für den Knoten nicht laden
##view_tree_common_loadFailed_create = Failed to create view for this node
##view_tree_common_loadFailed_descendants = Failed to load descendants for tree
##view_tree_common_loadFailed_generic = Failed to load data for tree
@@ -1703,21 +1733,21 @@ widget_recordEditor_warn_validation = Ein oder mehrere Felder haben ungültige W
##widget_resourceFactoryWizard_contentTemplatePrompt = Deployment Time Configuration Templates
##widget_resourceFactoryWizard_createSubmit = A request to create a resource with the name of [{0}] has been submitted successfully.
##widget_resourceFactoryWizard_createSubmitType = A request to create a resource of type [{0}] has been submitted successfully.
-##widget_resourceFactoryWizard_createWizardTitle = Create New Resource of Type [{0}]
-##widget_resourceFactoryWizard_createWizardWindowTitle = Resource Create Wizard
-##widget_resourceFactoryWizard_editConfigStepName = Deployment Options
+widget_resourceFactoryWizard_createWizardTitle = Neue Ressource vom Typ [{0}] anlegen
+widget_resourceFactoryWizard_createWizardWindowTitle = Assistent zum Erzeugen von Ressourcen
+widget_resourceFactoryWizard_editConfigStepName = Optionen für das Deployment
widget_resourceFactoryWizard_execute1 = Konnte keine neue Ressource anlegen - es wurde keien Paketversion angegeben
widget_resourceFactoryWizard_execute2 = Konnte keine neue Ressource anlegen
##widget_resourceFactoryWizard_failedToDeleteVersion = Failed to delete package version while canceling a resource create
##widget_resourceFactoryWizard_failedToGetType = Failed to get backing package type for new resource
-##widget_resourceFactoryWizard_importFailure = Failed to manually import resource
+widget_resourceFactoryWizard_importFailure = Das manuelle importieren der Ressource ist fehlgeschlagen
##widget_resourceFactoryWizard_importSubmitted = A request to import a new resource of type [{0}] has been submitted
widget_resourceFactoryWizard_importWizardTitle = Importieren von Ressourcen des Typs [{0}]
-##widget_resourceFactoryWizard_importWizardWindowTitle = Resource Import Wizard
-##widget_resourceFactoryWizard_infoStepName = Resource Information
+widget_resourceFactoryWizard_importWizardWindowTitle = Wizard zum Import von Ressourcen
+widget_resourceFactoryWizard_infoStepName = Information über die Ressource
widget_resourceFactoryWizard_infoStep_loadFail = Konnte die verfügbaren Architekturen nicht ermitteln
widget_resourceFactoryWizard_namePrompt = Name der neuen Ressource
-##widget_resourceFactoryWizard_templatePrompt = Connection Settings Template
+widget_resourceFactoryWizard_templatePrompt = Vorlage für die Verbindungseinstellungen
##widget_resourceFactoryWizard_timeoutHelp = A timeout duration. If specified will override the default timeout for child resource creation (on the RHQ Agent). Useful for particularly long create actions, like deployment of a large application. Usually used if a previous attempt suffered a timeout failure.
widget_resourceFactoryWizard_uploadFailure = Konnte die Datei nicht hochladen
##widget_resourceFactoryWizard_uploadFileStepName = Upload Resource Content File
@@ -1732,3 +1762,24 @@ widget_typeCache_loadFail = Konnte die Metadaten für den Ressourcen-Typ nicht l
widget_typeTree_badTemplateType = Ungültige URL. Unbekannter Vorlagen-Typ [{0}]
widget_typeTree_badTypeId = Ungültige URL. Unbekannte Ressource-Typ-ID [{0}]
widget_typeTree_loadFail = Konnte die Ressource-Typen nicht laden
+common_title_ancestry=Vorfahren
+common_title_change_refresh_time=Aktualisierungsintervall
+widget_colorPicker_tooltip=Klicken Sie, um eine neue Farbe auszuwählen
+widget_jobTriggerEditor_field_repeatInterval_now=Jetzt starten und alle
+widget_jobTriggerEditor_field_startType=Starten
+widget_jobTriggerEditor_message_endTimeMustBeAfterStartTime=Der Endzeitpunkt muss nach dem Startzeitpunkt liegen
+view_adminContent_contentSources=Quellen für Inhalte
+view_autoDiscoveryQ_confirmSelectAll=Auch die Kind-Ressourcen der Plattform(en) auswählen?
+view_autoDiscoveryQ_deselectAll=Auswahl für alle aufheben
+view_autoDiscoveryQ_ignoreInProgress=Die ausgewählte Ressource wird ignoriert...
+view_autoDiscoveryQ_importInProgress=Die ausgewählten Ressourcen werden in''s Inventar aufgenommen
+view_autoDiscoveryQ_selectAll=Alle auswählen
+view_bundle_deployWizard_getInfoStep=Bitte geben die Informationen zum Deployment an
+view_bundle_deployWizard_getInfo_clean=Clean Deployment? (löscht das Deploy-Verzeichnis auf der Ziel-Plattform)
+view_bundle_deployWizard_selectBundleStep=Bundle zum Deployment auswählen
+view_bundle_deployWizard_selectBundle_single=Wählen Sie nur ein einzelnes Bundle für''s Deployment aus
+view_bundle_deployWizard_selectVersionStep=Wählen Sie die Version des Bundles
+view_bundle_deploy_clickForError=Klicken Sie auf das Icon für die Fehlermeldung
+view_bundle_deploy_deleteFailure=Konnte das Bundle-Deploymment nicht löschen [{0}]
+view_bundle_deploy_deleteSuccessful=Sie haben das Bundle-Deployment [{0}] erfolgreich gelöscht
+view_configEdit_msg_1=Eigentschaft [{0}] zur Menge hinzugefügt
12 years, 1 month
[rhq] 2 commits - modules/plugins
by ips
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ASConnection.java | 77 ++++++----
modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableDiscoveryComponent.java | 2
modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresUserDiscoveryComponent.java | 4
3 files changed, 54 insertions(+), 29 deletions(-)
New commits:
commit 559098b15019378432d8ad0be83ab6dbbc490be9
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Mar 29 00:06:18 2012 -0400
turn down logging a bit and fix an incorrect log category name
diff --git a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableDiscoveryComponent.java b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableDiscoveryComponent.java
index f43e14d..3114a60 100644
--- a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableDiscoveryComponent.java
+++ b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresTableDiscoveryComponent.java
@@ -43,7 +43,7 @@ public class PostgresTableDiscoveryComponent implements ResourceDiscoveryCompone
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<PostgresDatabaseComponent> context)
throws Exception {
- log.debug("Discovering postgres tables for " + context.getParentResourceComponent().getDatabaseName());
+ log.debug("Discovering postgres tables for " + context.getParentResourceComponent().getDatabaseName() + "...");
Set<DiscoveredResourceDetails> discoveredTables = new HashSet<DiscoveredResourceDetails>();
Connection connection = context.getParentResourceComponent().getConnection();
diff --git a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresUserDiscoveryComponent.java b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresUserDiscoveryComponent.java
index 4eab143..9c7ae80 100644
--- a/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresUserDiscoveryComponent.java
+++ b/modules/plugins/postgres/src/main/java/org/rhq/plugins/postgres/PostgresUserDiscoveryComponent.java
@@ -39,13 +39,13 @@ import org.rhq.core.util.jdbc.JDBCUtil;
* @author Greg Hinkle
*/
public class PostgresUserDiscoveryComponent implements ResourceDiscoveryComponent<PostgresServerComponent<?>> {
- private static final Log log = LogFactory.getLog(PostgresTableDiscoveryComponent.class);
+ private static final Log log = LogFactory.getLog(PostgresUserDiscoveryComponent.class);
public static final String USERS_QUERY = "select * from pg_roles";
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<PostgresServerComponent<?>> context)
throws Exception {
- log.info("Discovering postgres users");
+ log.debug("Discovering postgres users for " + context.getParentResourceComponent().getJDBCUrl() + "...");
Set<DiscoveredResourceDetails> discoveredUsers = new HashSet<DiscoveredResourceDetails>();
Connection connection = context.getParentResourceComponent().getConnection();
commit c0d34a62c73dcee84350fb98a2babb9214658014
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Thu Mar 29 00:05:34 2012 -0400
log failures to connect to the management URL at DEBUG, rather than ERROR, level
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 1d6050a..5c1356a 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
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2011 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -43,26 +43,32 @@ import org.rhq.modules.plugins.jbossas7.json.Operation;
import org.rhq.modules.plugins.jbossas7.json.Result;
/**
- * Provide connections to the AS and reading / writing date from/to it.
+ * Provide management connections to an AS7 instance and reading/writing data from/to it.
+ *
* @author Heiko W. Rupp
*/
public class ASConnection {
public static final String MANAGEMENT = "/management";
+ private static final String FAILURE_DESCRIPTION = "\"failure-description\"";
+ private static final String INCLUDE_DEFAULT = "include-defaults";
+
+ // This is a variable on purpose, so devs can switch it on in the debugger or in the agent
+ public static boolean verbose = false;
+
private final Log log = LogFactory.getLog(ASConnection.class);
- URL url;
- String urlString;
+
+ private URL url;
+ private String urlString;
private ObjectMapper mapper;
- public static boolean verbose = false; // This is a variable on purpose, so devs can switch it on in the debugger or in the agent
- Authenticator passwordAuthenticator;
+ private Authenticator passwordAuthenticator;
private String host;
private int port;
- private String FAILURE_DESCRIPTION = "\"failure-description\"";
- private String INCLUDE_DEFAULT = "include-defaults";
/**
* Construct an ASConnection object. The real "physical" connection is done in
- * #executeRaw.
+ * {@link #executeRaw(Operation)}.
+ *
* @param host Host of the DomainController or standalone server
* @param port Port of the JSON api.
* @param user user needed for authentication
@@ -116,34 +122,56 @@ public class ASConnection {
* real work by talking to the remote server and sending JSON data, that
* is obtained by serializing the operation.
*
- * Please do not use this API , but execute()
- * @return JsonNode that describes the result
+ * Please do not use this API, but rather use {@link #execute(Operation)}.
+ *
* @param operation an Operation that should be run on the domain controller
* @param timeoutSec Timeout on connect and read in seconds
+ *
+ * @return JsonNode that describes the result
+ *
* @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation)
* @see #execute(org.rhq.modules.plugins.jbossas7.json.Operation, boolean)
* @see #executeComplex(org.rhq.modules.plugins.jbossas7.json.Operation)
*/
public JsonNode executeRaw(Operation operation, int timeoutSec) {
- InputStream inputStream;
- BufferedReader br = null;
- InputStream es = null;
- HttpURLConnection conn = null;
long t1 = System.currentTimeMillis();
+
+ HttpURLConnection conn;
+ OutputStream out;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.addRequestProperty("Content-Type", "application/json");
conn.addRequestProperty("Accept", "application/json");
- conn.setConnectTimeout(timeoutSec * 1000); // 10s
- conn.setReadTimeout(timeoutSec * 1000); // 10s
+ int timeoutMillis = timeoutSec * 1000;
+ conn.setConnectTimeout(timeoutMillis);
+ conn.setReadTimeout(timeoutMillis);
- if (conn.getReadTimeout() != 10 * 1000)
- log.warn("JRE uses a broken timeout mechanism - nothing we can do");
+ if (conn.getReadTimeout() != timeoutMillis) {
+ log.warn("The JRE uses a broken timeout mechanism - nothing we can do.");
+ }
- OutputStream out = conn.getOutputStream();
+ out = conn.getOutputStream();
+ } catch (IOException e) {
+ // This most likely just means the server is down.
+ if (log.isDebugEnabled()) {
+ log.debug("Failed to open connection to [" + urlString + "] in order to invoke [" + operation + "]: "
+ + e);
+ }
+ // TODO (ips): Would it make more sense to return null here, since we didn't even connect?
+ Result failure = new Result();
+ failure.setFailureDescription(e.getMessage());
+ failure.setOutcome("failure");
+ failure.setRhqThrowable(e);
+ JsonNode ret = mapper.valueToTree(failure);
+ return ret;
+ }
+ InputStream inputStream;
+ BufferedReader br = null;
+ InputStream es = null;
+ try {
//add additional request property to include-defaults=true to all requests.
//if it's already set we leave it alone and assume that Operation creator is taking over control.
if (operation.getAdditionalProperties().isEmpty()
@@ -159,7 +187,7 @@ public class ASConnection {
if (containsSpaces(operation.getAddress().getPath())) {
Result noResult = new Result();
String outcome = "- Path '" + operation.getAddress().getPath()
- + "' in invalid as it cannot contain spaces -";
+ + "' is invalid as it contains spaces -";
if (verbose) {
log.error(outcome);
}
@@ -187,7 +215,6 @@ public class ASConnection {
}
if (inputStream != null) {
-
br = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder builder = new StringBuilder();
@@ -230,8 +257,7 @@ public class ASConnection {
}
}
} catch (IllegalArgumentException iae) {
- log.error("Illegal argument " + iae);
- log.error(" for input " + operation);
+ log.error("Illegal argument " + iae + "\n\t for input " + operation);
} catch (SocketTimeoutException ste) {
log.error("Request to AS timed out " + ste.getMessage());
conn.disconnect();
@@ -242,7 +268,6 @@ public class ASConnection {
JsonNode ret = mapper.valueToTree(failure);
return ret;
-
} catch (IOException e) {
log.error("Failed to get data: " + e.getMessage());
@@ -387,7 +412,6 @@ public class ASConnection {
}
Result res;
try {
-
//check for failure-description indicator, otherwise ObjectMapper will try to deserialize as json. Ex.
// {"outcome":"failed","failure-description":"JBAS014792: Unknown attribute number-of-timed-out-transactions","rolled-back":true}
String as7ResultSerialization = node.toString();
@@ -425,4 +449,5 @@ public class ASConnection {
public int getPort() {
return port;
}
+
}
12 years, 1 month
[rhq] 2 commits - modules/plugins
by snegrea
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadDelegate.java | 11
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationWriteDelegate.java | 27
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 64 +-
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadingTest.java | 58 +
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationUpdatingTest.java | 315 +++++-----
modules/plugins/jboss-as-7/src/test/resources/groupedproperties.json | 24
modules/plugins/jboss-as-7/src/test/resources/test-plugin.xml | 29
7 files changed, 371 insertions(+), 157 deletions(-)
New commits:
commit f58db1a1406ee2e0db86698a55912c9ac6c2172c
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Wed Mar 28 20:52:55 2012 -0500
Preliminary support for cmp subsystem.
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 3bc4694..8436761 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
@@ -2808,4 +2808,36 @@ working area for individual server instances</li></ul>"/>
</service>
+ <service name="CMP"
+ class="BaseComponent"
+ discovery="SubsystemDiscovery"
+ description="The configuration of the cmp subsystem."
+ singleton="true">
+
+ <runs-inside>
+ <parent-resource-type name="Profile" plugin="jboss-as-7"/>
+ <parent-resource-type name="JBossAS7 Standalone Server" plugin="jboss-as-7"/>
+ </runs-inside>
+
+ <plugin-configuration>
+ <c:simple-property name="path" default="subsystem=cmp" readOnly="true"/>
+ </plugin-configuration>
+
+ <resource-configuration>
+ <c:group name="child:hilo-keygenerator=hilo-keygenerator" displayName="HiLo based key generators.">
+ <c:simple-property name="block-size" required="false" type="long" readOnly="true" description="The block size"/>
+ <c:simple-property name="create-table" required="false" type="boolean" readOnly="true" description="Boolean to determine whether to create create the tables"/>
+ <c:simple-property name="create-table-ddl" required="false" type="string" readOnly="true" description="The DDL used to create the table"/>
+ <c:simple-property name="data-source" required="false" type="string" readOnly="true" description="The datasource used for sequence generation"/>
+ <c:simple-property name="drop-table" required="false" type="boolean" readOnly="true" description="Boolean to determine whether to create drop the tables"/>
+ <c:simple-property name="id-column" required="false" type="string" readOnly="true" description="The ID column name"/>
+ <c:simple-property name="select-hi-ddl" required="false" type="string" readOnly="true" description="The DDL used to select the hi value"/>
+ <c:simple-property name="sequence-column" required="false" type="string" readOnly="true" description="The sequence column name"/>
+ <c:simple-property name="sequence-name" required="false" type="string" readOnly="true" description="The name of the sequence"/>
+ <c:simple-property name="table-name" required="false" type="string" readOnly="true" description="The table name"/>
+ </c:group>
+ </resource-configuration>
+
+ </service>
+
</plugin>
commit fa0d3329874e5887557df4afafcdd8d82cd99bc6
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Wed Mar 28 18:05:40 2012 -0500
Add support for singleton subsystems with identically named properties to be configured from the grouped properties section of the main resource.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadDelegate.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadDelegate.java
index 9965e9c..a1cde65 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadDelegate.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadDelegate.java
@@ -206,6 +206,17 @@ public class ConfigurationLoadDelegate implements ConfigurationFacet {
} else { // standard case
Object valueObject;
+
+ //strip :number from properties
+ if (propertyName.contains(":")) {
+ try {
+ Integer.parseInt(propertyName.substring(propertyName.lastIndexOf(':') + 1));
+ propertyName = propertyName.substring(0, propertyName.lastIndexOf(':'));
+ } catch (Exception e) {
+ //do nothing, this means the property name does not end with :number, so nothing needs to be stripped
+ }
+ }
+
if (propertyName.endsWith(":expr") || propertyName.endsWith(":collapsed")) {
String realName = propertyName.substring(0, propertyName.indexOf(":"));
valueObject = results.get(realName);
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationWriteDelegate.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationWriteDelegate.java
index fad0128..0d39fd1 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationWriteDelegate.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ConfigurationWriteDelegate.java
@@ -240,12 +240,11 @@ public class ConfigurationWriteDelegate implements ConfigurationFacet {
}
}
- private void updateHandlePropertyMap(CompositeOperation cop, PropertyMap prop, PropertyDefinitionMap propDef,
- Address address) {
-
- String propName = prop.getName();
+ private void updateHandlePropertyMap(CompositeOperation cop, PropertyMap prop, PropertyDefinitionMap propDef, Address address) {
Operation writeAttribute;
Map<String,Object> results;
+
+ String propName = stripNumberIdentifier(prop.getName());
if (propName.endsWith(":collapsed")) {
String realName = propName.substring(0, propName.indexOf(':'));
results = handleCollapsedMap(prop, propDef);
@@ -386,7 +385,9 @@ public class ConfigurationWriteDelegate implements ConfigurationFacet {
values.add(mapResult);
}
}
- Operation writeAttribute = new WriteAttribute(address,prop.getName(),values);
+
+ String name = stripNumberIdentifier(prop.getName());
+ Operation writeAttribute = new WriteAttribute(address,name,values);
cop.addStep(writeAttribute);
}
@@ -399,7 +400,7 @@ public class ConfigurationWriteDelegate implements ConfigurationFacet {
return;
Operation writeAttribute = new WriteAttribute(address);
- String name = propertySimple.getName();
+ String name = stripNumberIdentifier(propertySimple.getName());
if (name.endsWith(":expr")) {
String realName = name.substring(0,name.indexOf(":"));
@@ -482,5 +483,17 @@ public class ConfigurationWriteDelegate implements ConfigurationFacet {
return ret;
}
-
+ private String stripNumberIdentifier(String name) {
+ //strip :number from the property name, it's not needed
+ //it was added in the descriptor as unique identifier
+ if (name.contains(":")) {
+ try {
+ Integer.parseInt(name.substring(name.lastIndexOf(':') + 1));
+ name = name.substring(0, name.lastIndexOf(':'));
+ } catch (Exception e) {
+ //do nothing, this means the property name does not end with :number, so nothing needs to be stripped
+ }
+ }
+ return name;
+ }
}
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 1d85bff..3bc4694 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
@@ -2694,10 +2694,10 @@ working area for individual server instances</li></ul>"/>
<resource-configuration>
<c:group name="child:bean-validation=bean-validation" displayName="Bean validation (JSR-303) for resource adapters.">
- <c:simple-property name="enabled" required="false" type="boolean" readOnly="false" defaultValue="true" description="Specify whether bean validation is enabled. The default value is true."/>
+ <c:simple-property name="enabled:1" required="false" type="boolean" readOnly="false" defaultValue="true" displayName="Enabled" description="Specify whether bean validation is enabled. The default value is true."/>
</c:group>
<c:group name="child:archive-validation=archive-validation" displayName="Archive validation for resource adapters.">
- <c:simple-property name="enabled" required="false" type="boolean" readOnly="false" defaultValue="true" description="Specify whether archive validation is enabled. The default value is true."/>
+ <c:simple-property name="enabled:2" required="false" type="boolean" readOnly="false" defaultValue="true" displayName="Enabled" description="Specify whether archive validation is enabled. The default value is true."/>
<c:simple-property name="fail-on-error" required="false" type="boolean" readOnly="false" defaultValue="true" description="Should an archive validation error report fail the deployment. The default value is true."/>
<c:simple-property name="fail-on-warn" required="false" type="boolean" readOnly="false" defaultValue="false" description="Should an archive validation warning report fail the deployment. The default value is false."/>
</c:group>
@@ -2736,28 +2736,28 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="name" required="false" type="string" readOnly="false" description="The name of the WorkManager"/>
<c:group name="child:long-running-threads=default-long-running-threads" displayName="Long running thread pool executor with a bounded queue where threads submittings tasks may block.">
- <c:simple-property name="allow-core-timeout" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether core threads may time out. The default value is false."/>
- <c:simple-property name="core-threads:expr" required="false" type="string" readOnly="false" description="The core thread pool size which is smaller than the maximum pool size. If undefined, the core thread pool size is the same as the maximum thread pool size."/>
- <c:map-property name="keepalive-time" description="Used to specify the amount of time that pool threads should be kept running when idle; if not specified, threads will run until the executor is shut down." >
+ <c:simple-property name="allow-core-timeout:1" required="false" type="boolean" readOnly="false" defaultValue="false" displayName="Allow Core Timeout" description="Whether core threads may time out. The default value is false."/>
+ <c:simple-property name="core-threads:expr:2" required="false" type="string" readOnly="false" displayName="Core Threads" description="The core thread pool size which is smaller than the maximum pool size. If undefined, the core thread pool size is the same as the maximum thread pool size."/>
+ <c:map-property name="keepalive-time:3" displayName="Keepalive Time" description="Used to specify the amount of time that pool threads should be kept running when idle; if not specified, threads will run until the executor is shut down." >
<c:simple-property name="time" required="true" type="long" readOnly="true" description="The time"/>
<c:simple-property name="unit" required="true" type="string" readOnly="true" description="The time unit"/>
</c:map-property>
- <c:simple-property name="max-threads:expr" required="false" type="string" readOnly="false" description="The maximum thread pool size."/>
- <c:simple-property name="name" required="false" type="string" readOnly="true" description="The name of the thread pool."/>
- <c:simple-property name="queue-length:expr" required="false" type="string" readOnly="false" description="The queue length."/>
- <c:simple-property name="thread-factory" required="false" type="string" readOnly="false" description="Specifies the name of a specific thread factory to use to create worker threads. If not defined an appropriate default thread factory will be used."/>
+ <c:simple-property name="max-threads:expr:4" required="false" type="string" readOnly="false" displayName="Max Threads" description="The maximum thread pool size."/>
+ <c:simple-property name="name:5" required="false" type="string" readOnly="true" displayName="Name" description="The name of the thread pool."/>
+ <c:simple-property name="queue-length:expr:6" required="false" type="string" readOnly="false" displayName="Queue Length" description="The queue length."/>
+ <c:simple-property name="thread-factory:7" required="false" type="string" readOnly="false" displayName="Thread Factory" description="Specifies the name of a specific thread factory to use to create worker threads. If not defined an appropriate default thread factory will be used."/>
</c:group>
<c:group name="child:short-running-threads=default-short-running-threads" displayName="Short running thread pool executor with a bounded queue where threads submittings tasks may block.">
- <c:simple-property name="allow-core-timeout" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether core threads may time out. The default value is false."/>
- <c:simple-property name="core-threads:expr" required="false" type="string" readOnly="false" description="The core thread pool size which is smaller than the maximum pool size. If undefined, the core thread pool size is the same as the maximum thread pool size."/>
- <c:map-property name="keepalive-time" description="Used to specify the amount of time that pool threads should be kept running when idle; if not specified, threads will run until the executor is shut down." >
+ <c:simple-property name="allow-core-timeout:8" required="false" type="boolean" readOnly="false" defaultValue="false" displayName="Allow Core Timeout" description="Whether core threads may time out. The default value is false."/>
+ <c:simple-property name="core-threads:expr:9" required="false" type="string" readOnly="false" displayName="Core Threads" description="The core thread pool size which is smaller than the maximum pool size. If undefined, the core thread pool size is the same as the maximum thread pool size."/>
+ <c:map-property name="keepalive-time:10" displayName="Keepalive Time" description="Used to specify the amount of time that pool threads should be kept running when idle; if not specified, threads will run until the executor is shut down." >
<c:simple-property name="time" required="true" type="long" readOnly="true" description="The time"/>
<c:simple-property name="unit" required="true" type="string" readOnly="true" description="The time unit"/>
</c:map-property>
- <c:simple-property name="max-threads:expr" required="false" type="string" readOnly="false" description="The maximum thread pool size."/>
- <c:simple-property name="name" required="false" type="string" readOnly="true" description="The name of the thread pool."/>
- <c:simple-property name="queue-length:expr" required="false" type="string" readOnly="false" description="The queue length."/>
- <c:simple-property name="thread-factory" required="false" type="string" readOnly="false" description="Specifies the name of a specific thread factory to use to create worker threads. If not defined an appropriate default thread factory will be used."/>
+ <c:simple-property name="max-threads:expr:11" required="false" type="string" readOnly="false" displayName="Max Threads" description="The maximum thread pool size."/>
+ <c:simple-property name="name:12" required="false" type="string" readOnly="true" displayName="Name" description="The name of the thread pool."/>
+ <c:simple-property name="queue-length:expr:13" required="false" type="string" readOnly="false" displayName="Queue Length" description="The queue length."/>
+ <c:simple-property name="thread-factory:14" required="false" type="string" readOnly="false" displayName="Thread Factory" description="Specifies the name of a specific thread factory to use to create worker threads. If not defined an appropriate default thread factory will be used."/>
</c:group>
</resource-configuration>
</service>
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadingTest.java
index c9caba4..171a6c7 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadingTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationLoadingTest.java
@@ -525,4 +525,60 @@ public class ConfigurationLoadingTest extends AbstractConfigurationHandlingTest
index++;
}
}
-}
+
+ public void testGroupedPropertiesWithIdenticalNames() throws Exception {
+ String resultString = loadJsonFromFile("groupedproperties.json");
+
+ ConfigurationDefinition definition = loadDescriptor("groupedproperties");
+
+ ObjectMapper mapper = new ObjectMapper();
+ ComplexResult result = mapper.readValue(resultString, ComplexResult.class);
+ JsonNode json = mapper.valueToTree(result);
+
+ FakeConnection connection = new FakeConnection();
+ connection.setContent(json);
+
+ ConfigurationLoadDelegate delegate = new ConfigurationLoadDelegate(definition, connection, null);
+ Configuration config = delegate.loadResourceConfiguration();
+ Collection<Property> properties = config.getProperties();
+
+ Assert.assertEquals(properties.size(), 6);
+
+ for (int index = 1; index < 5; index += 3) {
+ String stringValue = index + "" + (index + 1) + "" + (index + 2);
+
+ String firstPropName = "firstprop:" + index;
+ boolean firstPropFound = false;
+ String secondPropName = "secondprop:" + (index + 1);
+ boolean secondPropFound = false;
+ String thirdPropName = "thirdprop:" + (index + 2);
+ boolean thirdPropFound = false;
+
+ for (Property property : properties) {
+ if (property.getName().equals(firstPropName)) {
+ firstPropFound = true;
+ Assert.assertEquals(((PropertySimple) property).getStringValue(), stringValue);
+ } else if (property.getName().equals(secondPropName)) {
+ secondPropFound = true;
+ PropertyList list = (PropertyList) property;
+ Assert.assertEquals(list.getList().size(), 3);
+ for (int i = 0; i < 3; i++) {
+ PropertySimple simpleProperty = (PropertySimple) list.getList().get(i);
+ String expectedValue = "test" + (i + index);
+ Assert.assertEquals(simpleProperty.getStringValue(), expectedValue);
+ }
+ } else if (property.getName().equals(thirdPropName)) {
+ thirdPropFound = true;
+ PropertyMap map = (PropertyMap) property;
+ Assert.assertEquals(map.getMap().size(), 1);
+ String actualValue = ((PropertySimple) (map.get("value"))).getStringValue();
+ Assert.assertEquals(actualValue, stringValue);
+ }
+ }
+
+ Assert.assertTrue(firstPropFound);
+ Assert.assertTrue(secondPropFound);
+ Assert.assertTrue(thirdPropFound);
+ }
+ }
+}
\ No newline at end of file
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationUpdatingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationUpdatingTest.java
index 75967bb..2fffee5 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationUpdatingTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/ConfigurationUpdatingTest.java
@@ -45,7 +45,8 @@ import org.rhq.modules.plugins.jbossas7.json.Operation;
@Test(groups = "unit")
public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest {
- ObjectMapper mapper ;
+ ObjectMapper mapper;
+
@BeforeSuite
void loadPluginDescriptor() throws Exception {
super.loadPluginDescriptor();
@@ -60,20 +61,19 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- conf.put(new PropertySimple("needed","test"));
- conf.put(new PropertySimple("optional",null));
+ conf.put(new PropertySimple("needed", "test"));
+ conf.put(new PropertySimple("optional", null));
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
assert cop.numberOfSteps() == 1;
Operation step1 = cop.step(0);
assert step1.getOperation().equals("write-attribute");
- Map<String,Object> props = step1.getAdditionalProperties();
- assert props.size()==2;
-
+ Map<String, Object> props = step1.getAdditionalProperties();
+ assert props.size() == 2;
}
@@ -83,13 +83,11 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- PropertyList propertyList = new PropertyList("foo",
- new PropertySimple("optional","Hello"),
- new PropertySimple("optional",null),
- new PropertySimple("optional","world"));
+ PropertyList propertyList = new PropertyList("foo", new PropertySimple("optional", "Hello"),
+ new PropertySimple("optional", null), new PropertySimple("optional", "world"));
conf.put(propertyList);
@@ -98,12 +96,10 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
assert cop.numberOfSteps() == 1 : "#Steps should be 1 but were " + cop.numberOfSteps();
Operation step1 = cop.step(0);
assert step1.getOperation().equals("write-attribute");
- Map<String,Object> props = step1.getAdditionalProperties();
- assert props.size()==2;
+ Map<String, Object> props = step1.getAdditionalProperties();
+ assert props.size() == 2;
List<String> values = (List<String>) props.get("value");
- assert values.size()==2 : "Values had "+ values.size() + " entries"; // The optional null must not be present
-
-
+ assert values.size() == 2 : "Values had " + values.size() + " entries"; // The optional null must not be present
String result = mapper.writeValueAsString(cop);
@@ -115,12 +111,11 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- PropertyMap propertyMap = new PropertyMap("foo",
- new PropertySimple("needed","Hello"),
- new PropertySimple("optional","world"));
+ PropertyMap propertyMap = new PropertyMap("foo", new PropertySimple("needed", "Hello"), new PropertySimple(
+ "optional", "world"));
conf.put(propertyMap);
@@ -129,26 +124,26 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
assert cop.numberOfSteps() == 1 : "#Steps should be 1 but were " + cop.numberOfSteps();
Operation step1 = cop.step(0);
assert step1.getOperation().equals("write-attribute");
- Map<String,Object> props = step1.getAdditionalProperties();
- assert props.size()==2;
- Map<String,Object> values = (Map<String,Object>) props.get("value");
- assert values.size()==2 : "Values had "+ values.size() + " entries instead of 2"; // The optional null must not be present
+ Map<String, Object> props = step1.getAdditionalProperties();
+ assert props.size() == 2;
+ Map<String, Object> values = (Map<String, Object>) props.get("value");
+ assert values.size() == 2 : "Values had " + values.size() + " entries instead of 2"; // The optional null must not be present
String result = mapper.writeValueAsString(cop);
}
+
public void test4() throws Exception {
ConfigurationDefinition definition = loadDescriptor("mapOfSimple1");
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- PropertyMap propertyMap = new PropertyMap("foo",
- new PropertySimple("needed","Hello"),
- new PropertySimple("readOnly","world"));
+ PropertyMap propertyMap = new PropertyMap("foo", new PropertySimple("needed", "Hello"), new PropertySimple(
+ "readOnly", "world"));
conf.put(propertyMap);
@@ -157,10 +152,10 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
assert cop.numberOfSteps() == 1 : "#Steps should be 1 but were " + cop.numberOfSteps();
Operation step1 = cop.step(0);
assert step1.getOperation().equals("write-attribute");
- Map<String,Object> props = step1.getAdditionalProperties();
- assert props.size()==2;
- Map<String,Object> values = (Map<String,Object>) props.get("value");
- assert values.size()==1 : "Values had "+ values.size() + " entries instead of 1"; // The optional null must not be present
+ Map<String, Object> props = step1.getAdditionalProperties();
+ assert props.size() == 2;
+ Map<String, Object> values = (Map<String, Object>) props.get("value");
+ assert values.size() == 1 : "Values had " + values.size() + " entries instead of 1"; // The optional null must not be present
String result = mapper.writeValueAsString(cop);
@@ -172,11 +167,10 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- PropertyMap propertyMap = new PropertyMap("foo",
- new PropertySimple("needed","Hello"));
+ PropertyMap propertyMap = new PropertyMap("foo", new PropertySimple("needed", "Hello"));
conf.put(propertyMap);
@@ -185,10 +179,10 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
assert cop.numberOfSteps() == 1 : "#Steps should be 1 but were " + cop.numberOfSteps();
Operation step1 = cop.step(0);
assert step1.getOperation().equals("write-attribute");
- Map<String,Object> props = step1.getAdditionalProperties();
- assert props.size()==2;
- Map<String,Object> values = (Map<String,Object>) props.get("value");
- assert values.size()==1 : "Values had "+ values.size() + " entries instead of 1"; // The optional null must not be present
+ Map<String, Object> props = step1.getAdditionalProperties();
+ assert props.size() == 2;
+ Map<String, Object> values = (Map<String, Object>) props.get("value");
+ assert values.size() == 1 : "Values had " + values.size() + " entries instead of 1"; // The optional null must not be present
String result = mapper.writeValueAsString(cop);
@@ -200,14 +194,13 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- PropertyMap propertyMap = new PropertyMap("theMap",
- new PropertySimple("needed","Hello"),
- new PropertySimple("optional","World"));
+ PropertyMap propertyMap = new PropertyMap("theMap", new PropertySimple("needed", "Hello"), new PropertySimple(
+ "optional", "World"));
- PropertyList propertyList = new PropertyList("foo",propertyMap);
+ PropertyList propertyList = new PropertyList("foo", propertyMap);
conf.put(propertyList);
@@ -216,12 +209,12 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
assert cop.numberOfSteps() == 1 : "#Steps should be 1 but were " + cop.numberOfSteps();
Operation step1 = cop.step(0);
assert step1.getOperation().equals("write-attribute");
- Map<String,Object> props = step1.getAdditionalProperties();
- assert props.size()==2;
- List<Map<String,Object>> values = (List<Map<String, Object>>) props.get("value");
- assert values.size()==1 : "Values had "+ values.size() + " entries instead of 1"; // The optional null must not be present
- Map<String,Object> map = values.get(0);
- assert map.size()==2 : "Map had " + map.size() + " entries instead of two";
+ Map<String, Object> props = step1.getAdditionalProperties();
+ assert props.size() == 2;
+ List<Map<String, Object>> values = (List<Map<String, Object>>) props.get("value");
+ assert values.size() == 1 : "Values had " + values.size() + " entries instead of 1"; // The optional null must not be present
+ Map<String, Object> map = values.get(0);
+ assert map.size() == 2 : "Map had " + map.size() + " entries instead of two";
String result = mapper.writeValueAsString(cop);
@@ -232,17 +225,17 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
PropertyMap propertyMap = new PropertyMap("http");
- propertyMap.put(new PropertySimple("name","http"));
- propertyMap.put(new PropertySimple("port",18080));
- propertyMap.put(new PropertySimple("fixed-port",false));
+ propertyMap.put(new PropertySimple("name", "http"));
+ propertyMap.put(new PropertySimple("port", 18080));
+ propertyMap.put(new PropertySimple("fixed-port", false));
PropertyList propertyList = new PropertyList("*");
propertyList.add(propertyMap);
conf.put(propertyList);
- conf.put(new PropertySimple("port-offset",0));
+ conf.put(new PropertySimple("port-offset", 0));
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
@@ -253,23 +246,23 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
// As we do not specify a base address when creating the delegate 0 or 1 address element is ok.
assert step1.getAddress().isEmpty();
- assert step2.getAddress().size()==1;
- assert step3.getAddress().size()==1;
+ assert step2.getAddress().size() == 1;
+ assert step3.getAddress().size() == 1;
assert step1.getAdditionalProperties().get("name").equals("port-offset");
assert step1.getAdditionalProperties().get("value").equals("0");
assert step2.getAdditionalProperties().get("name").equals("port");
Object value = step2.getAdditionalProperties().get("value");
- assert value !=null;
+ assert value != null;
assert value instanceof Integer;
- assert (Integer)value == 18080;
+ assert (Integer) value == 18080;
assert step3.getAdditionalProperties().get("name").equals("fixed-port");
Object value1 = step3.getAdditionalProperties().get("value");
- assert value1 !=null;
+ assert value1 != null;
assert value1 instanceof Boolean;
- assert !(Boolean)value1;
+ assert !(Boolean) value1;
assert step2.getAddress().get(0).equals("socket-binding=http");
assert step3.getAddress().get(0).equals("socket-binding=http");
@@ -280,24 +273,24 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
PropertyList propertyList = new PropertyList("*");
PropertyMap propertyMap = new PropertyMap("binding");
- propertyMap.put(new PropertySimple("name","http"));
- propertyMap.put(new PropertySimple("port",18080));
- propertyMap.put(new PropertySimple("fixed-port",false));
+ propertyMap.put(new PropertySimple("name", "http"));
+ propertyMap.put(new PropertySimple("port", 18080));
+ propertyMap.put(new PropertySimple("fixed-port", false));
propertyList.add(propertyMap);
propertyMap = new PropertyMap("binding");
- propertyMap.put(new PropertySimple("name","https"));
- propertyMap.put(new PropertySimple("port",18081));
- propertyMap.put(new PropertySimple("fixed-port",false));
+ propertyMap.put(new PropertySimple("name", "https"));
+ propertyMap.put(new PropertySimple("port", 18081));
+ propertyMap.put(new PropertySimple("fixed-port", false));
propertyList.add(propertyMap);
conf.put(propertyList);
- conf.put(new PropertySimple("port-offset",0));
+ conf.put(new PropertySimple("port-offset", 0));
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
@@ -310,24 +303,23 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
// As we do not specify a base address when creating the delegate 0 or 1 address element is ok.
assert step1.getAddress().isEmpty();
- assert step2.getAddress().size()==1;
- assert step3.getAddress().size()==1;
+ assert step2.getAddress().size() == 1;
+ assert step3.getAddress().size() == 1;
assert step1.getAdditionalProperties().get("name").equals("port-offset");
assert step1.getAdditionalProperties().get("value").equals("0");
assert step2.getAdditionalProperties().get("name").equals("port");
Object value = step2.getAdditionalProperties().get("value");
- assert value !=null;
+ assert value != null;
assert value instanceof Integer;
- assert (Integer)value == 18080;
-
+ assert (Integer) value == 18080;
assert step3.getAdditionalProperties().get("name").equals("fixed-port");
Object value1 = step3.getAdditionalProperties().get("value");
- assert value1 !=null;
+ assert value1 != null;
assert value1 instanceof Boolean;
- assert !(Boolean)value1;
+ assert !(Boolean) value1;
assert step2.getAddress().get(0).equals("socket-binding=http");
assert step3.getAddress().get(0).equals("socket-binding=http");
@@ -341,16 +333,16 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
FakeConnection connection = new FakeConnection();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- conf.put(new PropertySimple("default-virtual-server","hulla")); // this is read-only and must not show up in result
- conf.put(new PropertySimple("test-prop","Heiko"));
- conf.put(new PropertySimple("check-interval",23));
- conf.put(new PropertySimple("disabled",true));
- conf.put(new PropertySimple("listings",false));
- conf.put(new PropertySimple("max-depth",17));
+ conf.put(new PropertySimple("default-virtual-server", "hulla")); // this is read-only and must not show up in result
+ conf.put(new PropertySimple("test-prop", "Heiko"));
+ conf.put(new PropertySimple("check-interval", 23));
+ conf.put(new PropertySimple("disabled", true));
+ conf.put(new PropertySimple("listings", false));
+ conf.put(new PropertySimple("max-depth", 17));
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
@@ -363,10 +355,10 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
Operation step5 = cop.step(4);
assert step1.getAddress().isEmpty();
- assert step2.getAddress().size()==1;
- assert step3.getAddress().size()==1;
- assert step4.getAddress().size()==1;
- assert step5.getAddress().size()==1;
+ assert step2.getAddress().size() == 1;
+ assert step3.getAddress().size() == 1;
+ assert step4.getAddress().size() == 1;
+ assert step5.getAddress().size() == 1;
assert step2.getAddress().get(0).equals("configuration=jsp-configuration");
assert step3.getAddress().get(0).equals("configuration=jsp-configuration");
assert step4.getAddress().get(0).equals("configuration=static-resources");
@@ -387,13 +379,12 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
String resultString = loadJsonFromFile("system-props.json");
ObjectMapper mapper = new ObjectMapper();
- ComplexResult result = mapper.readValue(resultString,ComplexResult.class);
+ ComplexResult result = mapper.readValue(resultString, ComplexResult.class);
JsonNode json = mapper.valueToTree(result);
connection.setContent(json);
-
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
@@ -402,16 +393,15 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
PropertyList propertyList = new PropertyList("*2");
PropertyMap propertyMap = new PropertyMap("*");
- propertyMap.put(new PropertySimple("name","hulla"));
- propertyMap.put(new PropertySimple("value","hopp"));
+ propertyMap.put(new PropertySimple("name", "hulla"));
+ propertyMap.put(new PropertySimple("value", "hopp"));
propertyList.add(propertyMap);
propertyMap = new PropertyMap("*");
- propertyMap.put(new PropertySimple("name","bar"));
- propertyMap.put(new PropertySimple("value","42!"));
+ propertyMap.put(new PropertySimple("name", "bar"));
+ propertyMap.put(new PropertySimple("value", "42!"));
propertyList.add(propertyMap);
conf.put(propertyList);
-
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
assert cop.numberOfSteps() == 3 : "#Steps should be 3 but were " + cop.numberOfSteps();
@@ -420,9 +410,9 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
Operation step2 = cop.step(1);
Operation step3 = cop.step(2);
- assert step1.getAddress().size()==1;
- assert step2.getAddress().size()==1;
- assert step3.getAddress().size()==1;
+ assert step1.getAddress().size() == 1;
+ assert step2.getAddress().size() == 1;
+ assert step3.getAddress().size() == 1;
assert step1.getAddress().get(0).equals("system-property=hulla");
assert step2.getAddress().get(0).equals("system-property=bar");
assert step3.getAddress().get(0).equals("system-property=hello");
@@ -444,13 +434,12 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
String resultString = loadJsonFromFile("system-props.json");
ObjectMapper mapper = new ObjectMapper();
- ComplexResult result = mapper.readValue(resultString,ComplexResult.class);
+ ComplexResult result = mapper.readValue(resultString, ComplexResult.class);
JsonNode json = mapper.valueToTree(result);
connection.setContent(json);
-
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
@@ -461,18 +450,17 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
PropertyList propertyList = new PropertyList("*2");
PropertyMap propertyMap = new PropertyMap("*");
// add 'hulla'
- propertyMap.put(new PropertySimple("name","hulla"));
- propertyMap.put(new PropertySimple("value","hopp"));
+ propertyMap.put(new PropertySimple("name", "hulla"));
+ propertyMap.put(new PropertySimple("value", "hopp"));
propertyList.add(propertyMap);
propertyMap = new PropertyMap("*");
// update 'bar' -> needs to trigger a remove + an :add
- propertyMap.put(new PropertySimple("name","bar"));
- propertyMap.put(new PropertySimple("value","42!"));
+ propertyMap.put(new PropertySimple("name", "bar"));
+ propertyMap.put(new PropertySimple("value", "42!"));
propertyList.add(propertyMap);
conf.put(propertyList);
// 'hello' is not present -> needs to trigger a :remove for it
-
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
assert cop.numberOfSteps() == 4 : "#Steps should be 4 but were " + cop.numberOfSteps();
@@ -482,10 +470,10 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
Operation step3 = cop.step(2);
Operation step4 = cop.step(3);
- assert step1.getAddress().size()==1;
- assert step2.getAddress().size()==1;
- assert step3.getAddress().size()==1;
- assert step4.getAddress().size()==1;
+ assert step1.getAddress().size() == 1;
+ assert step2.getAddress().size() == 1;
+ assert step3.getAddress().size() == 1;
+ assert step4.getAddress().size() == 1;
assert step1.getAddress().get(0).equals("system-property=hulla");
assert step2.getAddress().get(0).equals("system-property=bar");
assert step3.getAddress().get(0).equals("system-property=bar");
@@ -509,24 +497,23 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
String resultString = loadJsonFromFile("expressionTest.json");
ObjectMapper mapper = new ObjectMapper();
- ComplexResult result = mapper.readValue(resultString,ComplexResult.class);
+ ComplexResult result = mapper.readValue(resultString, ComplexResult.class);
JsonNode json = mapper.valueToTree(result);
connection.setContent(json);
-
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
- conf.put(new PropertySimple("foo:expr",123));
- conf.put(new PropertySimple("foo2:expr","${foo:42}"));
- conf.put(new PropertySimple("bar",456));
+ conf.put(new PropertySimple("foo:expr", 123));
+ conf.put(new PropertySimple("foo2:expr", "${foo:42}"));
+ conf.put(new PropertySimple("bar", 456));
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
assert cop != null;
- assert cop.numberOfSteps()==3;
+ assert cop.numberOfSteps() == 3;
Map<String, Object> additionalProperties = cop.step(0).getAdditionalProperties();
assert additionalProperties.get("name").equals("foo");
@@ -534,20 +521,18 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
additionalProperties = cop.step(1).getAdditionalProperties();
assert additionalProperties.get("name").equals("foo2");
- assert additionalProperties.get("value")!=null;
+ assert additionalProperties.get("value") != null;
assert additionalProperties.get("value") instanceof Map;
- Map<String,Object> map = (Map<String, Object>) additionalProperties.get("value");
+ Map<String, Object> map = (Map<String, Object>) additionalProperties.get("value");
assert map.containsKey("EXPRESSION_VALUE");
assert map.get("EXPRESSION_VALUE").equals("${foo:42}");
-
additionalProperties = cop.step(2).getAdditionalProperties();
assert additionalProperties.get("name").equals("bar");
assert additionalProperties.get("value").equals("456");
}
-
public void test13() throws Exception {
ConfigurationDefinition definition = loadDescriptor("test13");
@@ -556,37 +541,36 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
String resultString = loadJsonFromFile("collapsedMapTest.json");
ObjectMapper mapper = new ObjectMapper();
- ComplexResult result = mapper.readValue(resultString,ComplexResult.class);
+ ComplexResult result = mapper.readValue(resultString, ComplexResult.class);
JsonNode json = mapper.valueToTree(result);
connection.setContent(json);
-
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition,connection,null);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
Configuration conf = new Configuration();
PropertyMap pm = new PropertyMap("connector:collapsed");
- PropertySimple ps = new PropertySimple("name:0","in-vm");
+ PropertySimple ps = new PropertySimple("name:0", "in-vm");
pm.put(ps);
- ps = new PropertySimple("backup:1","hulla-hoo");
+ ps = new PropertySimple("backup:1", "hulla-hoo");
pm.put(ps);
conf.put(pm);
CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
assert cop != null;
- assert cop.numberOfSteps()==1;
+ assert cop.numberOfSteps() == 1;
Operation step = cop.step(0);
- assert step!=null;
+ assert step != null;
assert step.getOperation().equals("write-attribute") : "Step name was " + step.getOperation();
Map<String, Object> additionalProperties = step.getAdditionalProperties();
- assert additionalProperties !=null;
- assert additionalProperties.size()==2;
+ assert additionalProperties != null;
+ assert additionalProperties.size() == 2;
assert additionalProperties.get("name").equals("connector");
Object value = additionalProperties.get("value");
assert value instanceof Map;
- Map <String,Object> map = (Map<String, Object>) value;
+ Map<String, Object> map = (Map<String, Object>) value;
assert map.containsKey("in-vm");
assert map.containsValue("hulla-hoo");
}
@@ -648,4 +632,71 @@ public class ConfigurationUpdatingTest extends AbstractConfigurationHandlingTest
Assert.assertEquals(map.size(), 1);
}
}
+
+ @SuppressWarnings("unchecked")
+ public void testGroupedPropertiesWithIdenticalNames() throws Exception {
+ String resultString = loadJsonFromFile("groupedproperties.json");
+ ObjectMapper mapper = new ObjectMapper();
+ ComplexResult result = mapper.readValue(resultString, ComplexResult.class);
+ JsonNode json = mapper.valueToTree(result);
+
+ FakeConnection connection = new FakeConnection();
+ connection.setContent(json);
+
+ ConfigurationDefinition definition = loadDescriptor("groupedproperties");
+
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(definition, connection, null);
+
+ Configuration conf = new Configuration();
+ for (int index = 1; index < 5; index += 3) {
+ String stringValue = index + "" + (index + 1) + "" + (index + 2);
+
+ String firstPropName = "firstprop:" + index;
+ PropertySimple propertySimple = new PropertySimple(firstPropName, stringValue);
+ conf.put(propertySimple);
+
+ String secondPropName = "secondprop:" + (index + 1);
+ PropertyList propertyList = new PropertyList(secondPropName);
+ for (int i = 0; i < 3; i++) {
+ String value = "test" + (i + index);
+ PropertySimple tempPropertySimple = new PropertySimple("name", value);
+ propertyList.add(tempPropertySimple);
+ }
+ conf.put(propertyList);
+
+ String thirdPropName = "thirdprop:" + (index + 2);
+ PropertyMap propertyMap = new PropertyMap(thirdPropName);
+ PropertySimple tempPropertySimple = new PropertySimple("value", stringValue);
+ propertyMap.put(tempPropertySimple);
+ conf.put(propertyMap);
+ }
+
+ CompositeOperation cop = delegate.updateGenerateOperationFromProperties(conf, new Address());
+
+ Assert.assertNotNull(cop);
+ Assert.assertEquals(cop.numberOfSteps(), 6);
+
+ for (int index = 0; index < 6; index++) {
+ Operation step = cop.step(index);
+ Assert.assertEquals(step.getOperation(), "write-attribute", "Step name was " + step.getOperation());
+ Map<String, Object> additionalProperties = step.getAdditionalProperties();
+ Assert.assertEquals(additionalProperties.size(), 2);
+
+ if (additionalProperties.get("name").equals("firstprop")) {
+ String expectedValue = (index + 1) + "" + (index + 2) + "" + (index + 3);
+ Assert.assertEquals(additionalProperties.get("value"), expectedValue);
+ } else if (additionalProperties.get("name").equals("secondprop")) {
+ List<String> listValue = (List<String>) additionalProperties.get("value");
+ Assert.assertTrue(listValue.contains("test" + (index)));
+ Assert.assertTrue(listValue.contains("test" + (index + 1)));
+ Assert.assertTrue(listValue.contains("test" + (index + 2)));
+ } else {
+ Map<String, String> mapValue = (Map<String, String>) additionalProperties.get("value");
+ Assert.assertEquals(mapValue.size(), 1);
+ String expectedValue = (index - 1) + "" + (index) + "" + (index + 1);
+ Assert.assertEquals(mapValue.values().iterator().next(), expectedValue);
+ }
+ }
+
+ }
}
diff --git a/modules/plugins/jboss-as-7/src/test/resources/groupedproperties.json b/modules/plugins/jboss-as-7/src/test/resources/groupedproperties.json
new file mode 100644
index 0000000..06ff443
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/test/resources/groupedproperties.json
@@ -0,0 +1,24 @@
+{
+ "outcome" : "success",
+ "result" : {
+ "first-group" : {
+ "first-group" : {
+ "firstprop" : "123",
+ "secondprop" : [ "test1", "test2", "test3" ],
+ "thirdprop" : {
+ "value" : "123"
+ }
+ }
+ },
+ "second-group" : {
+ "second-group" : {
+ "firstprop" : "456",
+ "secondprop" : [ "test4", "test5", "test6" ],
+ "thirdprop" : {
+ "value" : "456"
+ }
+ }
+ }
+ },
+ "response-headers" : {"process-state" : "reload-required"}
+}
diff --git a/modules/plugins/jboss-as-7/src/test/resources/test-plugin.xml b/modules/plugins/jboss-as-7/src/test/resources/test-plugin.xml
index 4e9cdd2..16247c6 100644
--- a/modules/plugins/jboss-as-7/src/test/resources/test-plugin.xml
+++ b/modules/plugins/jboss-as-7/src/test/resources/test-plugin.xml
@@ -234,7 +234,7 @@
<server name="listOfPlainMaps"
class="BaseComponent"
discovery="SubsystemDiscovery"
- description="JacORB subsystem configuration"
+ description="list of plain maps"
singleton="true">
<resource-configuration>
@@ -247,5 +247,32 @@
</resource-configuration>
</server>
+ <server name="groupedproperties"
+ class="BaseComponent"
+ discovery="SubsystemDiscovery"
+ description="same name grouped properties"
+ singleton="true">
+ <resource-configuration>
+ <c:group name="child:first-group=first-group" displayName="First group">
+ <c:simple-property name="firstprop:1" type="string"/>
+ <c:list-property name="secondprop:2" displayName="Properties" required="false" readOnly="false">
+ <c:simple-property name="name" displayName="Property-Name"/>
+ </c:list-property>
+ <c:map-property name="thirdprop:3" displayName="Keepalive Time" description="Sample map property." >
+ <c:simple-property name="value" required="true" type="string" description="value"/>
+ </c:map-property>
+ </c:group>
+ <c:group name="child:second-group=second-group" displayName="First group">
+ <c:simple-property name="firstprop:4" type="string"/>
+ <c:list-property name="secondprop:5" displayName="Properties" required="false" readOnly="false">
+ <c:simple-property name="name" displayName="Property-Name"/>
+ </c:list-property>
+ <c:map-property name="thirdprop:6" displayName="Keepalive Time" description="Sample map property." >
+ <c:simple-property name="value" required="true" type="string" description="value"/>
+ </c:map-property>
+ </c:group>
+ </resource-configuration>
+ </server>
+
</plugin>
\ No newline at end of file
12 years, 1 month
[rhq] Branch 'feature/export-reports' - 91 commits - etc/scripts modules/core modules/enterprise modules/plugins pom.xml
by John Sanda
etc/scripts/jboss-as-spawn.sh | 105
modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RhqAgentPluginContainer.java | 94
modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RunDiscoveryExecutor.java | 13
modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java | 6
modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java | 10
modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceFilter.java | 43
modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceTypeUtility.java | 3
modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceUtility.java | 31
modules/core/domain/src/main/java/org/rhq/core/domain/util/TypeAndKeyResourceFilter.java | 25
modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java | 22
modules/core/native-system/src/main/java/org/rhq/core/system/NativeSystemInfo.java | 35
modules/core/plugin-container/src/main/java/org/rhq/core/pc/configuration/ConfigurationCheckExecutor.java | 24
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java | 18
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java | 11
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java | 7
modules/core/plugin-test-util/pom.xml | 1
modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java | 16
modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java | 9
modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java | 16
modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java | 22
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/ServerPluginDetailView.java | 136 -
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java | 4
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyMapListGridRecord.java | 40
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java | 63
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java | 9
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java | 19
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java | 24
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/AbstractOperationHistoryPortlet.java | 12
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java | 29
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListDetailView.java | 14
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java | 17
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java | 59
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsDataSource.java | 42
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsView.java | 2
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/OverviewForm.java | 6
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java | 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java | 18
modules/enterprise/server/plugins/drift-mongodb/pom.xml | 19
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java | 65
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java | 350 ++-
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java | 104
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/DirectoryFilter.java | 17
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java | 13
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java | 39
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java | 80
modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java | 21
modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml | 8
modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java | 99
modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java | 1106 ++++++++++
modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java | 152 +
modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java | 685 +++++-
modules/enterprise/server/plugins/pom.xml | 4
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryComponent.java | 18
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryDiscoveryComponent.java | 4
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheErrorLogEntryProcessor.java | 3
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheFilesComponent.java | 14
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleComponent.java | 4
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryComponent.java | 6
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryDiscoveryComponent.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDiscoveryComponent.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheLocationComponent.java | 14
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApachePluginLifecycleListener.java | 5
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java | 84
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java | 178 -
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerOperationsDelegate.java | 16
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceComponent.java | 92
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceDiscoveryComponent.java | 133 -
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKDiscoveryComponent.java | 27
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/SNMPConstants.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasNode.java | 24
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasTree.java | 16
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java | 82
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasTreeBuilderApache.java | 10
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingPositionToConfiguration.java | 86
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectiveToSimple.java | 88
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java | 248 +-
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/Util.java | 11
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheAugeasMapping.java | 57
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java | 155 -
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ConfigurationToAugeasApacheBase.java | 11
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/DirectiveMapping.java | 77
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java | 90
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigReader.java | 72
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java | 176 -
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveStack.java | 36
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveTree.java | 66
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParser.java | 6
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserException.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserImpl.java | 24
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ApacheBinaryInfo.java | 29
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java | 191 -
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeValueUtil.java | 11
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ConfigurationTimestamp.java | 33
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdAddressUtility.java | 168 -
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdConfParser.java | 53
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/OsProcessUtility.java | 52
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/RuntimeApacheConfiguration.java | 59
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VHostSpec.java | 38
modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VirtualHostLegacyResourceKeyUtil.java | 110
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/MIBLookupException.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPCacheObject.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java | 10
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPConnectException.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPException.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSessionCache.java | 9
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v1.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v2c.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v3.java | 2
modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPValue.java | 6
modules/plugins/apache/src/main/java/org/rhq/plugins/www/util/WWWUtils.java | 27
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasTest.java | 239 +-
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasUtil.java | 257 +-
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApachePluginTest.java | 16
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheTestConstants.java | 37
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/Components.java | 149 -
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/RuntimeConfigurationTest.java | 100
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/SnmpMappingTest.java | 42
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/UnitTestException.java | 30
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensFilter.java | 16
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensHelper.java | 127 -
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/ApacheConfigurationUtil.java | 330 +-
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockApacheBinaryInfo.java | 30
modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockProcessInfo.java | 6
modules/plugins/jboss-as-5/src/test/java/org/rhq/plugins/jbossas5/itest/ApplicationServerComponentTest.java | 14
modules/plugins/jboss-as-7/pom.xml | 5
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java | 43
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7Mode.java | 1
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java | 242 +-
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseComponent.java | 340 +--
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java | 416 +--
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java | 49
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/Domain2Descriptor.java | 2
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HornetQComponent.java | 12
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java | 109
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java | 127 +
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASComponent.java | 8
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java | 146 +
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java | 119 +
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 388 ++-
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java | 49
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java | 53
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java | 53
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java | 15
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainSocketBindingTest.java | 212 +
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java | 235 ++
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java | 22
modules/plugins/jboss-as-7/src/test/resources/itest/jbossas7-arquillian.xml | 2
modules/plugins/jboss-as-7/src/test/resources/log4j.xml | 2
modules/plugins/jboss-as-7/src/test/resources/standalone711.xml | 325 ++
modules/plugins/platform/src/main/java/org/rhq/plugins/platform/WindowsPlatformComponent.java | 21
pom.xml | 3
153 files changed, 7590 insertions(+), 3326 deletions(-)
New commits:
commit 8ac33e99cc480f2502013853713fba5b35385eaf
Merge: 86673a0 35aadf4
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Mar 28 21:49:49 2012 -0400
Merge branch 'master' into feature/export-reports
commit 35aadf4db3bd68be52fffed4006e10a0fae09cfd
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 21:44:24 2012 -0400
fix a couple compile errors and a regression in the code that determines the management bind address from the command line
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
index e0cf57e..4ca0a84 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
@@ -7,10 +7,14 @@ package org.rhq.modules.plugins.jbossas7;
*/
public class AS7CommandLineOption {
- private Character shortName;
+ private String shortName;
private String longName;
- public AS7CommandLineOption(Character shortName, String longName) {
+ public AS7CommandLineOption(char shortName, String longName) {
+ this(new String(new char[] {shortName}), longName);
+ }
+
+ public AS7CommandLineOption(String shortName, String longName) {
if ((shortName == null) && (longName == null)) {
throw new IllegalArgumentException("ShortName and longName cannot both be null.");
}
@@ -19,7 +23,8 @@ public class AS7CommandLineOption {
this.longName = longName;
}
- public Character getShortName() {
+
+ public String getShortName() {
return shortName;
}
@@ -27,4 +32,12 @@ public class AS7CommandLineOption {
return longName;
}
+ @Override
+ public String toString() {
+ return "AS7CommandLineOption{" +
+ "shortName='" + shortName + '\'' +
+ ", longName='" + longName + '\'' +
+ '}';
+ }
+
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index 8641df1..c3214ed 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -48,7 +48,7 @@ public class AbstractBaseDiscovery {
private static final String HOME_DIR_SYSPROP = "jboss.home.dir";
private static final String BIND_ADDRESS_MANAGEMENT_SYSPROP = "jboss.bind.address.management";
- private AS7CommandLineOption BIND_ADDRESS_MANAGEMENT_OPTION = new AS7CommandLineOption(null, "bmanagement");
+ private AS7CommandLineOption BIND_ADDRESS_MANAGEMENT_OPTION = new AS7CommandLineOption("bmanagement", null);
static final int DEFAULT_MGMT_PORT = 9990;
private static final String JBOSS_AS_PREFIX = "jboss-as-";
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index f6dc975..67f70cd 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -117,7 +117,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
pluginConfig.put(new PropertySimple("configDir", configDir));
pluginConfig.put(new PropertySimple("startScript", getMode().getStartScript()));
pluginConfig.put(new PropertySimple("domainHost", findHost(getHostXmlFile(process, configDir))));
- fillUserPassFromFile(pluginConfig, getMode(), homeDir.getPath());
+ fillUserPassFromFile(pluginConfig, getMode(), homeDir);
File logFile = getLogFile(getLogDir(process, baseDir));
initLogEventSourcesConfigProp(logFile.getPath(), pluginConfig);
HostPort managementHostPort = getManagementPortFromHostXml(commandLine);
@@ -316,8 +316,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
return (String) res.getResult();
}
- private void fillUserPassFromFile(Configuration config, AS7Mode mode, String baseDir) {
-
+ private void fillUserPassFromFile(Configuration config, AS7Mode mode, File baseDir) {
// String configDir = baseDir + File.separator + mode + File.separator + "configuration";
String realm = getManagementSecurityRealmFromHostXml();
String fileName = getSecurityPropertyFileFromHostXml(baseDir, mode, realm);
@@ -329,6 +328,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
+ "] or file is not readable");
return;
}
+ // TODO (ips): Can't we use Properties.load() to read the file?
BufferedReader br = null;
try {
FileReader fileReader = new FileReader(file);
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
index 68e407c..bdf8a66 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
@@ -55,7 +55,8 @@ import org.rhq.modules.plugins.jbossas7.json.ReadResource;
import org.rhq.modules.plugins.jbossas7.json.Result;
/**
- * Base component for functionality that is common to Standalone AS and HostControllers
+ * Base component for functionality that is common to Standalone Servers and Host Controllers.
+ *
* @author Heiko W. Rupp
*/
public class BaseServerComponent extends BaseComponent implements MeasurementFacet {
@@ -273,11 +274,12 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
return result;
}
- String homeDir = pluginConfig.getSimpleValue("homeDir", "");
- if (homeDir.isEmpty()) {
- result.setErrorMessage("No homeDir found, can not continue");
+ String homeDirString = pluginConfig.getSimpleValue("homeDir", "");
+ if (homeDirString.isEmpty()) {
+ result.setErrorMessage("No homeDir found - cannot continue.");
return result;
}
+ File homeDir = new File(homeDirString);
String configFile;
BaseProcessDiscovery processDiscovery;
@@ -318,8 +320,8 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
log.error(nsae.getMessage());
result.setErrorMessage(nsae.getMessage());
}
- result.setSimpleResult("User/Password set or updated");
- log.info("Installed management user [" + user + "].");
+ result.setSimpleResult("Management user [" + user + "] added or updated.");
+ log.info("Added or updated management user [" + user + "].");
context.getAvailabilityContext().requestAvailabilityCheck();
@@ -362,7 +364,6 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
else if (!requestName.startsWith("_skm:")) { // handled below
leftovers.add(request);
}
-
}
// Now handle the skm
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
index a4a46df..225468f 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
@@ -95,7 +95,7 @@ public class HostControllerDiscovery extends BaseProcessDiscovery {
@Override
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
- ProcessScanResult psr) {
+ ProcessScanResult psr) throws Exception {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
ProcessInfo process = psr.getProcessInfo();
Configuration pluginConfig = details.getPluginConfiguration();
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
index 9102b21..4a80c60 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
@@ -107,7 +107,7 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
@Override
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
- ProcessScanResult psr) {
+ ProcessScanResult psr) throws Exception {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
ProcessInfo process = psr.getProcessInfo();
Configuration pluginConfig = details.getPluginConfiguration();
commit e73c75134200da25d45abb25401bda5148a0c558
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 21:29:26 2012 -0400
tone down some INFO logging to DEBUG; remove some dead code
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java
index ce3eab7..67094b5 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java
@@ -60,7 +60,7 @@ import org.rhq.core.util.exception.ExceptionPackage;
import org.rhq.core.util.exception.Severity;
/**
- * Standard platform/server inventory detection execution. This is typically called in a non-blocking fashion and the
+ * Standard platform/server inventory detection execution. This is typically called in a non-blocking fashion, and the
* report is returned asynchronously to the server. It is available for direct execution via a Future when running in an
* embedded mode.
*
@@ -84,11 +84,6 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
this.configuration = configuration;
}
- public AutoDiscoveryExecutor() {
- autoDiscoveryRequest = new AutoDiscoveryRequest();
- autoDiscoveryRequest.getScanTypes().add(AutoDiscoveryScanType.Plugin);
- }
-
public void run() {
call();
}
@@ -167,7 +162,6 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
Set<ResourceType> serverTypes = pluginManager.getMetadataManager().getTypesForCategory(ResourceCategory.SERVER);
ResourceContainer platformContainer = inventoryManager.getResourceContainer(inventoryManager.getPlatform());
- ResourceComponent platformComponent = platformContainer.getResourceComponent();
Resource platformResource = platformContainer.getResource();
for (ResourceType serverType : serverTypes) {
@@ -195,7 +189,6 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
component, platformContainer, scanResults);
for (Resource discoveredServer : discoveredServers) {
- log.debug("Detected server " + discoveredServer);
Resource inventoriedResource = this.inventoryManager.mergeResourceFromDiscovery(discoveredServer,
platformResource);
@@ -237,8 +230,10 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
if ((queryResults != null) && (queryResults.size() > 0)) {
for (ProcessInfo autoDiscoveredProcess : queryResults) {
scanResults.add(new ProcessScanResult(processScan, autoDiscoveredProcess));
- log.info("Process scan auto-detected new server resource: scan=[" + processScan
- + "], discovered-process=[" + autoDiscoveredProcess + "]");
+ if (log.isDebugEnabled()) {
+ log.debug("Process scan auto-detected potential new server Resource: scan=[" + processScan
+ + "], discovered-process=[" + autoDiscoveredProcess + "]");
+ }
}
}
}
@@ -248,8 +243,7 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
private boolean verifyComponentCompatibility(ResourceDiscoveryComponent component,
ResourceComponent parentResourceComponent) throws PluginContainerException {
- Method discoveryCall = null;
-
+ Method discoveryCall;
try {
discoveryCall = component.getClass().getMethod("discoverResources", ResourceCategory.class);
} catch (NoSuchMethodException e) {
commit 11e7474de60d30533b9e339014ad5d035fa6a0b4
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 17:49:37 2012 -0400
fix bug where wrong path was being used for mgmt-users.properties file
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index 6139dc1..8641df1 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -255,7 +255,7 @@ public class AbstractBaseDiscovery {
return realm;
}
- String getSecurityPropertyFileFromHostXml(String baseDir, AS7Mode mode, String realm) {
+ String getSecurityPropertyFileFromHostXml(File baseDir, AS7Mode mode, String realm) {
if (hostXml == null)
throw new IllegalArgumentException(CALL_READ_STANDALONE_OR_HOST_XML_FIRST);
@@ -270,14 +270,15 @@ public class AbstractBaseDiscovery {
else
dmode = "domain";
- String fullName;
- if (relDir.equals("jboss." + dmode + ".config.dir"))
- fullName = baseDir + File.separator + mode.getBaseDir() + File.separator + "configuration" + File.separator
- + fileName;
- else
- fullName = relDir + File.separator + fileName;
+ File configDir;
+ if (relDir.equals("jboss." + dmode + ".config.dir")) {
+ configDir = new File(baseDir, "configuration");
+ } else {
+ configDir = new File(relDir);
+ }
+ File securityPropertyFile = new File(configDir, fileName);
- return fullName;
+ return securityPropertyFile.getPath();
}
protected File getHomeDir(ProcessInfo processInfo) {
commit c26cd5c8284e5d1aef243dde12477067df719d3b
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 17:26:57 2012 -0400
improve error handling
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 06371c6..f6dc975 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -72,16 +72,21 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
discoveredResources.add(details);
log.info("Discovered new " + discoveryContext.getResourceType().getName() + " Resource with key ["
+ details.getResourceKey() + "].");
- } catch (Exception e) {
+ } catch (RuntimeException e) {
+ // Only barf a stack trace for runtime exceptions.
log.error("Discovery of a " + discoveryContext.getResourceType().getName()
+ " Resource failed for " + processScanResult.getProcessInfo() + ".", e);
+ } catch (Exception e) {
+ log.error("Discovery of a " + discoveryContext.getResourceType().getName()
+ + " Resource failed for " + processScanResult.getProcessInfo() + " - cause: " + e);
}
}
return discoveredResources;
}
- protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext, ProcessScanResult psr) {
+ protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
+ ProcessScanResult psr) throws Exception {
Configuration pluginConfig = discoveryContext.getDefaultPluginConfiguration();
// IF SE, then look at domain/configuration/host.xml <management interface="default" port="9990
// for management port
@@ -97,7 +102,11 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
String configName = baseDir.getName();
String key = baseDir.getPath();
File configDir = getConfigDir(process, baseDir);
- readStandaloneOrHostXmlFromFile(getHostXmlFile(process, configDir).getPath()); // this sets this.hostXml
+ File hostXmlFile = getHostXmlFile(process, configDir);
+ if (!hostXmlFile.exists()) {
+ throw new Exception("Server configuration file not found at the expected location (" + hostXmlFile + ").");
+ }
+ readStandaloneOrHostXmlFromFile(hostXmlFile.getPath()); // this sets this.hostXml
HostPort hostPort = getHostPortFromHostXml();
String name = buildDefaultResourceName(hostPort, configName, productType);
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASComponent.java
index 1c49aaa..3f5efdb 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ManagedASComponent.java
@@ -113,8 +113,12 @@ public class ManagedASComponent extends BaseComponent {
// We need to deduct the domain host from the path, as it is not encoded in the resource itself.
String serverPath = path;
- serverPath = serverPath.substring(0,serverPath.indexOf(","));
- serverPath = serverPath.substring(serverPath.indexOf("=")+1);
+ try {
+ serverPath = serverPath.substring(0,serverPath.indexOf(","));
+ serverPath = serverPath.substring(serverPath.indexOf("=")+1);
+ } catch (RuntimeException e) {
+ throw new Exception("Failed to extract hostname from server path [" + serverPath + "].", e);
+ }
configuration.put(new PropertySimple("hostname",serverPath));
Operation op = new ReadResource(getAddress());
commit c03837e0bfc1b545809fe9728498848ea1d32a67
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 17:21:22 2012 -0400
improve logging
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/configuration/ConfigurationCheckExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/configuration/ConfigurationCheckExecutor.java
index 6138dcf..4447b9f 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/configuration/ConfigurationCheckExecutor.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/configuration/ConfigurationCheckExecutor.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2008 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -21,7 +21,6 @@ package org.rhq.core.pc.configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rhq.core.clientapi.agent.PluginContainerException;
-import org.rhq.core.clientapi.agent.configuration.ConfigurationUpdateRequest;
import org.rhq.core.clientapi.agent.configuration.ConfigurationUtility;
import org.rhq.core.clientapi.server.configuration.ConfigurationServerService;
import org.rhq.core.domain.measurement.AvailabilityType;
@@ -35,8 +34,6 @@ import org.rhq.core.pc.inventory.ResourceContainer;
import org.rhq.core.pc.util.FacetLockType;
import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
-import java.util.HashSet;
-import java.util.Set;
import java.util.List;
import java.util.concurrent.Callable;
@@ -44,6 +41,7 @@ import java.util.concurrent.Callable;
* @author Greg Hinkle
*/
public class ConfigurationCheckExecutor implements Runnable, Callable {
+
private Log log = LogFactory.getLog(ConfigurationCheckExecutor.class);
private ConfigurationManager configurationManager;
@@ -62,7 +60,7 @@ public class ConfigurationCheckExecutor implements Runnable, Callable {
}
public Object call() {
- log.info("Starting configuration update check");
+ log.info("Starting configuration update check...");
long start = System.currentTimeMillis();
checkConfigurations(this.inventoryManager.getPlatform(), true);
@@ -87,20 +85,16 @@ public class ConfigurationCheckExecutor implements Runnable, Callable {
// Expecting when the resource does not support configuration management
}
-
if (resourceComponent != null) {
// Only report availability for committed resources; don't bother with new, ignored or deleted resources.
if (resource.getInventoryStatus() == InventoryStatus.COMMITTED
&& resourceType.getResourceConfigurationDefinition() != null) {
- if (log.isErrorEnabled())
- log.debug("Checking for updated resource configuration on: " + resource);
-
- ConfigurationUpdateRequest request =
- new ConfigurationUpdateRequest(0, resource.getResourceConfiguration(), resource.getId());
+ if (log.isDebugEnabled()) {
+ log.debug("Checking for updated Resource configuration for " + resource + "...");
+ }
try {
-
Configuration liveConfiguration = resourceComponent.loadResourceConfiguration();
if (liveConfiguration != null) {
@@ -123,7 +117,8 @@ public class ConfigurationCheckExecutor implements Runnable, Callable {
}
}
} catch (Throwable t) {
- log.warn("Unable to check for updated configuration", t);
+ log.warn("An error occurred while checking for an updated Resource configuration for " +
+ resource + ".", t);
}
}
}
@@ -131,7 +126,7 @@ public class ConfigurationCheckExecutor implements Runnable, Callable {
if (checkChildren) {
for (Resource child : resource.getChildResources()) {
try {
- checkConfigurations(child, true);
+ checkConfigurations(child, true);
} catch (Exception e) {
e.printStackTrace();
}
@@ -139,4 +134,5 @@ public class ConfigurationCheckExecutor implements Runnable, Callable {
}
}
}
+
}
commit fdbb5c2d3eaf73e044d97064be42db85718ef03a
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 16:45:01 2012 -0400
add an 'rhqadmin' management user to each cloned AS7 config, so the instances can be connected to by RHQ without any
manual intervention; fix a regression
diff --git a/etc/scripts/jboss-as-spawn.sh b/etc/scripts/jboss-as-spawn.sh
index c1fe8ef..4bdbf30 100755
--- a/etc/scripts/jboss-as-spawn.sh
+++ b/etc/scripts/jboss-as-spawn.sh
@@ -10,7 +10,7 @@
#JBOSS_CONFIG=standalone
# the number of instances to start
-#JBOSS_INSTANCES=1
+#JBOSS_INSTANCES=2
# options to pass to the JBoss AS JVM
#JAVA_OPTS="-Xms200M -Xmx400M -XX:MaxPermSize=150M -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.lang.ClassLoader.allowArraySyntax=true -Djava.net.preferIPv4Stack=true"
@@ -70,17 +70,19 @@ if [ -n "${AS7}" ]; then
echo "AS7 config file not found." >&2
exit 1
fi
+ AS7_ENCODED_PASSWORD=`echo -n "rhqadmin:ManagementRealm:rhqadmin" | md5sum | awk '{printf $1}'`
fi
-for (( i = 1 ; i <= ${INSTANCES}; i++ )); do
+for (( i = 1 ; i <= ${JBOSS_INSTANCES}; i++ )); do
CONFIG_DIR_NAME="${JBOSS_CONFIG}${i}"
CONFIG_DIR="${SERVER_BASE_DIR}/${CONFIG_DIR_NAME}"
if [ ! -d "${CONFIG_DIR}" ]; then
echo "Creating new config dir '${CONFIG_DIR}'..."
- cp -pr "${SERVER_BASE_DIR}/${JBOSS_CONFIG}" "${CONFIG_DIR}"
+ cp -pr "${JBOSS_CONFIG_DIR}" "${CONFIG_DIR}"
( cd "${CONFIG_DIR}" ; rm -rf data log tmp work )
if [ -n "${AS7}" ]; then
sed -in '{s/<inet-address /<loopback-address /}' "${CONFIG_FILE}"
+ echo "rhqadmin=${AS7_ENCODED_PASSWORD}" >"${CONFIG_DIR}/configuration/mgmt-users.properties"
fi
fi
BIND_ADDRESS="127.${OCTET}.0.${i}"
commit 390d77685e376a39ea51a1cba4f3bd392cc3b290
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Wed Mar 28 16:31:18 2012 -0400
[Bug 802780 - Configuration editor in server plugin details is not stretching vertically]
I apologize for making more edits here than were probably necessary. I was
concerned that the async building of the section stack was a problem, which
it may have been, I'm not sure. Anyway, I think it's in decent shape now and
now waits to present the view until it's fully built.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/ServerPluginDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/ServerPluginDetailView.java
index b9e70e4..5e6f717 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/ServerPluginDetailView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/admin/ServerPluginDetailView.java
@@ -23,6 +23,7 @@ import java.util.ArrayList;
import java.util.EnumSet;
import java.util.Map;
+import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.VisibilityMode;
@@ -35,6 +36,7 @@ import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
+import com.smartgwt.client.widgets.toolbar.ToolStrip;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
@@ -52,11 +54,9 @@ import org.rhq.enterprise.gui.coregui.client.gwt.PluginGWTServiceAsync;
import org.rhq.enterprise.gui.coregui.client.util.message.Message;
import org.rhq.enterprise.gui.coregui.client.util.message.Message.Severity;
import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHStack;
import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableSectionStack;
import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVStack;
/**
* Shows details of a server plugin.
@@ -68,31 +68,32 @@ public class ServerPluginDetailView extends LocatableVLayout {
private final PluginGWTServiceAsync pluginManager = GWTServiceLookup.getPluginService();
private final int pluginId;
- private int DETAILS_POSITION = 0;
- private int HELP_POSITION = 1;
- private int CONTROLS_POSITION = 2;
- private int PLUGINCONFIG_POSITION = 3;
- private int SCHEDULEDJOBS_POSITION = 4;
+ private final LocatableSectionStack sectionStack;
+ private SectionStackSection detailsSection = null;
+ private SectionStackSection helpSection = null;
+ private SectionStackSection controlsSection = null;
+ private SectionStackSection pluginConfigSection = null;
+ private SectionStackSection scheduledJobsSection = null;
+ private int initSectionCount = 0;
public ServerPluginDetailView(String locatorId, int pluginId) {
super(locatorId);
this.pluginId = pluginId;
setHeight100();
setWidth100();
- }
-
- @Override
- protected void onDraw() {
- super.onDraw();
-
- final LocatableSectionStack sectionStack;
+ setOverflow(Overflow.AUTO);
sectionStack = new LocatableSectionStack(extendLocatorId("stack"));
sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE);
sectionStack.setWidth100();
sectionStack.setHeight100();
sectionStack.setMargin(5);
- sectionStack.setOverflow(Overflow.AUTO);
+ sectionStack.setOverflow(Overflow.VISIBLE);
+ }
+
+ @Override
+ protected void onInit() {
+ super.onInit();
pluginManager.getServerPlugin(this.pluginId, true, new AsyncCallback<ServerPlugin>() {
public void onSuccess(ServerPlugin plugin) {
@@ -107,8 +108,52 @@ public class ServerPluginDetailView extends LocatableVLayout {
CoreGUI.getErrorHandler().handleError(MSG.view_admin_plugins_loadFailure(), caught);
}
});
+ }
- addMember(sectionStack);
+ public boolean isInitialized() {
+ return initSectionCount >= 5;
+ }
+
+ @Override
+ protected void onDraw() {
+ super.onDraw();
+
+ // wait until we have all of the sections before we show them. We don't use InitializableView because,
+ // it seems they are not supported (in the applicable renderView()) at this level.
+ new Timer() {
+ final long startTime = System.currentTimeMillis();
+
+ public void run() {
+ if (isInitialized()) {
+ if (null != detailsSection) {
+ sectionStack.addSection(detailsSection);
+ }
+ if (null != helpSection) {
+ sectionStack.addSection(helpSection);
+ }
+ if (null != controlsSection) {
+ sectionStack.addSection(controlsSection);
+ }
+ if (null != pluginConfigSection) {
+ sectionStack.addSection(pluginConfigSection);
+ }
+ if (null != scheduledJobsSection) {
+ sectionStack.addSection(scheduledJobsSection);
+ }
+
+ addMember(sectionStack);
+ markForRedraw();
+
+ } else {
+ // don't wait forever, give up after 20s and show what we have
+ long elapsedMillis = System.currentTimeMillis() - startTime;
+ if (elapsedMillis > 20000) {
+ initSectionCount = 5;
+ }
+ schedule(100); // Reschedule the timer.
+ }
+ }
+ }.run(); // fire the timer immediately
}
private void prepareControlsSection(final SectionStack stack, final ServerPlugin plugin) {
@@ -121,8 +166,10 @@ public class ServerPluginDetailView extends LocatableVLayout {
SectionStackSection section = new SectionStackSection(MSG.view_admin_plugins_serverControls());
section.setExpanded(false);
section.addItem(new ServerPluginControlView(extendLocatorId("controlView"), plugin, result));
- stack.addSection(section, CONTROLS_POSITION);
+
+ controlsSection = section;
}
+ ++initSectionCount;
}
public void onFailure(Throwable caught) {
@@ -137,26 +184,23 @@ public class ServerPluginDetailView extends LocatableVLayout {
pluginManager.getServerPluginConfigurationDefinition(pluginKey, new AsyncCallback<ConfigurationDefinition>() {
public void onSuccess(ConfigurationDefinition def) {
if (def != null) {
- LocatableVStack layout = new LocatableVStack(extendLocatorId("pcEditorLayout"));
- layout.setMargin(5);
- layout.setMembersMargin(5);
- layout.setAutoHeight();
+ LocatableVLayout layout = new LocatableVLayout(extendLocatorId("pcEditorLayout"));
- LocatableHStack buttons = new LocatableHStack(extendLocatorId("pcButtonsLayout"));
+ ToolStrip buttons = new ToolStrip();
+ buttons.setWidth100();
+ buttons.setExtraSpace(10);
buttons.setMembersMargin(5);
- buttons.setAutoHeight();
- layout.addMember(buttons);
+ buttons.setLayoutMargin(5);
final IButton saveButtonPC = new LocatableIButton(extendLocatorId("pcSave"), MSG
.common_button_save());
- buttons.addMember(saveButtonPC);
final IButton resetButtonPC = new LocatableIButton(extendLocatorId("pcRest"), MSG
.common_button_reset());
- buttons.addMember(resetButtonPC);
Configuration config = plugin.getPluginConfiguration();
final ConfigurationEditor editorPC = new ConfigurationEditor(extendLocatorId("pcEdit"), def, config);
+ editorPC.setOverflow(Overflow.AUTO);
editorPC.addPropertyValueChangeListener(new PropertyValueChangeListener() {
public void propertyValueChanged(PropertyValueChangeEvent event) {
if (event.isInvalidPropertySetChanged()) {
@@ -169,7 +213,6 @@ public class ServerPluginDetailView extends LocatableVLayout {
}
}
});
- layout.addMember(editorPC);
resetButtonPC.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
@@ -200,11 +243,19 @@ public class ServerPluginDetailView extends LocatableVLayout {
}
});
+ buttons.addMember(saveButtonPC);
+ buttons.addMember(resetButtonPC);
+ layout.addMember(buttons);
+ layout.addMember(editorPC);
+
SectionStackSection section = new SectionStackSection(MSG.view_admin_plugins_serverConfig());
section.setExpanded(false);
section.setItems(layout);
- stack.addSection(section, PLUGINCONFIG_POSITION);
+
+ pluginConfigSection = section;
}
+
+ ++initSectionCount;
}
@Override
@@ -222,14 +273,12 @@ public class ServerPluginDetailView extends LocatableVLayout {
public void onSuccess(ConfigurationDefinition def) {
if (def != null) {
LocatableVLayout layout = new LocatableVLayout(extendLocatorId("sjEditorLayout"));
- layout.setMargin(5);
- layout.setMembersMargin(5);
- layout.setAutoHeight();
- LocatableHStack buttons = new LocatableHStack(extendLocatorId("sjButtonsLayout"));
+ ToolStrip buttons = new ToolStrip();
+ buttons.setWidth100();
+ buttons.setExtraSpace(10);
buttons.setMembersMargin(5);
- buttons.setAutoHeight();
- layout.addMember(buttons);
+ buttons.setLayoutMargin(5);
final IButton saveButtonSJ = new LocatableIButton(extendLocatorId("sjSave"), MSG
.common_button_save());
@@ -241,6 +290,7 @@ public class ServerPluginDetailView extends LocatableVLayout {
Configuration config = plugin.getScheduledJobsConfiguration();
final ConfigurationEditor editorSJ = new ConfigurationEditor(extendLocatorId("sjEdit"), def, config);
+ editorSJ.setOverflow(Overflow.AUTO);
editorSJ.addPropertyValueChangeListener(new PropertyValueChangeListener() {
public void propertyValueChanged(PropertyValueChangeEvent event) {
if (event.isInvalidPropertySetChanged()) {
@@ -253,7 +303,6 @@ public class ServerPluginDetailView extends LocatableVLayout {
}
}
});
- layout.addMember(editorSJ);
resetButtonSJ.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
@@ -284,11 +333,17 @@ public class ServerPluginDetailView extends LocatableVLayout {
}
});
+ layout.addMember(buttons);
+ layout.addMember(editorSJ);
+
SectionStackSection section = new SectionStackSection(MSG.view_admin_plugins_serverScheduleJobs());
section.setExpanded(false);
section.setItems(layout);
- stack.addSection(section, SCHEDULEDJOBS_POSITION);
+
+ scheduledJobsSection = section;
}
+
+ ++initSectionCount;
}
@Override
@@ -305,8 +360,11 @@ public class ServerPluginDetailView extends LocatableVLayout {
section.setExpanded(true);
Label help = new Label(plugin.getHelp());
section.setItems(help);
- stack.addSection(section, HELP_POSITION);
+
+ helpSection = section;
}
+
+ ++initSectionCount;
return;
}
@@ -365,7 +423,9 @@ public class ServerPluginDetailView extends LocatableVLayout {
SectionStackSection section = new SectionStackSection(MSG.common_title_details());
section.setExpanded(true);
section.setItems(form);
- stack.addSection(section, DETAILS_POSITION);
+
+ detailsSection = section;
+ ++initSectionCount;
return;
}
commit 7aa4e443f237edac35209bb68e0ac289bc2ebb90
Author: Denis Krusko <kruskod(a)gmail.com>
Date: Wed Mar 28 22:15:51 2012 +0200
BZ 796795 Add separator after type label in type tooltip.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/OverviewForm.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/OverviewForm.java
index 54ac526..ff25487 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/OverviewForm.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/OverviewForm.java
@@ -143,8 +143,8 @@ public class OverviewForm extends EnhancedDynamicForm {
// Type
StaticTextItem typeItem = new StaticTextItem("type", MSG.view_summaryOverviewForm_field_type());
- typeItem.setTooltip(MSG.view_summaryOverviewForm_label_plugin() + type.getPlugin() + "\n<br>"
- + MSG.common_title_type() + type.getName());
+ typeItem.setTooltip(MSG.common_title_plugin() + ": " + type.getPlugin() + "\n<br>"
+ + MSG.common_title_type() + ": " + type.getName());
typeItem.setValue(AncestryUtil.getFormattedType(type));
formItems.add(typeItem);
@@ -347,7 +347,7 @@ public class OverviewForm extends EnhancedDynamicForm {
}
public void loadData() {
- // TODO: Reload the ResourceComposite too.
+ // TODO: Reload the ResourceComposite too.
loadTraitValues();
markForRedraw();
}
commit 1513f7dc395ddc7a10c99a955a91c4e8bf6f2798
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed Mar 28 21:57:50 2012 +0200
Add test for domain mode and apply fixes to the standalone one.
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainSocketBindingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainSocketBindingTest.java
new file mode 100644
index 0000000..f222224
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainSocketBindingTest.java
@@ -0,0 +1,212 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.modules.plugins.jbossas7.itest.domain;
+
+import java.util.Iterator;
+
+import org.jetbrains.annotations.NotNull;
+import org.testng.annotations.Test;
+
+import org.rhq.core.clientapi.agent.PluginContainerException;
+import org.rhq.core.clientapi.agent.configuration.ConfigurationUpdateRequest;
+import org.rhq.core.clientapi.server.configuration.ConfigurationUpdateResponse;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.resource.InventoryStatus;
+import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.ResourceCategory;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pc.inventory.InventoryManager;
+import org.rhq.modules.plugins.jbossas7.itest.AbstractJBossAS7PluginTest;
+import org.rhq.test.arquillian.RunDiscovery;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+/**
+ * Test stuff around socket bindings.
+ * This could actually also run for domain mode
+ * @author Heiko W. Rupp
+ */
+@Test(groups = {"integration", "pc", "domain"}, singleThreaded = true)
+public class DomainSocketBindingTest extends AbstractJBossAS7PluginTest {
+
+ public static final ResourceType RESOURCE_TYPE = new ResourceType("SocketBindingGroup", PLUGIN_NAME, ResourceCategory.SERVICE, null);
+ private static final String RESOURCE_KEY = "socket-binding-group=standard-sockets";
+
+ @Test(priority = 10,groups = "discovery")
+ @RunDiscovery(discoverServices = true, discoverServers = true)
+ public void runDiscovery() throws Exception {
+ Resource platform = this.pluginContainer.getInventoryManager().getPlatform();
+
+ Thread.sleep(10*1000L); // delay so that PC gets a chance to scan for resources
+
+ assertNotNull(platform);
+ assertEquals(platform.getInventoryStatus(), InventoryStatus.COMMITTED);
+
+ Thread.sleep(20*1000L); // delay so that PC gets a chance to scan for resources
+ }
+
+
+ @Test(priority = 11)
+ public void loadBindings() throws Exception {
+
+ loadConfig();
+ }
+
+ @Test(priority = 11)
+ public void addBinding() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertyMap map = new PropertyMap("binding");
+ PropertySimple ps = new PropertySimple("name","bla");
+ map.put(ps);
+ ps = new PropertySimple("port:expr",12345);
+ map.put(ps);
+ ps = new PropertySimple("fixed-port",false);
+ map.put(ps);
+ ps = new PropertySimple("multicast-port:expr","${foo.bar.baz:12346}");
+ map.put(ps);
+ PropertyList pl = (PropertyList) configuration.get("*");
+ int count = pl.getList().size();
+ pl.add(map);
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config add resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ pl = (PropertyList) configuration.get("*");
+ assert pl.getList().size() == count+1;
+ }
+
+ @Test(priority = 11)
+ public void addModifyBinding() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertyMap map = new PropertyMap("binding");
+ PropertySimple ps = new PropertySimple("name","bla2");
+ map.put(ps);
+ ps = new PropertySimple("port:expr",12355);
+ map.put(ps);
+ ps = new PropertySimple("fixed-port",false);
+ map.put(ps);
+ ps = new PropertySimple("multicast-port:expr","${foo.bar.baz:12356}");
+ map.put(ps);
+ PropertyList pl = (PropertyList) configuration.get("*");
+ pl.add(map);
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config add resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ map=null;
+ pl = (PropertyList) configuration.get("*");
+ for (Property prop: pl.getList()) {
+ PropertyMap pm = (PropertyMap) prop;
+ PropertySimple ps2 = pm.getSimple("name");
+ if (!ps2.getStringValue().equals("bla2"))
+ continue;
+
+ map = pm;
+ }
+ assert map != null : "Did not find 'bla2' in the returned config";
+ map.put(new PropertySimple("port:expr",22355));
+ map.put(new PropertySimple("fixed-port",true));
+ request = new ConfigurationUpdateRequest(2,configuration,getResource().getId());
+ response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config update resulted in this error: " + response.getErrorMessage();
+
+ }
+
+ @Test(priority = 11)
+ public void addRemoveBinding() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertyMap map = new PropertyMap("binding");
+ PropertySimple ps = new PropertySimple("name","bla3");
+ map.put(ps);
+ ps = new PropertySimple("port:expr",12365);
+ map.put(ps);
+ ps = new PropertySimple("fixed-port",false);
+ map.put(ps);
+ ps = new PropertySimple("multicast-port:expr","${foo.bar.baz:12366}");
+ map.put(ps);
+ PropertyList pl = (PropertyList) configuration.get("*");
+ int count = pl.getList().size();
+ pl.add(map);
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config add resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ pl = (PropertyList) configuration.get("*");
+ assert pl.getList().size() == count+1;
+
+ Iterator<Property> iter = pl.getList().iterator();
+ while (iter.hasNext()) {
+ Property prop = iter.next();
+ PropertyMap pm = (PropertyMap) prop;
+ if (pm.getSimpleValue("name","xxx").equals("bla3")) {
+ iter.remove();
+ break;
+ }
+ }
+ assert pl.getList().size() == count;
+
+ request = new ConfigurationUpdateRequest(3,configuration,getResource().getId());
+ response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Property removal resulted in this error: " + response.getErrorMessage();
+ }
+
+
+
+
+ @NotNull
+ private Configuration loadConfig() throws PluginContainerException {
+ Configuration config = pluginContainer.getConfigurationManager().loadResourceConfiguration(getResource().getId());
+ assert config != null;
+ assert !config.getProperties().isEmpty();
+ return config;
+ }
+
+ private Resource getResource() {
+
+ InventoryManager im = pluginContainer.getInventoryManager();
+ Resource platform = im.getPlatform();
+ assert platform != null : "Did not find a platform";
+ Resource server = getResourceByTypeAndKey(platform,DomainServerComponentTest.RESOURCE_TYPE,DomainServerComponentTest.RESOURCE_KEY);
+ assert server != null : "Did not find the domain server";
+ Resource bindings = getResourceByTypeAndKey(server,RESOURCE_TYPE,RESOURCE_KEY);
+ assert bindings != null : "Did not find " + RESOURCE_KEY;
+ return bindings;
+ }
+
+}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
index 6b90fd8..8cd26d6 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
@@ -33,6 +33,7 @@ import org.rhq.core.domain.configuration.Property;
import org.rhq.core.domain.configuration.PropertyList;
import org.rhq.core.domain.configuration.PropertyMap;
import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceCategory;
import org.rhq.core.domain.resource.ResourceType;
@@ -40,6 +41,9 @@ import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.modules.plugins.jbossas7.itest.AbstractJBossAS7PluginTest;
import org.rhq.test.arquillian.RunDiscovery;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
/**
* Test stuff around socket bindings.
* This could actually also run for domain mode
@@ -51,20 +55,27 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
public static final ResourceType RESOURCE_TYPE = new ResourceType("SocketBindingGroup", PLUGIN_NAME, ResourceCategory.SERVICE, null);
private static final String RESOURCE_KEY = "socket-binding-group=standard-sockets";
- @BeforeClass
- @RunDiscovery(discoverServices = true)
- public void doSomeDiscovery() throws Exception {
+ @Test(priority = 10,groups = "discovery")
+ @RunDiscovery(discoverServices = true, discoverServers = true) public void doSomeDiscovery() throws Exception {
+ Resource platform = this.pluginContainer.getInventoryManager().getPlatform();
+ assertNotNull(platform);
+ assertEquals(platform.getInventoryStatus(), InventoryStatus.COMMITTED);
+
+ Thread.sleep(20*1000L); // delay so that PC gets a chance to scan for resources
+
}
+ @Test(priority = 11)
public void loadBindings() throws Exception {
loadConfig();
}
+ @Test(priority = 11)
public void addBinding() throws Exception {
Configuration configuration = loadConfig();
- PropertyMap map = new PropertyMap("socket-binding=bla");
+ PropertyMap map = new PropertyMap("binding");
PropertySimple ps = new PropertySimple("name","bla");
map.put(ps);
ps = new PropertySimple("port",12345);
@@ -87,17 +98,18 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
assert pl.getList().size() == count+1;
}
+ @Test(priority = 11)
public void addModifyBinding() throws Exception {
Configuration configuration = loadConfig();
- PropertyMap map = new PropertyMap("bla2");
+ PropertyMap map = new PropertyMap("binding");
PropertySimple ps = new PropertySimple("name","bla2");
map.put(ps);
- ps = new PropertySimple("port",12355);
+ ps = new PropertySimple("port:expr",12355);
map.put(ps);
ps = new PropertySimple("fixed-port",false);
map.put(ps);
- ps = new PropertySimple("multicast-port","${foo.bar.baz:12356}");
+ ps = new PropertySimple("multicast-port:expr","${foo.bar.baz:12356}");
map.put(ps);
PropertyList pl = (PropertyList) configuration.get("*");
pl.add(map);
@@ -110,14 +122,16 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
configuration = loadConfig();
map=null;
pl = (PropertyList) configuration.get("*");
- for (Property prop: pl.getList()) {
- if (!prop.getName().equals("bla2"))
+ for (Property prop : pl.getList()) {
+ PropertyMap pm = (PropertyMap) prop;
+ PropertySimple ps2 = pm.getSimple("name");
+ if (!ps2.getStringValue().equals("bla2"))
continue;
- map = (PropertyMap) prop;
+ map = pm;
}
assert map != null : "Did not find 'bla2' in the returned config";
- map.put(new PropertySimple("port",22355));
+ map.put(new PropertySimple("port:expr",22355));
map.put(new PropertySimple("fixed-port",true));
request = new ConfigurationUpdateRequest(2,configuration,getResource().getId());
response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
@@ -126,17 +140,18 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
}
+ @Test(priority = 11)
public void addRemoveBinding() throws Exception {
Configuration configuration = loadConfig();
- PropertyMap map = new PropertyMap("bla3");
+ PropertyMap map = new PropertyMap("binding");
PropertySimple ps = new PropertySimple("name","bla3");
map.put(ps);
- ps = new PropertySimple("port",12365);
+ ps = new PropertySimple("port:expr",12365);
map.put(ps);
ps = new PropertySimple("fixed-port",false);
map.put(ps);
- ps = new PropertySimple("multicast-port","${foo.bar.baz:12366}");
+ ps = new PropertySimple("multicast-port:expr","${foo.bar.baz:12366}");
map.put(ps);
PropertyList pl = (PropertyList) configuration.get("*");
int count = pl.getList().size();
@@ -154,11 +169,13 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
Iterator<Property> iter = pl.getList().iterator();
while (iter.hasNext()) {
Property prop = iter.next();
- if (prop.getName().equals("bla3")) {
+ PropertyMap pm = (PropertyMap) prop;
+ if (pm.getSimpleValue("name","xxx").equals("bla3")) {
iter.remove();
break;
}
}
+ assert pl.getList().size() == count;
request = new ConfigurationUpdateRequest(3,configuration,getResource().getId());
response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
@@ -167,6 +184,7 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
}
/** THIS ONE WILL NOT WORK IN DOMAIN MODE */
+ @Test(priority = 11)
public void changePortOffset() throws Exception {
Configuration configuration = loadConfig();
commit ec16506e36e34f960bab19e263ce8781cdd6f944
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 14:45:52 2012 -0400
turn down PC logging by default to make test output more readable
diff --git a/modules/plugins/jboss-as-7/src/test/resources/log4j.xml b/modules/plugins/jboss-as-7/src/test/resources/log4j.xml
index 2687703..6e73f53 100644
--- a/modules/plugins/jboss-as-7/src/test/resources/log4j.xml
+++ b/modules/plugins/jboss-as-7/src/test/resources/log4j.xml
@@ -43,7 +43,6 @@
</layout>
</appender>
-<!--
<category name="org.rhq.core.pc">
<priority value="ERROR"/>
</category>
@@ -51,7 +50,7 @@
<category name="org.rhq.core.pc.PluginContainer">
<priority value="INFO"/>
</category>
--->
+
<category name="org.rhq.core.clientapi">
<priority value="FATAL"/>
</category>
commit 94460b066cd9cbd956b4c2ec1aca454454071c4f
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 14:45:22 2012 -0400
well-formed XML cannot have "--" within a comment
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 a8fe908..ba2e445 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
@@ -370,7 +370,7 @@ public class Domain2Descriptor {
builder.append(generateProperty(4, entryValue, type, entryKey, null));
builder.append('\n');
} else {
- builder.append("<!--").append(entry.getKey()).append("--").append(entry.getValue().toString())
+ builder.append("<!--").append(entry.getKey()).append("..").append(entry.getValue().toString())
.append("-->");
}
}
commit 1c3f8bcaf12995abf50565994f3fcabc5e2634f9
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 14:44:44 2012 -0400
add support for resolving jboss.*.dir sysprops that are relative paths (this completes the work on https://bugzilla.redhat.com/show_bug.cgi?id=807008); add some utility code for reading AS7 server command line options; improve code for determining log file location
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
new file mode 100644
index 0000000..e0cf57e
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
@@ -0,0 +1,30 @@
+package org.rhq.modules.plugins.jbossas7;
+
+/**
+ * The name(s) associated with an AS7 server command line option.
+ *
+ * @author Ian Springer
+ */
+public class AS7CommandLineOption {
+
+ private Character shortName;
+ private String longName;
+
+ public AS7CommandLineOption(Character shortName, String longName) {
+ if ((shortName == null) && (longName == null)) {
+ throw new IllegalArgumentException("ShortName and longName cannot both be null.");
+ }
+
+ this.shortName = shortName;
+ this.longName = longName;
+ }
+
+ public Character getShortName() {
+ return shortName;
+ }
+
+ public String getLongName() {
+ return longName;
+ }
+
+}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index a7acad9..6139dc1 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -32,6 +32,7 @@ import javax.xml.xpath.XPathFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.jetbrains.annotations.Nullable;
import org.w3c.dom.Document;
import org.rhq.core.pluginapi.util.FileUtils;
@@ -44,9 +45,11 @@ import org.rhq.core.system.ProcessInfo;
*/
public class AbstractBaseDiscovery {
- static final String BOOT_LOG_FILE_SYSPROP = "org.jboss.boot.log.file";
private static final String HOME_DIR_SYSPROP = "jboss.home.dir";
+ private static final String BIND_ADDRESS_MANAGEMENT_SYSPROP = "jboss.bind.address.management";
+ private AS7CommandLineOption BIND_ADDRESS_MANAGEMENT_OPTION = new AS7CommandLineOption(null, "bmanagement");
+
static final int DEFAULT_MGMT_PORT = 9990;
private static final String JBOSS_AS_PREFIX = "jboss-as-";
static final String CALL_READ_STANDALONE_OR_HOST_XML_FIRST = "hostXml is null. You need to call 'readStandaloneOrHostXml' first.";
@@ -82,17 +85,6 @@ public class AbstractBaseDiscovery {
}
/**
- * Determine the location of the boot log file of the server by parsing the command line
- * @param commandLine command line arguments of the process
- * @return The log file location or empty string otherwise
- */
- //-Dorg.jboss.boot.log.file=/devel/jbas7/jboss-as/build/target/jboss-7.0.0.Alpha2/domain/log/server-manager/boot.log
- //-Dlogging.configuration=file:/devel/jbas7/jboss-as/build/target/jboss-7.0.0.Alpha2/domain/configuration/logging.properties
- String getLogFileFromCommandLine(String[] commandLine) {
- return getSystemPropertyFromCommandLine(commandLine, BOOT_LOG_FILE_SYSPROP, "");
- }
-
- /**
* Try to obtain the management IP and port from the already parsed host.xml or standalone.xml
* @return an Object containing host and port
* @see #readStandaloneOrHostXmlFromFile(String) for how to obtain the parsed xml
@@ -194,47 +186,24 @@ public class AbstractBaseDiscovery {
if (value.contains(":")) {
int i = value.indexOf(":");
expression = value.substring(0, i);
- fallback = value.substring(i + 1);
+ fallback = ((i + 1) < value.length()) ? value.substring(i + 1) : "";
} else {
expression = value;
}
- /*
- * Now try to find the expression in the arguments.
- * AS 7 unfortunately is "too clever" and we need to look for
- * -D jboss.bind.address.management
- * or
- * -b management
- * to find the management addresss
- */
-
- String ret = null;
- for (int i = 0, commandLineLength = commandLine.length; i < commandLineLength; i++) {
- String line = commandLine[i];
- if (expression.contains("address")) {
- if (line.contains("-bmanagement") || line.contains("jboss.bind.address.management")) {
- if (line.contains("="))
- ret = line.substring(line.indexOf("=") + 1); // -bmanagement=1.2.3.4
- else
- ret = commandLine[i + 1]; // -bmanagement 1.2.3.4
- break;
- }
- } else if (expression.equals("jboss.management.http.port")) {
- if (line.contains(expression)) {
- ret = line.substring(line.indexOf("=") + 1);
- break;
- }
- } else if (expression.equals(SOCKET_BINDING_PORT_OFFSET_SYSPROP)) {
- if (line.contains(expression)) {
- ret = line.substring(line.indexOf('=')+1);
- break;
- }
- }
- }
- if (ret == null)
- ret = fallback;
- return ret;
+ String resolvedValue = null;
+ if (expression.equals(BIND_ADDRESS_MANAGEMENT_SYSPROP)) {
+ // special case: mgmt address can be specified via either -bmanagement= or -Djboss.bind.address.management=
+ resolvedValue = getOptionFromCommandLine(commandLine, BIND_ADDRESS_MANAGEMENT_OPTION);
+ }
+ if (resolvedValue == null) {
+ resolvedValue = getSystemPropertyFromCommandLine(commandLine, expression);
+ }
+ if (resolvedValue == null) {
+ resolvedValue = fallback;
+ }
+ return resolvedValue;
}
/**
@@ -314,7 +283,17 @@ public class AbstractBaseDiscovery {
protected File getHomeDir(ProcessInfo processInfo) {
String home = getSystemPropertyFromCommandLine(processInfo.getCommandLine(), HOME_DIR_SYSPROP,
processInfo.getEnvironmentVariable("JBOSS_HOME"));
- return new File(FileUtils.getCanonicalPath(home));
+ File homeDir = new File(home);
+ if (!homeDir.isAbsolute()) {
+ if (processInfo.getExecutable() == null) {
+ throw new RuntimeException(HOME_DIR_SYSPROP + " for AS7 process " + processInfo
+ + " is a relative path, and the RHQ Agent process does not have permission to resolve it.");
+ }
+ String cwd = processInfo.getExecutable().getCwd();
+ homeDir = new File(cwd, home);
+ }
+
+ return new File(FileUtils.getCanonicalPath(homeDir.getPath()));
}
protected String determineServerVersionFromHomeDir(String homeDir) {
@@ -356,17 +335,20 @@ public class AbstractBaseDiscovery {
}
}
+ @Nullable
protected static String getSystemPropertyFromCommandLine(String[] commandLine, String systemPropertyName) {
return getSystemPropertyFromCommandLine(commandLine, systemPropertyName, null);
}
+ @Nullable
protected static String getSystemPropertyFromCommandLine(String[] commandLine, String systemPropertyName,
- String defaultValue) {
- for (String arg : commandLine) {
- String prefix = "-D" + systemPropertyName;
- String prefixWithEqualsSign = prefix + "=";
+ String defaultValue) {
+ String prefix = "-D" + systemPropertyName;
+ String prefixWithEqualsSign = prefix + "=";
+ for (String arg : commandLine) {
if (arg.startsWith(prefixWithEqualsSign)) {
- return arg.substring(prefixWithEqualsSign.length());
+ return (prefixWithEqualsSign.length() < arg.length()) ?
+ arg.substring(prefixWithEqualsSign.length()) : "";
} else if (arg.equals(prefix)) {
return "";
}
@@ -374,15 +356,49 @@ public class AbstractBaseDiscovery {
return defaultValue;
}
- protected HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
- for (String line : commandLine) {
- if (line.contains(SOCKET_BINDING_PORT_OFFSET_SYSPROP)) {
- String tmp = line.substring(line.indexOf('=')+1);
- Integer offset = Integer.valueOf(tmp);
- managementPort.port+=offset;
- break;
+ @Nullable
+ protected static String getOptionFromCommandLine(String[] commandLine, AS7CommandLineOption option) {
+ String shortOptionPrefix;
+ String shortOption;
+ if (option.getShortName() != null) {
+ shortOption = "-" + option.getShortName();
+ shortOptionPrefix = shortOption + "=";
+ } else {
+ shortOption = null;
+ shortOptionPrefix = null;
+ }
+ String longOptionPrefix;
+ if (option.getLongName() != null) {
+ longOptionPrefix = "--" + option.getLongName() + "=";
+ } else {
+ longOptionPrefix = null;
+ }
+ for (int i = 0, commandLineLength = commandLine.length; i < commandLineLength; i++) {
+ String arg = commandLine[i];
+ if (option.getShortName() != null) {
+ if (arg.startsWith(shortOptionPrefix)) {
+ return (shortOptionPrefix.length() < arg.length()) ? arg.substring(shortOptionPrefix.length()) : "";
+ } else if (arg.equals(shortOption)) {
+ return (i != (commandLineLength - 1)) ? commandLine[i + 1] : "";
+ }
+ }
+ if (option.getLongName() != null) {
+ if (arg.startsWith(longOptionPrefix)) {
+ return (longOptionPrefix.length() < arg.length()) ? arg.substring(longOptionPrefix.length()) : "";
+ }
}
}
+ // If we reached here, the option wasn't on the command line.
+
+ return null;
+ }
+
+ protected HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
+ String value = getSystemPropertyFromCommandLine(commandLine, SOCKET_BINDING_PORT_OFFSET_SYSPROP);
+ if (value != null) {
+ int offset = Integer.valueOf(value);
+ managementPort.port += offset;
+ }
return managementPort;
}
@@ -412,4 +428,5 @@ public class AbstractBaseDiscovery {
return "HostPort{" + "host='" + host + '\'' + ", port=" + port + ", isLocal=" + isLocal + '}';
}
}
+
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 553075a..06371c6 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -56,7 +56,8 @@ import org.rhq.modules.plugins.jbossas7.json.Result;
* Abstract base discovery component for the two server types - "JBossAS7 Host Controller" and
* "JBossAS7 Standalone Server".
*/
-public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent, ManualAddFacet {
+public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
+ implements ResourceDiscoveryComponent, ManualAddFacet {
private final Log log = LogFactory.getLog(this.getClass());
@@ -64,16 +65,16 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext discoveryContext) throws Exception {
Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
- List<ProcessScanResult> scans = discoveryContext.getAutoDiscoveredProcesses();
- for (ProcessScanResult psr : scans) {
+ List<ProcessScanResult> processScanResults = discoveryContext.getAutoDiscoveredProcesses();
+ for (ProcessScanResult processScanResult : processScanResults) {
try {
- DiscoveredResourceDetails details = buildResourceDetails(discoveryContext, psr);
+ DiscoveredResourceDetails details = buildResourceDetails(discoveryContext, processScanResult);
discoveredResources.add(details);
log.info("Discovered new " + discoveryContext.getResourceType().getName() + " Resource with key ["
+ details.getResourceKey() + "].");
} catch (Exception e) {
- log.error("Discovery for a " + discoveryContext.getResourceType().getName()
- + " Resource failed for process " + psr + ": " + e);
+ log.error("Discovery of a " + discoveryContext.getResourceType().getName()
+ + " Resource failed for " + processScanResult.getProcessInfo() + ".", e);
}
}
@@ -86,16 +87,17 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
// for management port
ProcessInfo process = psr.getProcessInfo();
String[] commandLine = process.getCommandLine();
- String homeDir = getHomeDir(process).getPath();
- JBossProductType productType = JBossProductType.determineJBossProductType(new File(homeDir));
- String version = determineServerVersionFromHomeDir(homeDir);
+ File homeDir = getHomeDir(process);
+ JBossProductType productType = JBossProductType.determineJBossProductType(homeDir);
+ String version = determineServerVersionFromHomeDir(homeDir.getPath());
if (productType != JBossProductType.AS) {
version = productType.SHORT_NAME + " " + version;
}
- File baseDir = getBaseDir(process);
+ File baseDir = getBaseDir(process, homeDir);
String configName = baseDir.getName();
String key = baseDir.getPath();
- readStandaloneOrHostXmlFromFile(getHostXmlFile(process).getPath()); // this sets this.hostXml
+ File configDir = getConfigDir(process, baseDir);
+ readStandaloneOrHostXmlFromFile(getHostXmlFile(process, configDir).getPath()); // this sets this.hostXml
HostPort hostPort = getHostPortFromHostXml();
String name = buildDefaultResourceName(hostPort, configName, productType);
@@ -103,12 +105,12 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
pluginConfig.put(new PropertySimple("homeDir", homeDir));
pluginConfig.put(new PropertySimple("baseDir", baseDir));
- pluginConfig.put(new PropertySimple("configDir", getConfigDir(process)));
+ pluginConfig.put(new PropertySimple("configDir", configDir));
pluginConfig.put(new PropertySimple("startScript", getMode().getStartScript()));
- pluginConfig.put(new PropertySimple("domainHost", findHost(getHostXmlFile(process))));
- fillUserPassFromFile(pluginConfig, getMode(), homeDir);
- String logFile = getLogFile(process).getAbsolutePath();
- initLogEventSourcesConfigProp(logFile, pluginConfig);
+ pluginConfig.put(new PropertySimple("domainHost", findHost(getHostXmlFile(process, configDir))));
+ fillUserPassFromFile(pluginConfig, getMode(), homeDir.getPath());
+ File logFile = getLogFile(getLogDir(process, baseDir));
+ initLogEventSourcesConfigProp(logFile.getPath(), pluginConfig);
HostPort managementHostPort = getManagementPortFromHostXml(commandLine);
pluginConfig.put(new PropertySimple("hostname", managementHostPort.host));
pluginConfig.put(new PropertySimple("port", managementHostPort.port));
@@ -141,41 +143,117 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
pluginConfig, process);
}
- protected File getBaseDir(ProcessInfo process) {
+ protected File getBaseDir(ProcessInfo process, File homeDir) {
String baseDirString = getSystemPropertyFromCommandLine(process.getCommandLine(),
getBaseDirSystemPropertyName());
- File baseDir = (baseDirString != null) ? new File(FileUtils.getCanonicalPath(baseDirString)) :
- new File(getHomeDir(process), getDefaultBaseDirName());
+ File baseDir;
+ if (baseDirString != null) {
+ baseDir = new File(baseDirString);
+ if (!baseDir.isAbsolute()) {
+ if (process.getExecutable() == null) {
+ baseDir = new File(homeDir, baseDirString);
+ if (!baseDir.exists()) {
+ throw new RuntimeException(getBaseDirSystemPropertyName() + " for AS7 process " + process
+ + " is a relative path, and the RHQ Agent process does not have permission to resolve it.");
+ }
+ } else {
+ String cwd = process.getExecutable().getCwd();
+ baseDir = new File(cwd, baseDirString);
+ if (!baseDir.exists()) {
+ baseDir = new File(homeDir, baseDirString);
+ }
+ }
+ }
+ baseDir = new File(FileUtils.getCanonicalPath(baseDir.getPath()));
+ } else {
+ baseDir = new File(homeDir, getDefaultBaseDirName());
+ }
return baseDir;
}
- protected File getConfigDir(ProcessInfo process) {
+ protected File getConfigDir(ProcessInfo process, File baseDir) {
String configDirString = getSystemPropertyFromCommandLine(process.getCommandLine(),
getConfigDirSystemPropertyName());
- File configDir = (configDirString != null) ? new File(FileUtils.getCanonicalPath(configDirString)) :
- new File(getBaseDir(process), getDefaultConfigDirName());
+ File configDir;
+ if (configDirString != null) {
+ configDir = new File(configDirString);
+ if (!configDir.isAbsolute()) {
+ if (process.getExecutable() == null) {
+ throw new RuntimeException(getConfigDirSystemPropertyName() + " for AS7 process " + process
+ + " is a relative path, and the RHQ Agent process does not have permission to resolve it.");
+ }
+ String cwd = process.getExecutable().getCwd();
+ configDir = new File(cwd, configDirString);
+ }
+ configDir = new File(FileUtils.getCanonicalPath(configDir.getPath()));
+ } else {
+ configDir = new File(baseDir, getDefaultConfigDirName());
+ }
return configDir;
}
- protected File getHostXmlFile(ProcessInfo process) {
- return new File(getConfigDir(process), getHostXmlFileName());
+ protected File getLogDir(ProcessInfo process, File baseDir) {
+ String logDirString = getSystemPropertyFromCommandLine(process.getCommandLine(),
+ getLogDirSystemPropertyName());
+ File logDir;
+ if (logDirString != null) {
+ logDir = new File(logDirString);
+ if (!logDir.isAbsolute()) {
+ if (process.getExecutable() == null) {
+ throw new RuntimeException(getLogDirSystemPropertyName() + " for AS7 process " + process
+ + " is a relative path, and the RHQ Agent process does not have permission to resolve it.");
+ }
+ String cwd = process.getExecutable().getCwd();
+ logDir = new File(cwd, logDirString);
+ }
+ logDir = new File(FileUtils.getCanonicalPath(logDir.getPath()));
+ } else {
+ logDir = new File(baseDir, getDefaultLogDirName());
+ }
+ return logDir;
+ }
+
+ // Returns the name of the host config xml file (domain controller) or server config xml file (standalone server),
+ // e.g. "standalone.xml" or "host.xml".
+ protected String getHostXmlFileName(ProcessInfo process) {
+ AS7CommandLineOption hostXmlFileNameOption = getHostXmlFileNameOption();
+ String optionValue = getOptionFromCommandLine(process.getCommandLine(), hostXmlFileNameOption);
+ return (optionValue != null) ? optionValue : getDefaultHostXmlFileName();
+ }
+
+
+ // Returns the host config xml file (domain controller) or server config xml file (standalone server).
+ protected File getHostXmlFile(ProcessInfo process, File configDir) {
+ return new File(configDir, getHostXmlFileName(process));
}
protected String getDefaultConfigDirName() {
return "configuration";
}
+ protected String getDefaultLogDirName() {
+ return "log";
+ }
+
protected abstract AS7Mode getMode();
- protected abstract File getLogFile(ProcessInfo process);
+ protected File getLogFile(File logDir) {
+ return new File(logDir, getLogFileName());
+ }
protected abstract String getBaseDirSystemPropertyName();
protected abstract String getConfigDirSystemPropertyName();
+ protected abstract String getLogDirSystemPropertyName();
+
protected abstract String getDefaultBaseDirName();
- protected abstract String getHostXmlFileName();
+ protected abstract AS7CommandLineOption getHostXmlFileNameOption();
+
+ protected abstract String getDefaultHostXmlFileName();
+
+ protected abstract String getLogFileName();
protected abstract String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType);
@@ -187,20 +265,20 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
ResourceDiscoveryContext context) throws InvalidPluginConfigurationException {
String hostname = pluginConfiguration.getSimpleValue("hostname", null);
- String portS = pluginConfiguration.getSimpleValue("port", null);
+ String portString = pluginConfiguration.getSimpleValue("port", null);
String user = pluginConfiguration.getSimpleValue("user", null);
String pass = pluginConfiguration.getSimpleValue("password", null);
- if (hostname == null || portS == null) {
+ if (hostname == null || portString == null) {
throw new InvalidPluginConfigurationException("Host and port must not be null");
}
- int port = Integer.valueOf(portS);
+ int port = Integer.valueOf(portString);
ProductInfo productInfo = new ProductInfo(hostname, user, pass, port).getFromRemote();
String productName = productInfo.getProductName();
String productVersion = productInfo.getProductVersion();
- String resourceKey = hostname + ":" + portS + ":" + productName;
+ String resourceKey = hostname + ":" + port + ":" + productName;
String description;
if (productName.contains("EAP")) {
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
index 7adbbf3..a4a46df 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
@@ -36,6 +36,9 @@ public class HostControllerDiscovery extends BaseProcessDiscovery {
private static final String DOMAIN_BASE_DIR_SYSPROP = "jboss.domain.base.dir";
private static final String DOMAIN_CONFIG_DIR_SYSPROP = "jboss.domain.config.dir";
+ private static final String DOMAIN_LOG_DIR_SYSPROP = "jboss.domain.log.dir";
+
+ private AS7CommandLineOption HOST_CONFIG_OPTION = new AS7CommandLineOption(null, "host-config");
@Override
protected AS7Mode getMode() {
@@ -53,16 +56,31 @@ public class HostControllerDiscovery extends BaseProcessDiscovery {
}
@Override
+ protected String getLogDirSystemPropertyName() {
+ return DOMAIN_LOG_DIR_SYSPROP;
+ }
+
+ @Override
protected String getDefaultBaseDirName() {
return "domain";
}
@Override
- protected String getHostXmlFileName() {
+ protected AS7CommandLineOption getHostXmlFileNameOption() {
+ return HOST_CONFIG_OPTION;
+ }
+
+ @Override
+ protected String getDefaultHostXmlFileName() {
return "host.xml";
}
@Override
+ protected String getLogFileName() {
+ return "host-controller.log";
+ }
+
+ @Override
protected String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType) {
String suffix = (hostPort.isLocal) ? "Domain Controller" : "Host Controller";
return configName + " " + productType.NAME + " " + suffix;
@@ -76,19 +94,15 @@ public class HostControllerDiscovery extends BaseProcessDiscovery {
}
@Override
- protected File getLogFile(ProcessInfo process) {
- String bootLogFile = getLogFileFromCommandLine(process.getCommandLine());
- return new File(bootLogFile);
- }
-
- @Override
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
ProcessScanResult psr) {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
+ ProcessInfo process = psr.getProcessInfo();
Configuration pluginConfig = details.getPluginConfiguration();
String domainConfig = getServerConfigFromCommandLine(psr.getProcessInfo().getCommandLine(), getMode());
pluginConfig.put(new PropertySimple("domainConfig", domainConfig));
- pluginConfig.put(new PropertySimple("hostConfig", getHostXmlFile(psr.getProcessInfo())));
+ String configDirString = pluginConfig.getSimpleValue("configDir", null);
+ pluginConfig.put(new PropertySimple("hostConfig", getHostXmlFile(process, new File(configDirString))));
return details;
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
index 9854cec..9102b21 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
@@ -36,6 +36,9 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
private static final String SERVER_BASE_DIR_SYSPROP = "jboss.server.base.dir";
private static final String SERVER_CONFIG_DIR_SYSPROP = "jboss.server.config.dir";
+ private static final String SERVER_LOG_DIR_SYSPROP = "jboss.server.log.dir";
+
+ private AS7CommandLineOption SERVER_CONFIG_OPTION = new AS7CommandLineOption('c', "server-config");
@Override
protected AS7Mode getMode() {
@@ -53,16 +56,31 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
}
@Override
+ protected String getLogDirSystemPropertyName() {
+ return SERVER_LOG_DIR_SYSPROP;
+ }
+
+ @Override
protected String getDefaultBaseDirName() {
return "standalone";
}
@Override
- protected String getHostXmlFileName() {
+ protected AS7CommandLineOption getHostXmlFileNameOption() {
+ return SERVER_CONFIG_OPTION;
+ }
+
+ @Override
+ protected String getDefaultHostXmlFileName() {
return "standalone.xml";
}
@Override
+ protected String getLogFileName() {
+ return "server.log";
+ }
+
+ @Override
protected String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType) {
String hostName = findHostName();
StringBuilder name = new StringBuilder();
@@ -79,13 +97,6 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
}
@Override
- protected File getLogFile(ProcessInfo process) {
- String bootLogFile = getLogFileFromCommandLine(process.getCommandLine());
- File logDir = new File(bootLogFile).getParentFile();
- return new File(logDir, "server.log");
- }
-
- @Override
protected HostPort getManagementPortFromHostXml(String[] commandLine) {
HostPort managementPort = super.getManagementPortFromHostXml(commandLine);
if (!managementPort.withOffset) {
@@ -98,8 +109,10 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
ProcessScanResult psr) {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
+ ProcessInfo process = psr.getProcessInfo();
Configuration pluginConfig = details.getPluginConfiguration();
- pluginConfig.put(new PropertySimple("config", getHostXmlFile(psr.getProcessInfo())));
+ String configDirString = pluginConfig.getSimpleValue("configDir", null);
+ pluginConfig.put(new PropertySimple("config", getHostXmlFile(process, new File(configDirString))));
return details;
}
commit f12571b2e6e4d5d17e8fb12a08f2cb781570a271
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Wed Mar 28 11:36:50 2012 -0400
Add some more protection against a null AvailabilityType getting included
in an AvailabilityReport.
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java
index 037fed6..24fdcf5 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AvailabilityExecutor.java
@@ -151,7 +151,7 @@ public class AvailabilityExecutor implements Runnable, Callable<AvailabilityRepo
if (Thread.interrupted()) {
if (log.isDebugEnabled()) {
log.debug("Exception occurred during availability check, but this thread has been interrupted, "
- + "so most likely the plugin container is shutting down: " + e);
+ + "so most likely the plugin container is shutting down: " + e);
}
return availabilityReport;
}
@@ -308,15 +308,18 @@ public class AvailabilityExecutor implements Runnable, Callable<AvailabilityRepo
}
}
}
- if (current == null) {
- current = AvailabilityType.DOWN;
+ }
+ if (null == current) {
+ if (log.isDebugEnabled()) {
+ log.debug("Protecting against null getAvailability(). Setting DOWN to " + resource);
}
+ current = AvailabilityType.DOWN;
}
}
// Add the availability to the report if it changed from its previous state or if this is a full report.
// Update the resource container only if the avail has changed.
- boolean availChanged = (previous == null) || (previous.getAvailabilityType() != current);
+ boolean availChanged = (null != current && (null == previous) || (current != previous.getAvailabilityType()));
if (availChanged || scan.isFull) {
Availability availability;
commit c5451b437c438dd0254524316b845ea2acc98ed2
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Wed Mar 28 09:52:57 2012 -0400
put bz# in warning message
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
index bfbf346..9245d3c 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
@@ -1222,8 +1222,9 @@ public class InventoryManager extends AgentService implements ContainerService,
// TODO REMOVE THIS IF STATEMENT - IT IS JUST FOR TESTING
if (!resource.getChildResources().getClass().getName().contains("Collections$SetFromMap")) {
- new Exception("BAD CHILD SET:" + resource.getChildResources().getClass().getName() + ":"
- + resource.getId() + ":" + resource.getName()).printStackTrace();
+ new Exception("BAD CHILD SET - IF YOU SEE THIS, LOG IT IN BZ 801432:"
+ + resource.getChildResources().getClass().getName() + ":" + resource.getId() + ":"
+ + resource.getName()).printStackTrace();
}
for (Resource child : resource.getChildResources()) {
commit 249e20180843f3d0c6f4ca85edb153e5d91587a6
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed Mar 28 15:29:32 2012 +0200
BZ 805028 - honor the new port-offset attribtute for <socket-binding-group> elements in the AS7 descriptor.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index 8206c61..a7acad9 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2011 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -50,6 +50,7 @@ public class AbstractBaseDiscovery {
static final int DEFAULT_MGMT_PORT = 9990;
private static final String JBOSS_AS_PREFIX = "jboss-as-";
static final String CALL_READ_STANDALONE_OR_HOST_XML_FIRST = "hostXml is null. You need to call 'readStandaloneOrHostXml' first.";
+ private static final String SOCKET_BINDING_PORT_OFFSET_SYSPROP = "jboss.socket.binding.port-offset";
protected Document hostXml;
protected final Log log = LogFactory.getLog(this.getClass());
private static final String JBOSS_EAP_PREFIX = "jboss-eap-";
@@ -108,6 +109,7 @@ public class AbstractBaseDiscovery {
socketBindingName = obtainXmlPropertyViaXPath("//management/management-interfaces/http-interface/socket-binding/@http");
String socketInterface = obtainXmlPropertyViaXPath("//management/management-interfaces/http-interface/socket/@interface");
+ String portOffset = null;
if (!socketInterface.isEmpty()) {
interfaceExpession = obtainXmlPropertyViaXPath("//interfaces/interface[@name='" + socketInterface
@@ -133,6 +135,11 @@ public class AbstractBaseDiscovery {
+ socketBindingName + "']/@port");
String interfaceName = obtainXmlPropertyViaXPath("/server/socket-binding-group/socket-binding[@name='"
+ socketBindingName + "']/@interface");
+ String socketBindingGroupName = "standard-sockets";
+ // /server/socket-binding-group[@name='standard-sockets']/@port-offset
+ String xpathExpression =
+ "/server/socket-binding-group[@name='" + socketBindingGroupName + "']/@port-offset";
+ portOffset = obtainXmlPropertyViaXPath(xpathExpression);
// TODO the next may also be expressed differently
interfaceExpession = obtainXmlPropertyViaXPath("/server/interfaces/interface[@name='" + interfaceName
@@ -149,11 +156,19 @@ public class AbstractBaseDiscovery {
else
hp.host = "localhost"; // Fallback
+ hp.port = 0;
+
if (portString != null && !portString.isEmpty()) {
String tmp = replaceDollarExpression(portString, commandLine, String.valueOf(DEFAULT_MGMT_PORT));
hp.port = Integer.valueOf(tmp);
- } else
- hp.port = DEFAULT_MGMT_PORT; // Fallback to default
+ }
+
+ if (portOffset!=null && !portOffset.isEmpty()) {
+ String tmp = replaceDollarExpression(portOffset, commandLine, "0");
+ Integer offset = Integer.valueOf(tmp);
+ hp.port += offset;
+ hp.withOffset=true;
+ }
return hp;
}
@@ -203,13 +218,17 @@ public class AbstractBaseDiscovery {
ret = commandLine[i + 1]; // -bmanagement 1.2.3.4
break;
}
- } else if (expression.contains("port")) {
+ } else if (expression.equals("jboss.management.http.port")) {
if (line.contains(expression)) {
ret = line.substring(line.indexOf("=") + 1);
break;
}
+ } else if (expression.equals(SOCKET_BINDING_PORT_OFFSET_SYSPROP)) {
+ if (line.contains(expression)) {
+ ret = line.substring(line.indexOf('=')+1);
+ break;
+ }
}
-
}
if (ret == null)
ret = fallback;
@@ -355,6 +374,19 @@ public class AbstractBaseDiscovery {
return defaultValue;
}
+ protected HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
+ for (String line : commandLine) {
+ if (line.contains(SOCKET_BINDING_PORT_OFFSET_SYSPROP)) {
+ String tmp = line.substring(line.indexOf('=')+1);
+ Integer offset = Integer.valueOf(tmp);
+ managementPort.port+=offset;
+ break;
+ }
+ }
+
+ return managementPort;
+ }
+
/**
* Helper class that holds information about the host,port tuple
*/
@@ -362,6 +394,7 @@ public class AbstractBaseDiscovery {
String host;
int port;
boolean isLocal = true;
+ boolean withOffset = false;
public HostPort() {
host = "localhost";
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index c5515f3..553075a 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -58,8 +58,6 @@ import org.rhq.modules.plugins.jbossas7.json.Result;
*/
public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent, ManualAddFacet {
- private static final String SOCKET_BINDING_PORT_OFFSET_SYSPROP = "jboss.socket.binding.port-offset";
-
private final Log log = LogFactory.getLog(this.getClass());
// Auto-discover running AS7 instances.
@@ -180,21 +178,8 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
protected abstract String getHostXmlFileName();
protected abstract String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType);
-
- protected abstract String buildDefaultResourceDescription(HostPort hostPort, JBossProductType productType);
-
- protected HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
- for (String line : commandLine) {
- if (line.contains(SOCKET_BINDING_PORT_OFFSET_SYSPROP)) {
- String tmp = line.substring(line.indexOf('=')+1);
- Integer offset = Integer.valueOf(tmp);
- managementPort.port+=offset;
- break;
- }
- }
- return managementPort;
- }
+ protected abstract String buildDefaultResourceDescription(HostPort hostPort, JBossProductType productType);
// Manually add a (remote) AS7 instance.
@Override
@@ -288,7 +273,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
}
}
- private String findHost(File hostXmlFile) {
+ private String findHost(File hostXmlFile) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String hostName = null;
try {
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
index 32d206b..7adbbf3 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2012 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
index c5ffaac..9854cec 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2012 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -88,14 +88,17 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
@Override
protected HostPort getManagementPortFromHostXml(String[] commandLine) {
HostPort managementPort = super.getManagementPortFromHostXml(commandLine);
- return checkForSocketBindingOffset(managementPort, commandLine);
+ if (!managementPort.withOffset) {
+ managementPort = checkForSocketBindingOffset(managementPort, commandLine);
+ }
+ return managementPort;
}
@Override
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
ProcessScanResult psr) {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
- Configuration pluginConfig = details.getPluginConfiguration();
+ Configuration pluginConfig = details.getPluginConfiguration();
pluginConfig.put(new PropertySimple("config", getHostXmlFile(psr.getProcessInfo())));
return details;
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java
index 85ae619..7c7c70f 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java
@@ -112,6 +112,37 @@ public class XmlFileReadingTest {
}
+ public void testXpath711() throws Exception {
+
+ BaseProcessDiscovery bd = new StandaloneASDiscovery();
+ URL url = getClass().getClassLoader().getResource("standalone711.xml");
+ bd.readStandaloneOrHostXmlFromFile(url.getFile());
+
+ String realm = bd.obtainXmlPropertyViaXPath("//management/management-interfaces/http-interface/@security-realm");
+ assert "ManagementRealm".equals(realm) : "Realm was " + realm;
+ String sbindingRef = bd.obtainXmlPropertyViaXPath(
+ ("//management/management-interfaces/http-interface/socket-binding/@http"));
+ assert "management-http".equals(sbindingRef): "Socketbinding was " + sbindingRef;
+
+ String pathExpr = "/server/socket-binding-group/socket-binding[@name='" + sbindingRef + "']/@port";
+ String port = bd.obtainXmlPropertyViaXPath(pathExpr);
+ assert "${jboss.management.http.port:9990}".equals(port) : "Port was [" + port + "]";
+
+ pathExpr = "/server/socket-binding-group/socket-binding[@name='" + sbindingRef + "']/@interface";
+ String interfName = bd.obtainXmlPropertyViaXPath(pathExpr);
+ assert "management".equals(interfName) : "Interface was " + interfName;
+
+ pathExpr = "/server/interfaces/interface[@name='" + interfName + "']/inet-address/@value";
+ String interfElem = bd.obtainXmlPropertyViaXPath(pathExpr);
+ assert "${jboss.bind.address.management:127.0.0.71}".equals(interfElem) : "InterfElem was " + interfElem;
+
+ String socketBindingGroupName = "standard-sockets";
+ pathExpr = "/server/socket-binding-group[@name='" + socketBindingGroupName + "']/@port-offset";
+ String offsetAttr = bd.obtainXmlPropertyViaXPath(pathExpr);
+ assert "${jboss.socket.binding.port-offset:123}".equals(offsetAttr) : "Port-Offset was " + offsetAttr;
+
+ }
+
public void testGetRealm() throws Exception {
BaseProcessDiscovery bd = new StandaloneASDiscovery();
diff --git a/modules/plugins/jboss-as-7/src/test/resources/standalone711.xml b/modules/plugins/jboss-as-7/src/test/resources/standalone711.xml
new file mode 100644
index 0000000..c3400d1
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/test/resources/standalone711.xml
@@ -0,0 +1,325 @@
+<?xml version='1.0' encoding='UTF-8'?>
+
+<!--
+ ~ RHQ Management Platform
+ ~ Copyright (C) 2005-2012 Red Hat, Inc.
+ ~ All rights reserved.
+ ~
+ ~ This program is free software; you can redistribute it and/or modify
+ ~ it under the terms of the GNU General Public License as published by
+ ~ the Free Software Foundation version 2 of the License.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ ~ GNU General Public License for more details.
+ ~
+ ~ You should have received a copy of the GNU General Public License
+ ~ along with this program; if not, write to the Free Software
+ ~ Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ -->
+
+<server xmlns="urn:jboss:domain:1.2">
+
+ <extensions>
+ <extension module="org.jboss.as.clustering.infinispan"/>
+ <extension module="org.jboss.as.configadmin"/>
+ <extension module="org.jboss.as.connector"/>
+ <extension module="org.jboss.as.deployment-scanner"/>
+ <extension module="org.jboss.as.ee"/>
+ <extension module="org.jboss.as.ejb3"/>
+ <extension module="org.jboss.as.jaxrs"/>
+ <extension module="org.jboss.as.jdr"/>
+ <extension module="org.jboss.as.jmx"/>
+ <extension module="org.jboss.as.jpa"/>
+ <extension module="org.jboss.as.logging"/>
+ <extension module="org.jboss.as.mail"/>
+ <extension module="org.jboss.as.naming"/>
+ <extension module="org.jboss.as.osgi"/>
+ <extension module="org.jboss.as.pojo"/>
+ <extension module="org.jboss.as.remoting"/>
+ <extension module="org.jboss.as.sar"/>
+ <extension module="org.jboss.as.security"/>
+ <extension module="org.jboss.as.threads"/>
+ <extension module="org.jboss.as.transactions"/>
+ <extension module="org.jboss.as.web"/>
+ <extension module="org.jboss.as.webservices"/>
+ <extension module="org.jboss.as.weld"/>
+ </extensions>
+
+ <management>
+ <security-realms>
+ <security-realm name="ManagementRealm">
+ <authentication>
+ <properties path="mgmt-users.properties" relative-to="jboss.server.config.dir"/>
+ </authentication>
+ </security-realm>
+ <security-realm name="ApplicationRealm">
+ <authentication>
+ <properties path="application-users.properties" relative-to="jboss.server.config.dir"/>
+ </authentication>
+ </security-realm>
+ </security-realms>
+ <management-interfaces>
+ <native-interface security-realm="ManagementRealm">
+ <socket-binding native="management-native"/>
+ </native-interface>
+ <http-interface security-realm="ManagementRealm">
+ <socket-binding http="management-http"/>
+ </http-interface>
+ </management-interfaces>
+ </management>
+
+ <profile>
+ <subsystem xmlns="urn:jboss:domain:logging:1.1">
+ <console-handler name="CONSOLE">
+ <level name="INFO"/>
+ <formatter>
+ <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
+ </formatter>
+ </console-handler>
+ <periodic-rotating-file-handler name="FILE">
+ <formatter>
+ <pattern-formatter pattern="%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
+ </formatter>
+ <file relative-to="jboss.server.log.dir" path="server.log"/>
+ <suffix value=".yyyy-MM-dd"/>
+ <append value="true"/>
+ </periodic-rotating-file-handler>
+ <logger category="com.arjuna">
+ <level name="WARN"/>
+ </logger>
+ <logger category="org.apache.tomcat.util.modeler">
+ <level name="WARN"/>
+ </logger>
+ <logger category="sun.rmi">
+ <level name="WARN"/>
+ </logger>
+ <logger category="jacorb">
+ <level name="WARN"/>
+ </logger>
+ <logger category="jacorb.config">
+ <level name="ERROR"/>
+ </logger>
+ <root-logger>
+ <level name="INFO"/>
+ <handlers>
+ <handler name="CONSOLE"/>
+ <handler name="FILE"/>
+ </handlers>
+ </root-logger>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:configadmin:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:datasources:1.0">
+ <datasources>
+ <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
+ <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>
+ <driver>h2</driver>
+ <security>
+ <user-name>sa</user-name>
+ <password>sa</password>
+ </security>
+ </datasource>
+ <drivers>
+ <driver name="h2" module="com.h2database.h2">
+ <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
+ </driver>
+ </drivers>
+ </datasources>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1">
+ <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000"/>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:ee:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:ejb3:1.2">
+ <session-bean>
+ <stateless>
+ <bean-instance-pool-ref pool-name="slsb-strict-max-pool"/>
+ </stateless>
+ <stateful default-access-timeout="5000" cache-ref="simple"/>
+ <singleton default-access-timeout="5000"/>
+ </session-bean>
+ <pools>
+ <bean-instance-pools>
+ <strict-max-pool name="slsb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
+ <strict-max-pool name="mdb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5" instance-acquisition-timeout-unit="MINUTES"/>
+ </bean-instance-pools>
+ </pools>
+ <caches>
+ <cache name="simple" aliases="NoPassivationCache"/>
+ <cache name="passivating" passivation-store-ref="file" aliases="SimpleStatefulCache"/>
+ </caches>
+ <passivation-stores>
+ <file-passivation-store name="file"/>
+ </passivation-stores>
+ <async thread-pool-name="default"/>
+ <timer-service thread-pool-name="default">
+ <data-store path="timer-service-data" relative-to="jboss.server.data.dir"/>
+ </timer-service>
+ <remote connector-ref="remoting-connector" thread-pool-name="default"/>
+ <thread-pools>
+ <thread-pool name="default">
+ <max-threads count="10"/>
+ <keepalive-time time="100" unit="milliseconds"/>
+ </thread-pool>
+ </thread-pools>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:infinispan:1.2" default-cache-container="hibernate">
+ <cache-container name="hibernate" default-cache="local-query">
+ <local-cache name="entity">
+ <transaction mode="NON_XA"/>
+ <eviction strategy="LRU" max-entries="10000"/>
+ <expiration max-idle="100000"/>
+ </local-cache>
+ <local-cache name="local-query">
+ <transaction mode="NONE"/>
+ <eviction strategy="LRU" max-entries="10000"/>
+ <expiration max-idle="100000"/>
+ </local-cache>
+ <local-cache name="timestamps">
+ <transaction mode="NONE"/>
+ <eviction strategy="NONE"/>
+ </local-cache>
+ </cache-container>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:jaxrs:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:jca:1.1">
+ <archive-validation enabled="true" fail-on-error="true" fail-on-warn="false"/>
+ <bean-validation enabled="true"/>
+ <default-workmanager>
+ <short-running-threads>
+ <core-threads count="50"/>
+ <queue-length count="50"/>
+ <max-threads count="50"/>
+ <keepalive-time time="10" unit="seconds"/>
+ </short-running-threads>
+ <long-running-threads>
+ <core-threads count="50"/>
+ <queue-length count="50"/>
+ <max-threads count="50"/>
+ <keepalive-time time="10" unit="seconds"/>
+ </long-running-threads>
+ </default-workmanager>
+ <cached-connection-manager/>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:jdr:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:jmx:1.1">
+ <show-model value="true"/>
+ <remoting-connector/>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:jpa:1.0">
+ <jpa default-datasource=""/>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:mail:1.0">
+ <mail-session jndi-name="java:jboss/mail/Default">
+ <smtp-server outbound-socket-binding-ref="mail-smtp"/>
+ </mail-session>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:naming:1.1"/>
+ <subsystem xmlns="urn:jboss:domain:osgi:1.2" activation="lazy">
+ <properties>
+ <property name="org.osgi.framework.startlevel.beginning">
+ 1
+ </property>
+ </properties>
+ <capabilities>
+ <capability name="javax.servlet.api:v25"/>
+ <capability name="javax.transaction.api"/>
+ <capability name="org.apache.felix.log" startlevel="1"/>
+ <capability name="org.jboss.osgi.logging" startlevel="1"/>
+ <capability name="org.apache.felix.configadmin" startlevel="1"/>
+ <capability name="org.jboss.as.osgi.configadmin" startlevel="1"/>
+ </capabilities>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:pojo:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:remoting:1.1">
+ <connector name="remoting-connector" socket-binding="remoting" security-realm="ApplicationRealm"/>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:resource-adapters:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:sar:1.0"/>
+ <subsystem xmlns="urn:jboss:domain:security:1.1">
+ <security-domains>
+ <security-domain name="other" cache-type="default">
+ <authentication>
+ <login-module code="Remoting" flag="optional">
+ <module-option name="password-stacking" value="useFirstPass"/>
+ </login-module>
+ <login-module code="RealmUsersRoles" flag="required">
+ <module-option name="usersProperties" value="${jboss.server.config.dir}/application-users.properties"/>
+ <module-option name="rolesProperties" value="${jboss.server.config.dir}/application-roles.properties"/>
+ <module-option name="realm" value="ApplicationRealm"/>
+ <module-option name="password-stacking" value="useFirstPass"/>
+ </login-module>
+ </authentication>
+ </security-domain>
+ <security-domain name="jboss-web-policy" cache-type="default">
+ <authorization>
+ <policy-module code="Delegating" flag="required"/>
+ </authorization>
+ </security-domain>
+ <security-domain name="jboss-ejb-policy" cache-type="default">
+ <authorization>
+ <policy-module code="Delegating" flag="required"/>
+ </authorization>
+ </security-domain>
+ </security-domains>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:threads:1.1"/>
+ <subsystem xmlns="urn:jboss:domain:transactions:1.1">
+ <core-environment>
+ <process-id>
+ <uuid/>
+ </process-id>
+ </core-environment>
+ <recovery-environment socket-binding="txn-recovery-environment" status-socket-binding="txn-status-manager"/>
+ <coordinator-environment default-timeout="300"/>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host" native="false">
+ <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
+ <virtual-server name="default-host" enable-welcome-root="true">
+ <alias name="localhost"/>
+ <alias name="example.com"/>
+ </virtual-server>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:webservices:1.1">
+ <modify-wsdl-address>true</modify-wsdl-address>
+ <wsdl-host>${jboss.bind.address:127.0.0.1}</wsdl-host>
+ <endpoint-config name="Standard-Endpoint-Config"/>
+ <endpoint-config name="Recording-Endpoint-Config">
+ <pre-handler-chain name="recording-handlers" protocol-bindings="##SOAP11_HTTP ##SOAP11_HTTP_MTOM ##SOAP12_HTTP ##SOAP12_HTTP_MTOM">
+ <handler name="RecordingHandler" class="org.jboss.ws.common.invocation.RecordingServerHandler"/>
+ </pre-handler-chain>
+ </endpoint-config>
+ </subsystem>
+ <subsystem xmlns="urn:jboss:domain:weld:1.0"/>
+ </profile>
+
+ <interfaces>
+ <interface name="management">
+ <inet-address value="${jboss.bind.address.management:127.0.0.71}"/>
+ </interface>
+ <interface name="public">
+ <inet-address value="${jboss.bind.address:127.0.0.71}"/>
+ </interface>
+ <interface name="unsecure">
+ <inet-address value="${jboss.bind.address.unsecure:127.0.0.1}"/>
+ </interface>
+ </interfaces>
+
+ <socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:123}">
+ <socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}"/>
+ <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
+ <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:19443}"/>
+ <socket-binding name="ajp" port="8009"/>
+ <socket-binding name="http" port="8080"/>
+ <socket-binding name="https" port="8443"/>
+ <socket-binding name="osgi-http" interface="management" port="8090"/>
+ <socket-binding name="remoting" port="4447"/>
+ <socket-binding name="txn-recovery-environment" port="4712"/>
+ <socket-binding name="txn-status-manager" port="4713"/>
+ <outbound-socket-binding name="mail-smtp">
+ <remote-destination host="localhost" port="25"/>
+ </outbound-socket-binding>
+ </socket-binding-group>
+
+</server>
commit 59417ed3ac11e6eeca8df4ecaa46968bdd134e3d
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed Mar 28 12:51:20 2012 +0200
Trigger discovery
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
index d9afd1a..6b90fd8 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
@@ -22,6 +22,7 @@ package org.rhq.modules.plugins.jbossas7.itest.standalone;
import java.util.Iterator;
import org.jetbrains.annotations.NotNull;
+import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.rhq.core.clientapi.agent.PluginContainerException;
@@ -37,6 +38,7 @@ import org.rhq.core.domain.resource.ResourceCategory;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.modules.plugins.jbossas7.itest.AbstractJBossAS7PluginTest;
+import org.rhq.test.arquillian.RunDiscovery;
/**
* Test stuff around socket bindings.
@@ -49,6 +51,11 @@ public class SocketBindingTest extends AbstractJBossAS7PluginTest {
public static final ResourceType RESOURCE_TYPE = new ResourceType("SocketBindingGroup", PLUGIN_NAME, ResourceCategory.SERVICE, null);
private static final String RESOURCE_KEY = "socket-binding-group=standard-sockets";
+ @BeforeClass
+ @RunDiscovery(discoverServices = true)
+ public void doSomeDiscovery() throws Exception {
+ }
+
public void loadBindings() throws Exception {
loadConfig();
commit 51ace66460aa4ae35cf4d65ecfab0f1c1c320a28
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Wed Mar 28 10:57:11 2012 +0200
BZ 802794 - SocketBindingGroups must not be removed/re-added on change. Also add integration tests.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
index 8644b71..68e407c 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
@@ -394,6 +394,9 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
report.addData(data);
}
}
+ else {
+ log.debug("getSKMRequests failed: " + res.getFailureDescription());
+ }
}
super.getValues(report, leftovers);
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 0d2bfe0..1d85bff 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
@@ -2218,21 +2218,21 @@ working area for individual server instances</li></ul>"/>
<operation name="list-proxies" description="Read the list of httpd connected to the node.">
<results>
- <!-- List of proxies the node is connected to. Format (hostname:port) separated with comas.-->
+ <!-- List of proxies the node is connected to. Format (hostname:port) separated with comas.-->
<c:simple-property name="proxy-list" description="List of proxies the node is connected to. Format (hostname:port) separated with comas"/>
</results>
</operation>
<operation name="read-proxies-configuration" description="Send a DUMP to httpd and display the result.">
<results>
- <!-- Result of the DUMP command.-->
+ <!-- Result of the DUMP command.-->
<c:simple-property name="current-proxy-config" description="Result of the DUMP command. Snapshot of httpd/modcluster configuration."/>
</results>
</operation>
<operation name="read-proxies-info" description="Send a INFO to httpd and display the result.">
<results>
- <!-- Result of the INFO command.-->
+ <!-- Result of the INFO command.-->
<c:simple-property name="current-proxy-info" description="Result of the INFO command. Snapshot of httpd/modcluster proxy information."/>
</results>
</operation>
@@ -2309,7 +2309,7 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="ttl" required="false" type="integer" readOnly="false" defaultValue="60" description="Time to live (in seconds) for idle connections above smax"/>
<c:simple-property name="node-timeout" required="false" type="integer" readOnly="false" defaultValue="-1" description="Timeout (in seconds) for proxy connections to a node."/>
<c:simple-property name="balancer" required="false" type="string" readOnly="false" defaultValue="mycluster" description="The balancer name."/>
- <c:simple-property name="domain" required="false" type="string" readOnly="false" description="loadBalancingGroup name."/>
+ <c:simple-property name="domain" required="false" type="string" readOnly="false" description="loadBalancingGroup name."/>
</resource-configuration>
</server>
@@ -2448,7 +2448,7 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="port-offset" readOnly="false" displayName="Port Offset"
description="Offset from standard ports for this group. This is only available in standalone mode"
required="false"/>
- <c:group name="children:socket-binding:name+-" displayName="Individual socket bindings">
+ <c:group name="children:socket-binding:name+" displayName="Individual socket bindings">
<c:list-property name="*" displayName="Bindings">
<c:map-property name="binding">
<c:simple-property name="name" description="The name of the socket. Services which need to access the socket configuration information will find it using this name." readOnly="true"/>
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
new file mode 100644
index 0000000..d9afd1a
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/SocketBindingTest.java
@@ -0,0 +1,210 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+package org.rhq.modules.plugins.jbossas7.itest.standalone;
+
+import java.util.Iterator;
+
+import org.jetbrains.annotations.NotNull;
+import org.testng.annotations.Test;
+
+import org.rhq.core.clientapi.agent.PluginContainerException;
+import org.rhq.core.clientapi.agent.configuration.ConfigurationUpdateRequest;
+import org.rhq.core.clientapi.server.configuration.ConfigurationUpdateResponse;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.Property;
+import org.rhq.core.domain.configuration.PropertyList;
+import org.rhq.core.domain.configuration.PropertyMap;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.ResourceCategory;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pc.inventory.InventoryManager;
+import org.rhq.modules.plugins.jbossas7.itest.AbstractJBossAS7PluginTest;
+
+/**
+ * Test stuff around socket bindings.
+ * This could actually also run for domain mode
+ * @author Heiko W. Rupp
+ */
+@Test(groups = {"integration", "pc", "standalone"}, singleThreaded = true)
+public class SocketBindingTest extends AbstractJBossAS7PluginTest {
+
+ public static final ResourceType RESOURCE_TYPE = new ResourceType("SocketBindingGroup", PLUGIN_NAME, ResourceCategory.SERVICE, null);
+ private static final String RESOURCE_KEY = "socket-binding-group=standard-sockets";
+
+ public void loadBindings() throws Exception {
+
+ loadConfig();
+ }
+
+ public void addBinding() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertyMap map = new PropertyMap("socket-binding=bla");
+ PropertySimple ps = new PropertySimple("name","bla");
+ map.put(ps);
+ ps = new PropertySimple("port",12345);
+ map.put(ps);
+ ps = new PropertySimple("fixed-port",false);
+ map.put(ps);
+ ps = new PropertySimple("multicast-port","${foo.bar.baz:12346}");
+ map.put(ps);
+ PropertyList pl = (PropertyList) configuration.get("*");
+ int count = pl.getList().size();
+ pl.add(map);
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config add resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ pl = (PropertyList) configuration.get("*");
+ assert pl.getList().size() == count+1;
+ }
+
+ public void addModifyBinding() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertyMap map = new PropertyMap("bla2");
+ PropertySimple ps = new PropertySimple("name","bla2");
+ map.put(ps);
+ ps = new PropertySimple("port",12355);
+ map.put(ps);
+ ps = new PropertySimple("fixed-port",false);
+ map.put(ps);
+ ps = new PropertySimple("multicast-port","${foo.bar.baz:12356}");
+ map.put(ps);
+ PropertyList pl = (PropertyList) configuration.get("*");
+ pl.add(map);
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config add resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ map=null;
+ pl = (PropertyList) configuration.get("*");
+ for (Property prop: pl.getList()) {
+ if (!prop.getName().equals("bla2"))
+ continue;
+
+ map = (PropertyMap) prop;
+ }
+ assert map != null : "Did not find 'bla2' in the returned config";
+ map.put(new PropertySimple("port",22355));
+ map.put(new PropertySimple("fixed-port",true));
+ request = new ConfigurationUpdateRequest(2,configuration,getResource().getId());
+ response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config update resulted in this error: " + response.getErrorMessage();
+
+ }
+
+ public void addRemoveBinding() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertyMap map = new PropertyMap("bla3");
+ PropertySimple ps = new PropertySimple("name","bla3");
+ map.put(ps);
+ ps = new PropertySimple("port",12365);
+ map.put(ps);
+ ps = new PropertySimple("fixed-port",false);
+ map.put(ps);
+ ps = new PropertySimple("multicast-port","${foo.bar.baz:12366}");
+ map.put(ps);
+ PropertyList pl = (PropertyList) configuration.get("*");
+ int count = pl.getList().size();
+ pl.add(map);
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Config add resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ pl = (PropertyList) configuration.get("*");
+ assert pl.getList().size() == count+1;
+
+ Iterator<Property> iter = pl.getList().iterator();
+ while (iter.hasNext()) {
+ Property prop = iter.next();
+ if (prop.getName().equals("bla3")) {
+ iter.remove();
+ break;
+ }
+ }
+
+ request = new ConfigurationUpdateRequest(3,configuration,getResource().getId());
+ response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Property removal resulted in this error: " + response.getErrorMessage();
+ }
+
+ /** THIS ONE WILL NOT WORK IN DOMAIN MODE */
+ public void changePortOffset() throws Exception {
+
+ Configuration configuration = loadConfig();
+ PropertySimple ps = configuration.getSimple("port-offset");
+ String original = ps.getStringValue();
+
+ configuration.put(new PropertySimple("port-offset",0));
+
+ ConfigurationUpdateRequest request = new ConfigurationUpdateRequest(1,configuration,getResource().getId());
+ ConfigurationUpdateResponse response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Changing the port-offset resulted in this error: " + response.getErrorMessage();
+
+ configuration = loadConfig();
+ ps = configuration.getSimple("port-offset");
+ assert ps != null;
+ assert ps.getIntegerValue()!=null;
+ assert ps.getIntegerValue()==0;
+
+ configuration.put(new PropertySimple("port-offset",original));
+
+ request = new ConfigurationUpdateRequest(2,configuration,getResource().getId());
+ response = pluginContainer.getConfigurationManager().executeUpdateResourceConfigurationImmediately(request);
+ assert response!=null;
+ assert response.getErrorMessage()==null: "Changing the port-offset back resulted in this error: " + response.getErrorMessage();
+
+ }
+
+
+
+ @NotNull
+ private Configuration loadConfig() throws PluginContainerException {
+ Configuration config = pluginContainer.getConfigurationManager().loadResourceConfiguration(getResource().getId());
+ assert config != null;
+ assert !config.getProperties().isEmpty();
+ return config;
+ }
+
+ private Resource getResource() {
+
+ InventoryManager im = pluginContainer.getInventoryManager();
+ Resource platform = im.getPlatform();
+ Resource server = getResourceByTypeAndKey(platform,StandaloneServerComponentTest.RESOURCE_TYPE,StandaloneServerComponentTest.RESOURCE_KEY);
+ Resource bindings = getResourceByTypeAndKey(server,RESOURCE_TYPE,RESOURCE_KEY);
+ return bindings;
+ }
+
+}
commit 969ed45338179bfc4251ba4387ddf6916214206e
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 19:51:54 2012 -0400
update logic for determining product type - first try to use JBOSS_HOME/bin/product.conf, and if that fails, fall back to looking for substrings in the JBOSS_HOME directory name
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java
index 6002dac..93ce54e 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java
@@ -19,7 +19,9 @@
package org.rhq.modules.plugins.jbossas7;
import java.io.File;
-import java.util.Arrays;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Properties;
/**
* A product based on JBoss 7.x.
@@ -28,19 +30,17 @@ import java.util.Arrays;
*/
public enum JBossProductType {
- AS("AS7", "JBoss AS 7", "JBoss Application Server 7"),
- EAP("EAP6", "JBoss EAP 6", "JBoss Enterprise Application Platform 6"),
- EDG("EDG6", "JBoss EDG 6", "JBoss Enterprise Data Grid 6"),
- EPP("EPP6", "JBoss EAP 6", "JBoss Enterprise Portal Platform 6"),
-// EWP("EWP6", "JBoss EWP 6", "JBoss Enterprise Web Platform 6"),
- SOA("SOA-P6", "JBoss SOA-P 6", "JBoss Enterprise SOA Platform (ESB)");
+ AS("AS", "JBoss AS 7", "JBoss Application Server 7"),
+ EAP("EAP", "JBoss EAP 6", "JBoss Enterprise Application Platform 6"),
+ EDG("EDG", "JBoss EDG 6", "JBoss Enterprise Data Grid 6"),
+ EPP("EPP", "JBoss EAP 6", "JBoss Enterprise Portal Platform 6"),
+// EWP("EWP", "JBoss EWP 6", "JBoss Enterprise Web Platform 6"),
+ SOA("SOA-P", "JBoss SOA-P 6", "JBoss Enterprise SOA Platform (ESB)");
public final String SHORT_NAME;
public final String NAME;
public final String FULL_NAME;
- private static final String EAP_IMPLEMENTATION_TITLE = "JBoss Enterprise Application Platform";
-
JBossProductType(String shortName, String name, String fullName) {
this.SHORT_NAME = shortName;
this.NAME = name;
@@ -55,27 +55,42 @@ public enum JBossProductType {
* @return the product type
*/
public static JBossProductType determineJBossProductType(File homeDir) {
- JBossProductType productType;
- File productDir = new File(homeDir, "modules/org/jboss/as/product");
- if (productDir.exists()) {
+ try {
+ return determineJBossProductTypeViaProductConfFile(homeDir);
+ } catch (Exception e) {
+ // TODO: Log an error.
+ return determineJBossProductTypeViaHomeDirName(homeDir);
+ }
+ }
+
+ private static JBossProductType determineJBossProductTypeViaProductConfFile(File homeDir) throws Exception {
+ JBossProductType productType;
+ File productConfFile = new File(homeDir, "bin/product.conf");
+ if (productConfFile.exists()) {
// It's some product (i.e. not community AS).
- File[] files = productDir.listFiles();
- if (files.length == 0) {
- throw new RuntimeException("Unable to determine product type - [" + productDir
- + "] exists but is empty.");
+ Properties productConfProps = new Properties();
+ FileInputStream inputStream = new FileInputStream(productConfFile);
+ try {
+ productConfProps.load(inputStream);
+ } catch (IOException e) {
+ throw new Exception("Failed to parse " + productConfFile + ".", e);
+ } finally {
+ inputStream.close();
}
- if (files.length > 1) {
- throw new RuntimeException("Unable to determine product type - [" + productDir
- + "] contains multiple product subdirectories: " + Arrays.toString(files));
+ String slot = productConfProps.getProperty("slot", "").trim();
+ if (slot.isEmpty()) {
+ throw new Exception("'slot' property not found in " + productConfFile + ".");
}
- File productTypeDir = files[0];
- String productName = productTypeDir.getName();
- if (productName.equals("eap")) {
+ if (slot.equals("eap")) {
productType = JBossProductType.EAP;
- } else if (productName.equals("edg")) {
+ } else if (slot.equals("edg")) {
productType = JBossProductType.EDG;
+ } else if (slot.equals("epp")) {
+ productType = JBossProductType.EPP;
+ } else if (slot.equals("soa-p")) {
+ productType = JBossProductType.SOA;
} else {
- throw new RuntimeException("Unknown product type: " + productName);
+ throw new RuntimeException("Unknown product type: " + slot);
}
} else {
productType = JBossProductType.AS;
@@ -84,6 +99,26 @@ public enum JBossProductType {
return productType;
}
+ private static JBossProductType determineJBossProductTypeViaHomeDirName(File homeDir) {
+ JBossProductType productType;
+ String homeDirName = homeDir.getName();
+ if (homeDirName.contains("-as-")) {
+ productType = JBossProductType.AS;
+ } else if (homeDirName.contains("-eap-")) {
+ productType = JBossProductType.EAP;
+ } else if (homeDirName.contains("-edg-")) {
+ productType = JBossProductType.EDG;
+ } else if (homeDirName.contains("-epp-")) {
+ productType = JBossProductType.EPP;
+ } else if (homeDirName.contains("soa-p-")) {
+ productType = JBossProductType.SOA;
+ } else {
+ throw new RuntimeException("Failed to determine product type for JBoss product installed at [" + homeDir + "].");
+ }
+
+ return productType;
+ }
+
@Override
public String toString() {
return this.NAME;
commit 891804dc7546780190e63c20b0a73353e4ea1cd9
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 17:09:01 2012 -0400
[BZ 804705] NativeSystemInfo.getOperatingSystemName() now returns "Windows", rather than "Win32" for Windows systems, since "Win32" did not seem like an appropriate value in the case of 64-bit Windows systems (https://bugzilla.redhat.com/show_bug.cgi?id=804705)
diff --git a/modules/core/native-system/src/main/java/org/rhq/core/system/NativeSystemInfo.java b/modules/core/native-system/src/main/java/org/rhq/core/system/NativeSystemInfo.java
index 3c08b51..e7e5f1f 100644
--- a/modules/core/native-system/src/main/java/org/rhq/core/system/NativeSystemInfo.java
+++ b/modules/core/native-system/src/main/java/org/rhq/core/system/NativeSystemInfo.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2008 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -51,12 +51,13 @@ import org.rhq.core.system.pquery.ProcessInfoQuery;
* there are additional platform-specific methods that need to be exposed. Most functionality, however, can be exposed
* via this native superclass implementation.
*
- * <p>This implementation uses SIGAR. To enable debug logging in SIGAR, set the system property "sigar.nativeLogging" or
- * call {@link Sigar#enableLogging(boolean)}.</p>
+ * <p>This implementation uses SIGAR. To enable debug logging in SIGAR, set the system property
+ * <code>sigar.nativeLogging</code> or call {@link Sigar#enableLogging(boolean)}.</p>
*
* @author John Mazzitelli
*/
public class NativeSystemInfo implements SystemInfo {
+
private final Log log = LogFactory.getLog(NativeSystemInfo.class);
private SigarProxy sigar;
@@ -104,7 +105,11 @@ public class NativeSystemInfo implements SystemInfo {
}
public String getOperatingSystemName() {
- return OperatingSystem.getInstance().getName();
+ OperatingSystem os = OperatingSystem.getInstance();
+ // SIGAR returns "Win32" as the OS name for all Windows systems, even 64-bit ones. Work around this by instead
+ // returning "Windows" for all Windows systems, which is more consistent with the UNIX operating systems anyway.
+ // (https://jira.hyperic.com/browse/SIGAR-238)
+ return (OperatingSystem.NAME_WIN32.equals(os.getName()) ? "Windows" : os.getName());
}
public String getOperatingSystemVersion() {
@@ -115,10 +120,10 @@ public class NativeSystemInfo implements SystemInfo {
try {
return sigar.getNetInfo().getHostName();
} catch (Exception e) {
- // For some reason, the native layer failed to get the hostname
- // Let's fallback and ask Java for help. But if that fails, too,
- // let's wrap the native layer's exception since we'll want to
- // see its cause since it'll probably have a more descriptive error message
+ // For some reason, the native layer failed to get the hostname.
+ // Let's fallback and ask Java for help. But if that fails too,
+ // let's wrap the native layer's exception, since we'll want to
+ // see its cause, which will probably have a more descriptive error message.
try {
return InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException uhe) {
@@ -128,7 +133,7 @@ public class NativeSystemInfo implements SystemInfo {
}
public List<NetworkAdapterInfo> getAllNetworkAdapters() throws SystemInfoException {
- ArrayList<NetworkAdapterInfo> adapters = new ArrayList<NetworkAdapterInfo>();
+ List<NetworkAdapterInfo> adapters = new ArrayList<NetworkAdapterInfo>();
try {
String[] interfaceNames = sigar.getNetInterfaceList();
@@ -200,13 +205,12 @@ public class NativeSystemInfo implements SystemInfo {
}
public List<ServiceInfo> getAllServices() throws SystemInfoException {
- throw new UnsupportedOperationException("Cannot get services for this plaform");
+ throw new UnsupportedOperationException("Cannot get services for this platform");
}
public List<ProcessInfo> getAllProcesses() {
ArrayList<ProcessInfo> processes = new ArrayList<ProcessInfo>();
long[] pids = null;
- final int timeout = 2 * 60 * 1000; // 2 minutes
log.debug("Retrieving PIDs of all running processes...");
long startTime = System.currentTimeMillis();
@@ -238,10 +242,7 @@ public class NativeSystemInfo implements SystemInfo {
}
public ProcessInfo getThisProcess() {
- long self;
-
- self = sigar.getPid();
-
+ long self = sigar.getPid();
ProcessInfo info = new ProcessInfo(self);
return info;
}
@@ -269,7 +270,6 @@ public class NativeSystemInfo implements SystemInfo {
}
public Swap getSwapInfo() {
-
try {
// Removed this check since http://jira.hyperic.com/browse/SIGAR-112 is fixed.
/*
@@ -341,7 +341,7 @@ public class NativeSystemInfo implements SystemInfo {
}
public String getSystemArchitecture() {
- OperatingSystem op = OperatingSystem.getInstance();
+ OperatingSystem op = OperatingSystem.getInstance();
return op.getArch();
}
@@ -352,4 +352,5 @@ public class NativeSystemInfo implements SystemInfo {
public NativeSystemInfo() {
this.sigar = SigarAccess.getSigar();
}
+
}
\ No newline at end of file
diff --git a/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/WindowsPlatformComponent.java b/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/WindowsPlatformComponent.java
index aa8d2e8..f1229c3 100644
--- a/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/WindowsPlatformComponent.java
+++ b/modules/plugins/platform/src/main/java/org/rhq/plugins/platform/WindowsPlatformComponent.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2011 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -37,8 +37,6 @@ import org.rhq.core.domain.content.transfer.DeployPackageStep;
import org.rhq.core.domain.content.transfer.DeployPackagesResponse;
import org.rhq.core.domain.content.transfer.RemovePackagesResponse;
import org.rhq.core.domain.content.transfer.ResourcePackageDetails;
-import org.rhq.core.domain.measurement.MeasurementDataTrait;
-import org.rhq.core.domain.measurement.MeasurementScheduleRequest;
import org.rhq.core.pluginapi.content.ContentFacet;
import org.rhq.core.pluginapi.content.ContentServices;
import org.rhq.core.pluginapi.inventory.ResourceContext;
@@ -50,8 +48,6 @@ import org.rhq.plugins.platform.win.WindowsSoftwareDelegate;
*/
public class WindowsPlatformComponent extends PlatformComponent implements ContentFacet {
- private static final String OS_NAME_WIN32 = "Win32";
- private static final String OS_NAME_WIN64 = "Win64";
private final Log log = LogFactory.getLog(WindowsPlatformComponent.class);
private Win32EventLogDelegate eventLogDelegate;
@@ -70,7 +66,7 @@ public class WindowsPlatformComponent extends PlatformComponent implements Conte
if (eventLogDelegate != null) {
try {
eventLogDelegate.close();
- } catch (Throwable t2) {
+ } catch (Throwable ignore) {
} finally {
eventLogDelegate = null;
}
@@ -119,17 +115,4 @@ public class WindowsPlatformComponent extends PlatformComponent implements Conte
return null;
}
- @Override
- protected MeasurementDataTrait getMeasurementDataTrait(MeasurementScheduleRequest request) {
- MeasurementDataTrait trait = super.getMeasurementDataTrait(request);
- // SIGAR returns "Win32" as the OS name for all Windows systems, even 64-bit ones, so add some special code
- // to instead return "Win64" for 64-bit systems.
- if (trait.getName().equals(TRAIT_OSNAME) && trait.getValue().equals(OS_NAME_WIN32)) {
- if ("x64".equals(getSysinfo().getSystemArchitecture())) {
- trait.setValue(OS_NAME_WIN64);
- }
- }
- return trait;
- }
-
}
commit d4e2534409a75f4a715eec487a3a4eef90b42b94
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Tue Mar 27 16:53:53 2012 -0400
[BZ 801432][BZ 807465] this is just test code to see if we can catch the concurrent mod exception. we must remove this code before release
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
index 1310141..bfbf346 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/InventoryManager.java
@@ -1220,6 +1220,12 @@ public class InventoryManager extends AgentService implements ContainerService,
// recursively, but we need to do this now to ensure everything is stopped prior to removing them from inventory
deactivateResource(resource);
+ // TODO REMOVE THIS IF STATEMENT - IT IS JUST FOR TESTING
+ if (!resource.getChildResources().getClass().getName().contains("Collections$SetFromMap")) {
+ new Exception("BAD CHILD SET:" + resource.getChildResources().getClass().getName() + ":"
+ + resource.getId() + ":" + resource.getName()).printStackTrace();
+ }
+
for (Resource child : resource.getChildResources()) {
scanIsNeeded |= removeResourceAndIndicateIfScanIsNeeded(child);
}
commit 15b3b6b85685b52aad2a23abf392accac15a7110
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 15:51:47 2012 -0400
add support for spawning AS7 instances - either standalone servers or host controllers
diff --git a/etc/scripts/jboss-as-spawn.sh b/etc/scripts/jboss-as-spawn.sh
index 1174707..c1fe8ef 100755
--- a/etc/scripts/jboss-as-spawn.sh
+++ b/etc/scripts/jboss-as-spawn.sh
@@ -2,36 +2,105 @@
######### begin config ##########
-# the number of instances to start
-INSTANCES=5
-
# the JBoss AS home directory
-JBOSS_HOME=${HOME}/Applications/jboss-eap-5.1.2/jboss-as
+#JBOSS_HOME=${HOME}/Applications/jboss-as-7.1.1.Final
-# the name of the config to be cloned
-JBOSS_CONFIG=production
+# the name of the config to be cloned
+# (e.g. for AS7, "standalone" or "domain"; for other AS versions, "default" or "all")
+#JBOSS_CONFIG=standalone
+
+# the number of instances to start
+#JBOSS_INSTANCES=1
# options to pass to the JBoss AS JVM
-JAVA_OPTS="-Xms200M -Xmx400M -XX:MaxPermSize=150M -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.lang.ClassLoader.allowArraySyntax=true"
+#JAVA_OPTS="-Xms200M -Xmx400M -XX:MaxPermSize=150M -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.lang.ClassLoader.allowArraySyntax=true -Djava.net.preferIPv4Stack=true"
########## end config ###########
+if [ -z "${JBOSS_HOME}" ]; then
+ echo "The 'JBOSS_HOME' variable must be set to the JBoss install dir you want to spawn from." >&2
+ exit 1
+fi
+
+if [ -z "${JBOSS_CONFIG}" ]; then
+ echo "The 'JBOSS_CONFIG' variable must be set to the name of the JBoss config you want to spawn from." >&2
+ exit 1
+fi
+
+if [ -z "${JBOSS_INSTANCES}" ]; then
+ echo "The 'JBOSS_INSTANCES' variable must be set to the number of JBoss instances you want to spawn." >&2
+ exit 1
+fi
+
+if [ -z "${JAVA_OPTS}" ]; then
+ JAVA_OPTS="-Xms200M -Xmx400M -XX:MaxPermSize=150M -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dsun.lang.ClassLoader.allowArraySyntax=true -Djava.net.preferIPv4Stack=true"
+fi
+
echo "JBOSS_HOME=${JBOSS_HOME}"
echo "JAVA_OPTS=${JAVA_OPTS}"
# export these, since they are used by the forked run.sh processes.
export JBOSS_HOME JAVA_OPTS
-cd "${JBOSS_HOME}"
+if [ -f "${JBOSS_HOME}/jboss-modules.jar" ]; then
+ AS7=1
+ SERVER_BASE_DIR="${JBOSS_HOME}"
+else
+ AS7=
+ SERVER_BASE_DIR="${JBOSS_HOME}/server"
+ OCTET=1
+fi
+
+JBOSS_CONFIG_DIR="${SERVER_BASE_DIR}/${JBOSS_CONFIG}"
+if [ ! -d "${JBOSS_CONFIG_DIR}" ]; then
+ echo "Invalid config name '${JBOSS_CONFIG}' - ${JBOSS_CONFIG_DIR} does not exist." >&2
+ exit 1
+fi
+
+if [ -n "${AS7}" ]; then
+ if [ -f "${JBOSS_CONFIG_DIR}/configuration/standalone.xml" ]; then
+ AS7_STANDALONE=1
+ CONFIG_FILE="${JBOSS_CONFIG_DIR}/configuration/standalone.xml"
+ OCTET=2
+ elif [ -f "${JBOSS_CONFIG_DIR}/configuration/host.xml" ]; then
+ AS7_STANDALONE=
+ CONFIG_FILE="${JBOSS_CONFIG_DIR}/configuration/host.xml"
+ OCTET=3
+ else
+ echo "AS7 config file not found." >&2
+ exit 1
+ fi
+fi
+
for (( i = 1 ; i <= ${INSTANCES}; i++ )); do
- JBOSS_CONFIG_COPY="${JBOSS_CONFIG}${i}"
- if [ ! -d "server/${JBOSS_CONFIG_COPY}" ]; then
- echo "Creating new config dir '${JBOSS_HOME}/server/${JBOSS_CONFIG_COPY}'..."
- cp -pr server/${JBOSS_CONFIG} server/${JBOSS_CONFIG_COPY}
- ( cd server/${JBOSS_CONFIG_COPY} ; rm -rf data log tmp work )
+ CONFIG_DIR_NAME="${JBOSS_CONFIG}${i}"
+ CONFIG_DIR="${SERVER_BASE_DIR}/${CONFIG_DIR_NAME}"
+ if [ ! -d "${CONFIG_DIR}" ]; then
+ echo "Creating new config dir '${CONFIG_DIR}'..."
+ cp -pr "${SERVER_BASE_DIR}/${JBOSS_CONFIG}" "${CONFIG_DIR}"
+ ( cd "${CONFIG_DIR}" ; rm -rf data log tmp work )
+ if [ -n "${AS7}" ]; then
+ sed -in '{s/<inet-address /<loopback-address /}' "${CONFIG_FILE}"
+ fi
+ fi
+ BIND_ADDRESS="127.${OCTET}.0.${i}"
+
+ if wget -q -P /tmp http://${BIND_ADDRESS}:8080/; then
+ echo "Not starting AS instance with config '${CONFIG_DIR_NAME}' and bind address '${BIND_ADDRESS}', since an AS instance is already bound to ${BIND_ADDRESS}."
+ continue
+ fi
+
+ if [ -n "${AS7}" ]; then
+ if [ -n "${AS7_STANDALONE}" ]; then
+ echo "Starting AS7 standalone instance with config '${CONFIG_DIR_NAME}' and bind address '${BIND_ADDRESS}'..."
+ nohup $JBOSS_HOME/bin/standalone.sh -Djboss.server.base.dir=${CONFIG_DIR} -b=${BIND_ADDRESS} -bmanagement=${BIND_ADDRESS} -bunsecure=${BIND_ADDRESS} >${JBOSS_HOME}/bin/${CONFIG_DIR_NAME}.out 2>&1 &
+ else
+ echo "Starting AS7 host controller instance with config '${CONFIG_DIR_NAME}' and bind address '${BIND_ADDRESS}'..."
+ nohup $JBOSS_HOME/bin/domain.sh -Djboss.domain.base.dir=${CONFIG_DIR} -b=${BIND_ADDRESS} -bmanagement=${BIND_ADDRESS} -bunsecure=${BIND_ADDRESS} --pc-address=${BIND_ADDRESS} >${JBOSS_HOME}/bin/${CONFIG_DIR_NAME}.out 2>&1 &
+ fi
+ else
+ echo "Starting AS instance with config '${CONFIG_DIR_NAME}' and bind address '${BIND_ADDRESS}'..."
+ nohup $JBOSS_HOME/bin/run.sh -c ${CONFIG_DIR} -b ${BIND_ADDRESS} >$JBOSS_HOME/bin/${CONFIG_DIR_NAME}.out 2>&1 &
fi
- BIND_ADDRESS="127.0.0.$(($i + 1))"
- echo "Starting instance with config '${JBOSS_CONFIG_COPY}' and bind address '${BIND_ADDRESS}'..."
- nohup $JBOSS_HOME/bin/run.sh -c ${JBOSS_CONFIG_COPY} -b ${BIND_ADDRESS} >$JBOSS_HOME/bin/${JBOSS_CONFIG_COPY}.out 2>&1 &
done
commit d40e64950c325f895a9da346002941e515a7dbea
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 14:27:40 2012 -0400
make the homeDir plugin config prop optional; add a JBossProductType enum and some provisional code for determining the product type
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index c382a28..c5515f3 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -58,12 +58,6 @@ import org.rhq.modules.plugins.jbossas7.json.Result;
*/
public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent, ManualAddFacet {
- protected static final String JBOSS_EAP_6 = "JBoss Enterprise Application Platform 6";
- protected static final String JBOSS_EDG_6 = "JBoss Enterprise Data Grid 6";
- protected static final String JBOSS_EPP_6 = "JBoss Enterprise Portal Platform 6";
- protected static final String JBOSS_SOA_6 = "JBoss Service Oriented Architecture Platform 6";
- protected static final String AS7 = "AS7";
-
private static final String SOCKET_BINDING_PORT_OFFSET_SYSPROP = "jboss.socket.binding.port-offset";
private final Log log = LogFactory.getLog(this.getClass());
@@ -80,7 +74,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
log.info("Discovered new " + discoveryContext.getResourceType().getName() + " Resource with key ["
+ details.getResourceKey() + "].");
} catch (Exception e) {
- log.warn("Discovery for a " + discoveryContext.getResourceType().getName()
+ log.error("Discovery for a " + discoveryContext.getResourceType().getName()
+ " Resource failed for process " + psr + ": " + e);
}
}
@@ -95,34 +89,19 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
ProcessInfo process = psr.getProcessInfo();
String[] commandLine = process.getCommandLine();
String homeDir = getHomeDir(process).getPath();
+ JBossProductType productType = JBossProductType.determineJBossProductType(new File(homeDir));
String version = determineServerVersionFromHomeDir(homeDir);
-
+ if (productType != JBossProductType.AS) {
+ version = productType.SHORT_NAME + " " + version;
+ }
File baseDir = getBaseDir(process);
String configName = baseDir.getName();
String key = baseDir.getPath();
readStandaloneOrHostXmlFromFile(getHostXmlFile(process).getPath()); // this sets this.hostXml
HostPort hostPort = getHostPortFromHostXml();
- // TODO: Move this stuff to a ProductType enum.
- String productTypeName;
- String productTypePrefix;
- if (homeDir.contains("eap")) {
- productTypeName = JBOSS_EAP_6;
- productTypePrefix = EAP;
- } else if (homeDir.contains("edg")) {
- productTypeName = JBOSS_EDG_6;
- productTypePrefix = JDG;
- } else {
- productTypeName = AS7;
- productTypePrefix = null;
- }
-
- String name = buildDefaultResourceName(hostPort, configName, productTypeName);
- String description = buildDefaultResourceDescription(hostPort, productTypeName);
- if (productTypePrefix != null) {
- name = productTypePrefix + " " + name;
- version = productTypePrefix + " " + version;
- }
+ String name = buildDefaultResourceName(hostPort, configName, productType);
+ String description = buildDefaultResourceDescription(hostPort, productType);
pluginConfig.put(new PropertySimple("homeDir", homeDir));
pluginConfig.put(new PropertySimple("baseDir", baseDir));
@@ -143,8 +122,6 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
if (productInfo.fromRemote) {
version = productInfo.productName + " " + productInfo.productVersion;
name = productInfo.productName + " " + productInfo.serverName;
- String tmp = getServerDescr(productInfo.getProductName());
- description = "Standalone " + tmp + " server";
}
// String javaClazz = psr.getProcessInfo().getName();
@@ -202,9 +179,9 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
protected abstract String getHostXmlFileName();
- protected abstract String buildDefaultResourceName(HostPort hostPort, String configName, String productTypeName);
+ protected abstract String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType);
- protected abstract String buildDefaultResourceDescription(HostPort hostPort, String productTypeName);
+ protected abstract String buildDefaultResourceDescription(HostPort hostPort, JBossProductType productType);
protected HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
for (String line : commandLine) {
@@ -219,19 +196,6 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
return managementPort;
}
- // TODO: Move this to a ProductType enum.
- private String getServerDescr(String productName) {
- if (productName.equals("EAP"))
- return JBOSS_EAP_6;
- if (productName.equals("EDG"))
- return JBOSS_EDG_6;
- if (productName.equals("SOA"))
- return JBOSS_SOA_6;
- if (productName.equals("EPP"))
- return JBOSS_EPP_6;
- return AS7;
- }
-
// Manually add a (remote) AS7 instance.
@Override
public DiscoveredResourceDetails discoverResource(Configuration pluginConfiguration,
@@ -253,14 +217,14 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery impleme
String resourceKey = hostname + ":" + portS + ":" + productName;
- // TODO: Move this stuff to a ProductType enum.
String description;
if (productName.contains("EAP")) {
- description = "Standalone JBoss Enterprise Application Platform server";
+ description = "Standalone" + JBossProductType.EAP.FULL_NAME + " server";
} else if (productName.contains("EDG")) {
- description = "Standalone JBoss Enterprise DataGrid server";
- } else
+ description = "Standalone" + JBossProductType.EDG.FULL_NAME + " server";
+ } else {
description = context.getResourceType().getDescription();
+ }
pluginConfiguration.put(new PropertySimple("manuallyAdded", true));
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
index c3acc94..32d206b 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
@@ -63,16 +63,16 @@ public class HostControllerDiscovery extends BaseProcessDiscovery {
}
@Override
- protected String buildDefaultResourceName(HostPort hostPort, String configName, String productTypeName) {
+ protected String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType) {
String suffix = (hostPort.isLocal) ? "Domain Controller" : "Host Controller";
- return configName + " " + productTypeName + " " + suffix;
+ return configName + " " + productType.NAME + " " + suffix;
}
@Override
- protected String buildDefaultResourceDescription(HostPort hostPort, String productTypeName) {
+ protected String buildDefaultResourceDescription(HostPort hostPort, JBossProductType productType) {
String prefix = (hostPort.isLocal) ? "Domain controller" : "Host controller";
String suffix = (hostPort.isLocal) ? "domain" : "host";
- return prefix + " for a " + productTypeName + " " + suffix;
+ return prefix + " for a " + productType.FULL_NAME + " " + suffix;
}
@Override
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java
new file mode 100644
index 0000000..6002dac
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java
@@ -0,0 +1,92 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.modules.plugins.jbossas7;
+
+import java.io.File;
+import java.util.Arrays;
+
+/**
+ * A product based on JBoss 7.x.
+ *
+ * @author Ian Springer
+ */
+public enum JBossProductType {
+
+ AS("AS7", "JBoss AS 7", "JBoss Application Server 7"),
+ EAP("EAP6", "JBoss EAP 6", "JBoss Enterprise Application Platform 6"),
+ EDG("EDG6", "JBoss EDG 6", "JBoss Enterprise Data Grid 6"),
+ EPP("EPP6", "JBoss EAP 6", "JBoss Enterprise Portal Platform 6"),
+// EWP("EWP6", "JBoss EWP 6", "JBoss Enterprise Web Platform 6"),
+ SOA("SOA-P6", "JBoss SOA-P 6", "JBoss Enterprise SOA Platform (ESB)");
+
+ public final String SHORT_NAME;
+ public final String NAME;
+ public final String FULL_NAME;
+
+ private static final String EAP_IMPLEMENTATION_TITLE = "JBoss Enterprise Application Platform";
+
+ JBossProductType(String shortName, String name, String fullName) {
+ this.SHORT_NAME = shortName;
+ this.NAME = name;
+ this.FULL_NAME = fullName;
+ }
+
+ /**
+ * Determines the product type of a JBoss product installation.
+ *
+ * @param homeDir the JBoss product installation directory (e.g. /opt/jboss-as-7.1.1.Final)
+ *
+ * @return the product type
+ */
+ public static JBossProductType determineJBossProductType(File homeDir) {
+ JBossProductType productType;
+ File productDir = new File(homeDir, "modules/org/jboss/as/product");
+ if (productDir.exists()) {
+ // It's some product (i.e. not community AS).
+ File[] files = productDir.listFiles();
+ if (files.length == 0) {
+ throw new RuntimeException("Unable to determine product type - [" + productDir
+ + "] exists but is empty.");
+ }
+ if (files.length > 1) {
+ throw new RuntimeException("Unable to determine product type - [" + productDir
+ + "] contains multiple product subdirectories: " + Arrays.toString(files));
+ }
+ File productTypeDir = files[0];
+ String productName = productTypeDir.getName();
+ if (productName.equals("eap")) {
+ productType = JBossProductType.EAP;
+ } else if (productName.equals("edg")) {
+ productType = JBossProductType.EDG;
+ } else {
+ throw new RuntimeException("Unknown product type: " + productName);
+ }
+ } else {
+ productType = JBossProductType.AS;
+ }
+
+ return productType;
+ }
+
+ @Override
+ public String toString() {
+ return this.NAME;
+ }
+
+}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
index 8c4f9e7..c5ffaac 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
@@ -63,14 +63,19 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
}
@Override
- protected String buildDefaultResourceName(HostPort hostPort, String configName, String productTypeName) {
+ protected String buildDefaultResourceName(HostPort hostPort, String configName, JBossProductType productType) {
String hostName = findHostName();
- return (hostName == null || hostName.isEmpty()) ? configName : configName + " (" + hostName + ")";
+ StringBuilder name = new StringBuilder();
+ name.append(configName).append(" ").append(productType.SHORT_NAME);
+ if ((hostName != null) && !hostName.isEmpty()) {
+ name.append(" (").append(hostName).append(")");
+ }
+ return name.toString();
}
@Override
- protected String buildDefaultResourceDescription(HostPort hostPort, String productTypeName) {
- return "Standalone " + productTypeName + " server";
+ protected String buildDefaultResourceDescription(HostPort hostPort, JBossProductType productType) {
+ return "Standalone " + productType.FULL_NAME + " server";
}
@Override
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 6ad5105..0d2bfe0 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
@@ -73,7 +73,7 @@
<c:simple-property name="password" type="password" default="rhqadmin" description="Password for the management user" required="false"/>
<c:simple-property name="domainConfig" type="string" default="domain.xml" description="Running configuration (domain part)" displayName="Domain Configuration"/>
<c:simple-property name="hostConfig" type="string" default="host.xml" description="Running configuration (host part)" displayName="Host Configuration"/>
- <c:simple-property name="homeDir" type="file" description="Root directory of the server installation" displayName="Home Directory" readOnly="true" required="true"/>
+ <c:simple-property name="homeDir" type="file" description="Root directory of the server installation" displayName="Home Directory" readOnly="true" required="false"/>
<c:simple-property name="baseDir" type="file" description="Base directory for server content" displayName="Base Directory" readOnly="true" required="false"/>
<c:simple-property name="configDir" type="file" description="Base configuration directory" displayName="Configuration Directory" readOnly="true" required="false"/>
<c:simple-property name="startScript" type="file" default="bin/domain.sh" description="Script used to start the server. If the path is not absolute, it is relative to the base directory"/>
@@ -371,7 +371,7 @@
<c:simple-property name="user" default="rhqadmin" type="string" description="Management user for a secured AS" required="false"/>
<c:simple-property name="password" default="rhqadmin" type="password" description="Password for the management user" required="false"/>
<c:simple-property name="config" type="string" default="standalone.xml" description="Running configuration" displayName="Configuration"/>
- <c:simple-property name="homeDir" type="file" description="Root directory of the server installation" displayName="Home Directory" readOnly="true" required="true"/>
+ <c:simple-property name="homeDir" type="file" description="Root directory of the server installation" displayName="Home Directory" readOnly="true" required="false"/>
<c:simple-property name="baseDir" type="file" description="Base directory for server content" displayName="Base Directory" readOnly="true" required="false"/>
<c:simple-property name="configDir" type="file" description="Base configuration directory" displayName="Configuration Directory" readOnly="true" required="false"/>
<c:simple-property name="startScript" type="file" default="bin/standalone.sh" description="Script used to start the server. If the path is not absolute, it is relative to the base directory"/>
commit 8ffe2a02a8a8fb6b12e78ea02b3c4ee588c82fd7
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Tue Mar 27 14:19:15 2012 -0400
[Bug 805210 - Group view errors]
I couldn't reproduce the issue directly but I did find a few problems in
the portlet which I fixed here. I think it's likely that the problem
will be solved by these fixes. Primarily, it adds support in this portlet
and others to better handle having all of the enum filter values (in this
case the operation status enums) unset. Also, changes in config were not
being applied to the current instantiation of the portlet.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java
index c826557..fe19915 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupConfigurationUpdatesPortlet.java
@@ -23,7 +23,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
-import java.util.logging.Logger;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
@@ -213,7 +212,7 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement
updatedConfig);
//persist and reload portlet
- storedPortlet.setConfiguration(portletConfig);
+ storedPortlet.setConfiguration(updatedConfig);
configure(portletWindow, storedPortlet);
refresh();
}
@@ -301,7 +300,7 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement
@Override
public void onFailure(Throwable caught) {
Log.debug("Error retrieving resource group composite for group [" + context.getGroupId() + "]:"
- + caught.getMessage());
+ + caught.getMessage());
currentlyLoading = false;
}
@@ -457,8 +456,8 @@ public class GroupConfigurationUpdatesPortlet extends LocatableVLayout implement
int lastN = property.getIntegerValue();
property = portletConfig.getSimple(Constant.METRIC_RANGE_UNIT);
int lastUnits = property.getIntegerValue();
- ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, Integer
- .valueOf(lastUnits));
+ ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN,
+ Integer.valueOf(lastUnits));
criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0)));
criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1)));
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java
index f717db3..7bb6d08 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/groups/GroupOperationsPortlet.java
@@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.logging.Logger;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.Criteria;
@@ -158,7 +157,7 @@ public class GroupOperationsPortlet extends LocatableVLayout implements CustomSe
@Override
public void onFailure(Throwable caught) {
Log.debug("Error retrieving resource group composite for group [" + groupId + "]:"
- + caught.getMessage());
+ + caught.getMessage());
currentlyRefreshing = false;
}
@@ -282,7 +281,7 @@ public class GroupOperationsPortlet extends LocatableVLayout implements CustomSe
storedPortlet.setConfiguration(updatedConfig);
configure(portletWindow, storedPortlet);
//resynch the config object in the datasource
- groupOperations.setDatasource(new GroupOperationsCriteriaDataSource(portletConfig));
+ ((GroupOperationsCriteriaDataSource) groupOperations.getDataSource()).setPortletConfig(updatedConfig);
//apply latest settings to the visible result set
refresh();
}
@@ -394,11 +393,19 @@ class GroupOperationsCriteriaHistoryListView extends GroupOperationHistoryListVi
*/
class GroupOperationsCriteriaDataSource extends GroupOperationHistoryDataSource {
+ private Configuration portletConfig;
+
public GroupOperationsCriteriaDataSource(Configuration portletConfig) {
this.portletConfig = portletConfig;
}
- private Configuration portletConfig;
+ public Configuration getPortletConfig() {
+ return portletConfig;
+ }
+
+ public void setPortletConfig(Configuration portletConfig) {
+ this.portletConfig = portletConfig;
+ }
@Override
protected void executeFetch(final DSRequest request, final DSResponse response,
@@ -469,8 +476,8 @@ class GroupOperationsCriteriaDataSource extends GroupOperationHistoryDataSource
int lastN = property.getIntegerValue();
property = portletConfig.getSimple(Constant.METRIC_RANGE_UNIT);
int lastUnits = property.getIntegerValue();
- ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, Integer
- .valueOf(lastUnits));
+ ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN,
+ Integer.valueOf(lastUnits));
criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0)));
criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1)));
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java
index 9be65b5..f0c7af2 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/alerts/AbstractRecentAlertsPortlet.java
@@ -194,7 +194,8 @@ public abstract class AbstractRecentAlertsPortlet extends AlertHistoryView imple
@Override
public void onSubmitValues(SubmitValuesEvent event) {
// alert severity
- String selectedValue = alertPrioritySelector.getValue().toString();
+ String selectedValue = (null == alertPrioritySelector.getValue()) ? "" : alertPrioritySelector
+ .getValue().toString();
if ((selectedValue.trim().isEmpty())
|| (selectedValue.split(",").length == AlertPriority.values().length)) {
// no severity filter
@@ -227,12 +228,12 @@ public abstract class AbstractRecentAlertsPortlet extends AlertHistoryView imple
return customSettingsForm;
}
- /**
- * Takes the current value of the widget and persists it into the configuration object passed in.
- *
- * @param measurementRangeEditor metric range editor widget
- * @param portletConfig - the config to be updated
- */
+ /**
+ * Takes the current value of the widget and persists it into the configuration object passed in.
+ *
+ * @param measurementRangeEditor metric range editor widget
+ * @param portletConfig - the config to be updated
+ */
private void saveMeasurementRangeEditorSettings(final CustomConfigMeasurementRangeEditor measurementRangeEditor,
Configuration portletConfig) {
String selectedValue;
@@ -269,8 +270,9 @@ public abstract class AbstractRecentAlertsPortlet extends AlertHistoryView imple
} else {//if disabled, reset time defaults
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE_ENABLE, false));
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE_BEGIN_END_FLAG, false));
- List<Long> rangeArray = MeasurementUtility.calculateTimeFrame(Integer
- .valueOf(Constant.METRIC_RANGE_LASTN_DEFAULT), Integer.valueOf(Constant.METRIC_RANGE_UNIT_DEFAULT));
+ List<Long> rangeArray = MeasurementUtility.calculateTimeFrame(
+ Integer.valueOf(Constant.METRIC_RANGE_LASTN_DEFAULT),
+ Integer.valueOf(Constant.METRIC_RANGE_UNIT_DEFAULT));
// String[] range = {String.valueOf(rangeArray.get(0)),String.valueOf(rangeArray.get(1))};
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE,
(String.valueOf(rangeArray.get(0)) + "," + String.valueOf(rangeArray.get(1)))));
@@ -409,8 +411,8 @@ public abstract class AbstractRecentAlertsPortlet extends AlertHistoryView imple
int lastN = property.getIntegerValue();
property = this.configuration.getSimple(Constant.METRIC_RANGE_UNIT);
int lastUnits = property.getIntegerValue();
- ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, Integer
- .valueOf(lastUnits));
+ ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN,
+ Integer.valueOf(lastUnits));
criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0)));
criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1)));
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/AbstractOperationHistoryPortlet.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/AbstractOperationHistoryPortlet.java
index 66564c3..ab9da7b 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/AbstractOperationHistoryPortlet.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/portlets/recent/operations/AbstractOperationHistoryPortlet.java
@@ -162,7 +162,8 @@ public abstract class AbstractOperationHistoryPortlet extends OperationHistoryVi
@Override
public void onSubmitValues(SubmitValuesEvent event) {
// operation status
- String selectedValue = operationStatusSelector.getValue().toString();
+ String selectedValue = (null == operationStatusSelector.getValue()) ? "" : operationStatusSelector
+ .getValue().toString();
if ((selectedValue.trim().isEmpty())
|| (selectedValue.split(",").length == OperationRequestStatus.values().length)) {
selectedValue = "";
@@ -237,8 +238,9 @@ public abstract class AbstractOperationHistoryPortlet extends OperationHistoryVi
} else {//if disabled, reset time defaults
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE_ENABLE, false));
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE_BEGIN_END_FLAG, false));
- List<Long> rangeArray = MeasurementUtility.calculateTimeFrame(Integer
- .valueOf(Constant.METRIC_RANGE_LASTN_DEFAULT), Integer.valueOf(Constant.METRIC_RANGE_UNIT_DEFAULT));
+ List<Long> rangeArray = MeasurementUtility.calculateTimeFrame(
+ Integer.valueOf(Constant.METRIC_RANGE_LASTN_DEFAULT),
+ Integer.valueOf(Constant.METRIC_RANGE_UNIT_DEFAULT));
// String[] range = {String.valueOf(rangeArray.get(0)),String.valueOf(rangeArray.get(1))};
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE,
(String.valueOf(rangeArray.get(0)) + "," + String.valueOf(rangeArray.get(1)))));
@@ -380,8 +382,8 @@ public abstract class AbstractOperationHistoryPortlet extends OperationHistoryVi
int lastN = property.getIntegerValue();
property = this.configuration.getSimple(Constant.METRIC_RANGE_UNIT);
int lastUnits = property.getIntegerValue();
- ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN, Integer
- .valueOf(lastUnits));
+ ArrayList<Long> beginEnd = MeasurementUtility.calculateTimeFrame(lastN,
+ Integer.valueOf(lastUnits));
criteria.addFilterStartTime(Long.valueOf(beginEnd.get(0)));
criteria.addFilterEndTime(Long.valueOf(beginEnd.get(1)));
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java
index c964196..e49b081 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/detail/summary/AbstractActivityView.java
@@ -18,7 +18,9 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.common.detail.summary;
-import java.util.logging.Logger;
+import java.util.List;
+import java.util.Set;
+
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.IButton;
@@ -27,11 +29,17 @@ import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickEvent;
import com.smartgwt.client.widgets.events.CloseClickHandler;
-import com.smartgwt.client.widgets.form.fields.*;
+import com.smartgwt.client.widgets.form.fields.CheckboxItem;
+import com.smartgwt.client.widgets.form.fields.FormItem;
+import com.smartgwt.client.widgets.form.fields.FormItemIcon;
+import com.smartgwt.client.widgets.form.fields.LinkItem;
+import com.smartgwt.client.widgets.form.fields.SelectItem;
+import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
+
import org.rhq.core.domain.alert.AlertPriority;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.ConfigurationUpdateStatus;
@@ -55,10 +63,13 @@ import org.rhq.enterprise.gui.coregui.client.util.BrowserUtility;
import org.rhq.enterprise.gui.coregui.client.util.Log;
import org.rhq.enterprise.gui.coregui.client.util.MeasurementUtility;
import org.rhq.enterprise.gui.coregui.client.util.measurement.GwtMonitorUtils;
-import org.rhq.enterprise.gui.coregui.client.util.selenium.*;
-
-import java.util.List;
-import java.util.Set;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableCanvas;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableDynamicForm;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableHLayout;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableIButton;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableVLayout;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.LocatableWindow;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/**
* @author Simeon Pinder
@@ -294,8 +305,8 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
Resource[] currentResources = new Resource[explicitMembers.size()];
explicitMembers.toArray(currentResources);
if (group.getGroupCategory().equals(GroupCategory.COMPATIBLE)) {
- if (currentResources[0].getResourceType().getCategory().equals(
- ResourceCategory.PLATFORM)) {
+ if (currentResources[0].getResourceType().getCategory()
+ .equals(ResourceCategory.PLATFORM)) {
enableBundleArea();
getRecentBundleDeployments();
}
@@ -306,7 +317,7 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
@Override
public void onFailure(Throwable caught) {
Log.debug("Error retrieving information for group [" + group.getId() + "]:"
- + caught.getMessage());
+ + caught.getMessage());
}
});
@@ -469,10 +480,10 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
*/
public static Configuration saveResultCounterSettings(final SelectItem resultCountSelector,
final Configuration portletConfig) {
- String selectedValue;
if ((resultCountSelector != null) && (portletConfig != null)) {
- selectedValue = resultCountSelector.getValue().toString();
- if ((selectedValue.trim().isEmpty()) || (selectedValue.equalsIgnoreCase(Constant.RESULT_COUNT_DEFAULT))) {//then 5
+ String selectedValue = (null == resultCountSelector.getValue()) ? "" : resultCountSelector.getValue()
+ .toString();
+ if (selectedValue.trim().isEmpty() || (selectedValue.equalsIgnoreCase(Constant.RESULT_COUNT_DEFAULT))) {//then 5
portletConfig.put(new PropertySimple(Constant.RESULT_COUNT, Constant.RESULT_COUNT_DEFAULT));
} else {
portletConfig.put(new PropertySimple(Constant.RESULT_COUNT, selectedValue));
@@ -489,12 +500,12 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
*/
public static Configuration saveOperationStatusSelectorSettings(final SelectItem operationStatusSelector,
final Configuration portletConfig) {
- String selectedValue;
- selectedValue = operationStatusSelector.getValue().toString();
- if ((selectedValue.trim().isEmpty())
+ String selectedValue = (null == operationStatusSelector.getValue()) ? "" : operationStatusSelector.getValue()
+ .toString();
+ if (selectedValue.trim().isEmpty()
|| (selectedValue.split(",").length == OperationRequestStatus.values().length)) {//then no operation status specified
portletConfig.put(new PropertySimple(Constant.OPERATION_STATUS, ""));
- } else {//some subset of available alertPriorities will be used
+ } else {
portletConfig.put(new PropertySimple(Constant.OPERATION_STATUS, selectedValue));
}
return portletConfig;
@@ -508,9 +519,9 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
*/
public static Configuration saveConfigUpdateStatusSelectorSettings(final SelectItem configStatusSelector,
final Configuration portletConfig) {
- String selectedValue;
- selectedValue = configStatusSelector.getValue().toString();
- if ((selectedValue.trim().isEmpty())
+ String selectedValue = (null == configStatusSelector.getValue()) ? "" : configStatusSelector.getValue()
+ .toString();
+ if (selectedValue.trim().isEmpty()
|| (selectedValue.split(",").length == ConfigurationUpdateStatus.values().length)) {//then no operation status specified
portletConfig.put(new PropertySimple(Constant.CONFIG_UPDATE_STATUS, Constant.CONFIG_UPDATE_STATUS_DEFAULT));
} else {//some subset of available configUpdate statuses will be used
@@ -561,8 +572,9 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
} else {//if disabled, reset time defaults
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE_ENABLE, false));
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE_BEGIN_END_FLAG, false));
- List<Long> rangeArray = MeasurementUtility.calculateTimeFrame(Integer
- .valueOf(Constant.METRIC_RANGE_LASTN_DEFAULT), Integer.valueOf(Constant.METRIC_RANGE_UNIT_DEFAULT));
+ List<Long> rangeArray = MeasurementUtility.calculateTimeFrame(
+ Integer.valueOf(Constant.METRIC_RANGE_LASTN_DEFAULT),
+ Integer.valueOf(Constant.METRIC_RANGE_UNIT_DEFAULT));
// String[] range = {String.valueOf(rangeArray.get(0)),String.valueOf(rangeArray.get(1))};
portletConfig.put(new PropertySimple(Constant.METRIC_RANGE,
(String.valueOf(rangeArray.get(0)) + "," + String.valueOf(rangeArray.get(1)))));
@@ -578,8 +590,9 @@ public abstract class AbstractActivityView extends LocatableVLayout implements R
* returns populated configuration object.
*/
public static Configuration saveAlertPrioritySettings(SelectItem alertPrioritySelector, Configuration portletConfig) {
- String selectedValue = alertPrioritySelector.getValue().toString();
- if ((selectedValue.trim().isEmpty()) || (selectedValue.split(",").length == AlertPriority.values().length)) {//then no alertPriority specified
+ String selectedValue = (String) alertPrioritySelector.getValue();
+ if (null == selectedValue || selectedValue.trim().isEmpty()
+ || (selectedValue.split(",").length == AlertPriority.values().length)) {//then no alertPriority specified
portletConfig.put(new PropertySimple(Constant.ALERT_PRIORITY, ""));
} else {//some subset of available alertPriorities will be used
portletConfig.put(new PropertySimple(Constant.ALERT_PRIORITY, selectedValue));
commit c4aa0e7854db21715706999170ab4b0bc135f77e
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Tue Mar 27 14:15:26 2012 -0400
- Change the Default dash masup portlet to show RHQ homepage as opposed to
the rarely updated blog page. If this is no good we may want to either
take this portlet off the default dash or create a landing page specfically
for this portlet (i.e. something that fits and is useful). As another
aside, it might be nice to be able to maximize a portlet so you can
see more of one you currently care about. Perhaps throw it up into a
Window.
- Remove some commented out code.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java
index 41442b8..5cbc4c7 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/dashboard/DashboardsView.java
@@ -293,66 +293,6 @@ public class DashboardsView extends LocatableVLayout implements DashboardContain
return dashboardName;
}
- /*
- protected Dashboard getDefaultDashboard() {
-
- Dashboard dashboard = new Dashboard();
- dashboard.setName(MSG.common_title_default());
- dashboard.setCategory(DashboardCategory.INVENTORY);
- dashboard.setColumns(2);
- // only leftmost column width is currently settable, the rest are equally divided
- dashboard.setColumnWidths("32%");
- dashboard.getConfiguration().put(new PropertySimple(Dashboard.CFG_BACKGROUND, "#F1F2F3"));
-
- // Left Column
- DashboardPortlet summary = new DashboardPortlet(InventorySummaryPortlet.NAME, InventorySummaryPortlet.KEY, 210);
- dashboard.addPortlet(summary, 0, 0);
-
- DashboardPortlet discoveryQueue = new DashboardPortlet(AutodiscoveryPortlet.NAME, AutodiscoveryPortlet.KEY, 230);
- dashboard.addPortlet(discoveryQueue, 0, 1);
-
- DashboardPortlet recentlyAdded = new DashboardPortlet(RecentlyAddedResourcesPortlet.NAME,
- RecentlyAddedResourcesPortlet.KEY, 230);
- dashboard.addPortlet(recentlyAdded, 0, 2);
-
- DashboardPortlet tagCloud = new DashboardPortlet(TagCloudPortlet.NAME, TagCloudPortlet.KEY, 230);
- dashboard.addPortlet(tagCloud, 0, 3);
-
- // Right Column
- DashboardPortlet welcome = new DashboardPortlet(MessagePortlet.NAME, MessagePortlet.KEY, 210);
- welcome.getConfiguration().put(
- new PropertySimple("message", MSG.view_dashboardsManager_message_title_details()));
- dashboard.addPortlet(welcome, 1, 0);
-
- DashboardPortlet recentAlerts = new DashboardPortlet(RecentAlertsPortlet.NAME, RecentAlertsPortlet.KEY, 230);
- dashboard.addPortlet(recentAlerts, 1, 1);
-
- DashboardPortlet problemResources = new DashboardPortlet(ProblemResourcesPortlet.NAME,
- ProblemResourcesPortlet.KEY, 230);
- //initialize config for the problemResources portlet.
- problemResources.getConfiguration()
- .put(
- new PropertySimple(ProblemResourcesPortlet.PROBLEM_RESOURCE_SHOW_MAX,
- ProblemResourcesPortlet.defaultValue));
- problemResources.getConfiguration()
- .put(
- new PropertySimple(ProblemResourcesPortlet.PROBLEM_RESOURCE_SHOW_HRS,
- ProblemResourcesPortlet.defaultValue));
- dashboard.addPortlet(problemResources, 1, 2);
-
- DashboardPortlet operations = new DashboardPortlet(OperationsPortlet.NAME, OperationsPortlet.KEY, 420);
- dashboard.addPortlet(operations, 1, 3);
-
- DashboardPortlet news = new DashboardPortlet(MashupPortlet.NAME, MashupPortlet.KEY, 350);
- news.getConfiguration().put(
- new PropertySimple("address", "http://rhq-project.org/display/RHQ/RHQ+News?decorator=popup"));
- dashboard.addPortlet(news, 1, 4);
-
- return dashboard;
-
- }
- */
-
protected Dashboard getDefaultDashboard() {
Dashboard dashboard = new Dashboard();
@@ -380,8 +320,7 @@ public class DashboardsView extends LocatableVLayout implements DashboardContain
DashboardPortlet news = new DashboardPortlet(MashupPortlet.NAME, MashupPortlet.KEY, 300);
if (isRHQ) {
- news.getConfiguration().put(
- new PropertySimple("address", "http://rhq-project.org/display/RHQ/RHQ+News?decorator=popup"));
+ news.getConfiguration().put(new PropertySimple("address", "http://rhq-project.org/display/RHQ/Home"));
} else {
news.getConfiguration().put(
new PropertySimple("address",
commit 6bbadb28778381b4e81aaca5c59829d95554424d
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Tue Mar 27 14:10:40 2012 -0400
Make Montoring->Tables the default subtab, graphs is too slow.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
index 24d7270..4fb09ac 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java
@@ -213,7 +213,7 @@ public class ResourceDetailView extends AbstractTwoLevelTabSetView<ResourceCompo
MSG.view_tabs_common_schedules()), null);
monitorCallTime = new SubTab(monitoringTab.extendLocatorId("CallTime"), new ViewName("CallTime",
MSG.view_tabs_common_calltime()), null);
- monitoringTab.registerSubTabs(monitorGraphs, monitorTables, monitorTraits, monitorAvail, monitorSched,
+ monitoringTab.registerSubTabs(monitorTables, monitorGraphs, monitorTraits, monitorAvail, monitorSched,
monitorCallTime);
tabs.add(monitoringTab);
commit 083e3a6b9aad4ff76d0aadf1498611a638c37043
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 12:11:13 2012 -0400
deploy() now throws a RuntimeException if deployment of the plugin fails
diff --git a/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RhqAgentPluginContainer.java b/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RhqAgentPluginContainer.java
index 24f3c09..d1e73b0 100644
--- a/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RhqAgentPluginContainer.java
+++ b/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RhqAgentPluginContainer.java
@@ -20,12 +20,22 @@ package org.rhq.test.arquillian.impl;
import java.io.File;
import java.io.IOException;
+import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
+import javax.xml.namespace.QName;
+import javax.xml.stream.FactoryConfigurationError;
+import javax.xml.stream.XMLEventReader;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.events.Attribute;
+import javax.xml.stream.events.StartElement;
+import javax.xml.stream.events.XMLEvent;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -44,10 +54,12 @@ import org.jboss.shrinkwrap.api.Filter;
import org.jboss.shrinkwrap.api.Node;
import org.jboss.shrinkwrap.api.exporter.ZipExporter;
import org.jboss.shrinkwrap.descriptor.api.Descriptor;
+import org.jboss.shrinkwrap.impl.base.path.BasicPath;
import org.rhq.core.pc.PluginContainer;
import org.rhq.core.pc.ServerServices;
import org.rhq.core.pc.plugin.FileSystemPluginFinder;
+import org.rhq.core.pc.plugin.PluginEnvironment;
import org.rhq.core.system.SystemInfoFactory;
import org.rhq.core.util.file.FileUtil;
import org.rhq.test.arquillian.impl.util.SigarInstaller;
@@ -66,7 +78,9 @@ public class RhqAgentPluginContainer implements DeployableContainer<RhqAgentPlug
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 ArchivePath PLUGIN_DESCRIPTOR_PATH = new BasicPath("META-INF", "rhq-plugin.xml");
+
private static final Map<String, Boolean> NATIVE_SYSTEM_INFO_ENABLEMENT_PER_PC = new HashMap<String, Boolean>();
static {
@@ -206,25 +220,35 @@ public class RhqAgentPluginContainer implements DeployableContainer<RhqAgentPlug
try {
switchPcInstance();
} catch (Exception e) {
- throw new DeploymentException("Failed to switch plugin container.", e);
+ throw new DeploymentException("Failed to switch to PluginContainer [" + container.get().getName() + "].",
+ e);
}
- RhqAgentPluginArchive plugin = archive.as(RhqAgentPluginArchive.class);
+ RhqAgentPluginArchive pluginArchive = archive.as(RhqAgentPluginArchive.class);
- Node descriptor = plugin.get(ArchivePaths.create("META-INF/rhq-plugin.xml"));
+ Node descriptor = pluginArchive.get(ArchivePaths.create("META-INF/rhq-plugin.xml"));
if (descriptor == null) {
- throw new DeploymentException("Archive [" + archive + "] doesn't specify an RHQ plugin descriptor.");
+ throw new DeploymentException("Plugin archive [" + archive + "] doesn't specify an RHQ plugin descriptor.");
}
boolean wasStarted = stopPc();
- deployPlugin(plugin);
+ deployPlugin(pluginArchive);
if (wasStarted) {
startPc();
}
- LOG.info("Done deploying " + archive + " to PluginContainer " + container.get().getName());
+ PluginContainer pc = PluginContainer.getInstance();
+ String pluginName = getPluginName(pluginArchive);
+ PluginEnvironment plugin = pc.getPluginManager().getPlugin(pluginName);
+ if (plugin == null) {
+ throw new RuntimeException("Failed to deploy plugin '" + pluginName + "' (" + pluginArchive.getName()
+ + ") - check the log above for an error (and big stack trace) from PluginManager.initialize().");
+ }
+
+ LOG.info("Done deploying plugin '" + pluginName + "' (" + archive + ") to PluginContainer "
+ + container.get().getName() +".");
return new ProtocolMetaData();
}
@@ -323,7 +347,7 @@ public class RhqAgentPluginContainer implements DeployableContainer<RhqAgentPlug
* @return true if the plugin container needed to be started (i.e. was not running before), false otherwise.
*/
private boolean startPc() {
- LOG.debug("Starting PluginContainer on demand");
+ LOG.debug("Starting PluginContainer on demand...");
PluginContainer pc = PluginContainer.getInstance();
if (pc.isStarted()) {
@@ -344,7 +368,7 @@ public class RhqAgentPluginContainer implements DeployableContainer<RhqAgentPlug
* @return true if PC was running before this call, false otherwise
*/
private boolean stopPc() {
- LOG.debug("Stopping PluginContainer on demand");
+ LOG.debug("Stopping PluginContainer on demand...");
PluginContainer pc = PluginContainer.getInstance();
if (pc.isStarted()) {
pc.shutdown();
@@ -371,4 +395,56 @@ public class RhqAgentPluginContainer implements DeployableContainer<RhqAgentPlug
return switchPluginContainer(container.get().getName());
}
+ private static String getPluginName(Archive<?> archive) {
+ InputStream is = archive.get(PLUGIN_DESCRIPTOR_PATH).getAsset().openStream();
+ XMLEventReader rdr = null;
+ try {
+ rdr = XMLInputFactory.newInstance().createXMLEventReader(is);
+
+ XMLEvent event = null;
+ while (rdr.hasNext()) {
+ event = rdr.nextEvent();
+ if (event.getEventType() == XMLEvent.START_ELEMENT) {
+ break;
+ }
+ }
+
+ StartElement startElement = event.asStartElement();
+ String tagName = startElement.getName().getLocalPart();
+ if (!"plugin".equals(tagName)) {
+ throw new IllegalArgumentException("Illegal start tag found in the plugin descriptor. Expected 'plugin' but found '" + tagName + "' in the plugin '" + archive + "'.");
+ }
+
+ Attribute nameAttr = startElement.getAttributeByName(new QName("name"));
+
+ if (nameAttr == null) {
+ throw new IllegalArgumentException("Couldn't find the name attribute on the plugin tag in the plugin descriptor of plugin '" + archive + "'.");
+ }
+
+ return nameAttr.getValue();
+ } catch (XMLStreamException e) {
+ throw new IllegalArgumentException("Failed to extract the plugin name out of the RHQ plugin archive [" + archive + "]", e);
+ } catch (FactoryConfigurationError e) {
+ throw new IllegalArgumentException("Failed to extract the plugin name out of the RHQ plugin archive [" + archive + "]", e);
+ } finally {
+ closeReaderAndStream(rdr, is, archive);
+ }
+ }
+
+ private static void closeReaderAndStream(XMLEventReader rdr, InputStream str, Archive<?> archive) {
+ if (rdr != null) {
+ try {
+ rdr.close();
+ } catch (XMLStreamException e) {
+ LOG.error("Failed to close the XML reader of the plugin descriptor in archive [" + archive + "]", e);
+ }
+ }
+
+ try {
+ str.close();
+ } catch (IOException e) {
+ LOG.error("Failed to close the input stream of the plugin descriptor in archive [" + archive + "]", e);
+ }
+ }
+
}
commit e11909ad0e90695682abd0b943ed3f7f5c6ecdd9
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 11:15:30 2012 -0400
various minor improvements to itests: extra some code to util methods in core-domain; improve assertion failure messages; add some additional debug println's
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceFilter.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceFilter.java
new file mode 100644
index 0000000..db3c7a9
--- /dev/null
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceFilter.java
@@ -0,0 +1,43 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.core.domain.util;
+
+import org.rhq.core.domain.resource.Resource;
+
+/**
+ * A filter for {@link Resource}s
+ * <p/>
+ * Instances of this interface may be passed to the {@link
+ * org.rhq.core.domain.util.ResourceUtility#getChildResources(org.rhq.core.domain.resource.Resource, ResourceFilter)}
+ * method.
+ *
+ * @since 4.4
+ * @author Ian Springer
+ */
+public interface ResourceFilter {
+
+ /**
+ * Tests whether or not the specified Resource should be included in a Resource list.
+ *
+ * @param resource The Resource to be tested
+ * @return <code>true</code> if and only if <code>resource</code> should be included
+ */
+ boolean accept(Resource resource);
+
+}
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceTypeUtility.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceTypeUtility.java
index 3765c36..f3484f8 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceTypeUtility.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceTypeUtility.java
@@ -28,12 +28,13 @@ import org.rhq.core.domain.resource.ResourceType;
/**
* A set of utility methods for working with {@link ResourceType}s.
*
+ * @since 4.4
* @author Ian Springer
*/
public abstract class ResourceTypeUtility {
/**
- * Returns the set of MeasurementDefinition defined by the given Resource type, which are accepted by the specified
+ * Returns the set of MeasurementDefinitions defined by the given Resource type, which are accepted by the specified
* filter. If the filter is null, all of the type's MeasurementDefinitions will be returned.
*
* @param type the Resource type
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceUtility.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceUtility.java
index acd91b0..748a66e 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceUtility.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/ResourceUtility.java
@@ -18,12 +18,18 @@
*/
package org.rhq.core.domain.util;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.jetbrains.annotations.NotNull;
+
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
/**
* A set of utility methods for working with {@link Resource}s.
*
+ * @since 4.4
* @author Ian Springer
*/
public abstract class ResourceUtility {
@@ -37,6 +43,31 @@ public abstract class ResourceUtility {
return null;
}
+ /**
+ * Returns the set of child Resources defined by the given parent Resource, which are accepted by the specified
+ * filter. If the filter is null, all of the parent Resource's children will be returned.
+ *
+ * @param parentResource the parent Resource
+ * @param filter the filter; may be null
+ *
+ * @return the set of MeasurementDefinition defined by the given Resource type, which are accepted by the specified
+ * filter, or, if the filter is null, all of the type's MeasurementDefinitions
+ */
+ @NotNull
+ public static Set<Resource> getChildResources(Resource parentResource,
+ ResourceFilter filter) {
+ if (filter == null) {
+ return parentResource.getChildResources();
+ }
+ Set<Resource> acceptedChildResources = new LinkedHashSet<Resource>();
+ for (Resource childResource : parentResource.getChildResources()) {
+ if (filter.accept(childResource)) {
+ acceptedChildResources.add(childResource);
+ }
+ }
+ return acceptedChildResources;
+ }
+
private ResourceUtility() {
}
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/util/TypeAndKeyResourceFilter.java b/modules/core/domain/src/main/java/org/rhq/core/domain/util/TypeAndKeyResourceFilter.java
new file mode 100644
index 0000000..317dc36
--- /dev/null
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/util/TypeAndKeyResourceFilter.java
@@ -0,0 +1,25 @@
+package org.rhq.core.domain.util;
+
+import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.ResourceType;
+
+/**
+ * @since 4.4
+ * @author Ian Springer
+ */
+public class TypeAndKeyResourceFilter implements ResourceFilter {
+
+ private ResourceType resourceType;
+ private String resourceKey;
+
+ public TypeAndKeyResourceFilter(ResourceType resourceType, String resourceKey) {
+ this.resourceType = resourceType;
+ this.resourceKey = resourceKey;
+ }
+
+ @Override
+ public boolean accept(Resource resource) {
+ return (resource.getResourceType().equals(resourceType) && resource.getResourceKey().equals(resourceKey));
+ }
+
+}
diff --git a/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java b/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java
index 5f658f4..8a28883 100644
--- a/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java
+++ b/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java
@@ -130,6 +130,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
*/
@BeforeDiscovery
public void resetServerServices() throws Exception {
+ System.out.println("\n=== Resetting Server services prior to running discovery scan...");
try {
this.serverServices.resetMocks();
Mockito.when(this.serverServices.getDiscoveryServerService().mergeInventoryReport(Mockito.any(InventoryReport.class))).then(
diff --git a/modules/plugins/jboss-as-5/src/test/java/org/rhq/plugins/jbossas5/itest/ApplicationServerComponentTest.java b/modules/plugins/jboss-as-5/src/test/java/org/rhq/plugins/jbossas5/itest/ApplicationServerComponentTest.java
index 0344a41..1c0820e 100644
--- a/modules/plugins/jboss-as-5/src/test/java/org/rhq/plugins/jbossas5/itest/ApplicationServerComponentTest.java
+++ b/modules/plugins/jboss-as-5/src/test/java/org/rhq/plugins/jbossas5/itest/ApplicationServerComponentTest.java
@@ -22,6 +22,8 @@
*/
package org.rhq.plugins.jbossas5.itest;
+import java.util.Set;
+
import org.testng.Assert;
import org.testng.annotations.Test;
@@ -30,7 +32,7 @@ import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceCategory;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.domain.util.ResourceUtility;
-import org.rhq.core.pc.inventory.InventoryManager;
+import org.rhq.core.domain.util.TypeAndKeyResourceFilter;
import org.rhq.core.pluginapi.util.FileUtils;
import org.rhq.test.arquillian.RunDiscovery;
@@ -63,8 +65,14 @@ public class ApplicationServerComponentTest extends AbstractJBossAS5PluginTest {
}
private Resource getServerResource() {
- InventoryManager inventoryManager = this.pluginContainer.getInventoryManager();
- return ResourceUtility.getChildResource(inventoryManager.getPlatform(), RESOURCE_TYPE, RESOURCE_KEY);
+ Resource platform = this.pluginContainer.getInventoryManager().getPlatform();
+ Set<Resource> childResources = ResourceUtility.getChildResources(platform,
+ new TypeAndKeyResourceFilter(RESOURCE_TYPE, RESOURCE_KEY));
+ if (childResources.size() > 1) {
+ throw new IllegalStateException(platform + " has more than one child Resource with same type ("
+ + RESOURCE_TYPE + ") and key (" + RESOURCE_KEY + ").");
+ }
+ return (childResources.isEmpty()) ? null : childResources.iterator().next();
}
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java
index 5e22925..2880d85 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java
@@ -18,12 +18,17 @@
*/
package org.rhq.modules.plugins.jbossas7.itest;
+import java.util.Set;
+
import org.rhq.core.clientapi.agent.PluginContainerException;
import org.rhq.core.clientapi.agent.discovery.InvalidPluginConfigurationClientException;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.domain.resource.Resource;
+import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.domain.util.ResourceFilter;
import org.rhq.core.domain.util.ResourceUtility;
+import org.rhq.core.domain.util.TypeAndKeyResourceFilter;
import org.rhq.core.pc.inventory.InventoryManager;
import org.rhq.core.plugin.testutil.AbstractAgentPluginTest;
import org.rhq.core.pluginapi.operation.OperationResult;
@@ -31,6 +36,8 @@ import org.rhq.modules.plugins.jbossas7.itest.domain.DomainServerComponentTest;
import org.rhq.modules.plugins.jbossas7.itest.standalone.StandaloneServerComponentTest;
import org.rhq.test.arquillian.AfterDiscovery;
+import static org.testng.Assert.assertNotNull;
+
/**
* The base class for all jboss-as-7 plugin integration tests.
*
@@ -50,18 +57,20 @@ public abstract class AbstractJBossAS7PluginTest extends AbstractAgentPluginTest
*/
@AfterDiscovery
public void installManagementUsers() throws PluginContainerException {
+ System.out.println("\n=== Discovery scan completed.");
if (!createdManagementUsers) {
+ System.out.println("====== Installing management users...");
+
Resource platform = this.pluginContainer.getInventoryManager().getPlatform();
- Resource domainServer = ResourceUtility.getChildResource(platform,
- DomainServerComponentTest.RESOURCE_TYPE, DomainServerComponentTest.RESOURCE_KEY);
- if (domainServer != null) {
- installManagementUser(domainServer);
- }
- Resource standaloneServer = ResourceUtility.getChildResource(platform,
- StandaloneServerComponentTest.RESOURCE_TYPE, StandaloneServerComponentTest.RESOURCE_KEY);
- if (standaloneServer != null) {
- installManagementUser(standaloneServer);
- }
+
+ Resource domainServer = getResourceByTypeAndKey(platform, DomainServerComponentTest.RESOURCE_TYPE,
+ DomainServerComponentTest.RESOURCE_KEY);
+ installManagementUser(domainServer);
+
+ Resource standaloneServer = getResourceByTypeAndKey(platform, StandaloneServerComponentTest.RESOURCE_TYPE,
+ StandaloneServerComponentTest.RESOURCE_KEY);
+ installManagementUser(standaloneServer);
+
// TODO (ips, 03/16/12): Uncomment this once I fix the issue with Resources that were previously discovered
// and committed getting discovered with a status of NEW.
//createdManagementUsers = true;
@@ -69,7 +78,7 @@ public abstract class AbstractJBossAS7PluginTest extends AbstractAgentPluginTest
}
private void installManagementUser(Resource resource) throws PluginContainerException {
- System.out.println("\n>>> Installing management user [" + MANAGEMENT_USERNAME + "] for " + resource + "...");
+ System.out.println("========= Installing management user [" + MANAGEMENT_USERNAME + "] for " + resource + "...");
// Invoke the "installRhqUser" operation on the ResourceComponent - this will update the mgmt-users.properties
// file in the AS7 server's configuration directory.
@@ -103,4 +112,25 @@ public abstract class AbstractJBossAS7PluginTest extends AbstractAgentPluginTest
return PLUGIN_NAME;
}
+ protected static Resource getResourceByTypeAndKey(Resource parent, final ResourceType type, String key) {
+ Set<Resource> childResources = ResourceUtility.getChildResources(parent,
+ new TypeAndKeyResourceFilter(type, key));
+ if (childResources.size() > 1) {
+ throw new IllegalStateException(parent + " has more than one child Resource with same type ("
+ + type + ") and key (" + key + ").");
+ }
+ Resource serverResource = (childResources.isEmpty()) ? null : childResources.iterator().next();
+
+ assertNotNull(serverResource,
+ type.getName() + " Resource with key [" + key + "] not found in inventory - child "
+ + type.getCategory().getDisplayName() + "s that were discovered: "
+ + ResourceUtility.getChildResources(parent,
+ new ResourceFilter() {
+ public boolean accept(Resource resource) {
+ return (resource.getResourceType().getCategory() == type.getCategory());
+ }
+ }));
+ return serverResource;
+ }
+
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
index 8a90c8f..0cd1e01 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
@@ -26,8 +26,6 @@ import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
-import org.rhq.core.domain.util.ResourceUtility;
-import org.rhq.core.pc.inventory.InventoryManager;
import static org.testng.Assert.*;
@@ -53,17 +51,8 @@ public abstract class AbstractServerComponentTest extends AbstractJBossAS7Plugin
protected abstract String getServerResourceKey();
protected Resource getServerResource() {
- InventoryManager inventoryManager = this.pluginContainer.getInventoryManager();
- Resource resource = ResourceUtility.getChildResource(inventoryManager.getPlatform(),
- getServerResourceType(),
- getServerResourceKey());
-
- assertNotNull(resource,
- getServerResourceType().getName() + " Resource with key [" + getServerResourceKey()
- + "] not found in inventory - platform child Resources that were discovered: "
- + inventoryManager.getPlatform().getChildResources());
-
- return resource;
+ Resource platform = this.pluginContainer.getInventoryManager().getPlatform();
+ return getResourceByTypeAndKey(platform, getServerResourceType(), getServerResourceKey());
}
public void testAutoDiscovery() throws Exception {
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
index d532225..5400e57 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
@@ -57,8 +57,8 @@ public class DomainServerComponentTest extends AbstractServerComponentTest {
return "jboss.domain.portOffset";
}
- @RunDiscovery
@Test(priority = 20, groups = "discovery")
+ @RunDiscovery
public void testDomainServerDiscovery() throws Exception {
super.testAutoDiscovery();
}
diff --git a/modules/plugins/jboss-as-7/src/test/resources/log4j.xml b/modules/plugins/jboss-as-7/src/test/resources/log4j.xml
index 27eb821..2687703 100644
--- a/modules/plugins/jboss-as-7/src/test/resources/log4j.xml
+++ b/modules/plugins/jboss-as-7/src/test/resources/log4j.xml
@@ -43,14 +43,15 @@
</layout>
</appender>
+<!--
<category name="org.rhq.core.pc">
- <priority value="FATAL"/>
+ <priority value="ERROR"/>
</category>
<category name="org.rhq.core.pc.PluginContainer">
<priority value="INFO"/>
</category>
-
+-->
<category name="org.rhq.core.clientapi">
<priority value="FATAL"/>
</category>
commit 784357ca63a052a6ee6b8caa5a4d4cfb384b3883
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 11:07:21 2012 -0400
while processing @RunDiscovery, if an error occurs during either server or service discovery scan, throw a RuntimeException
diff --git a/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RunDiscoveryExecutor.java b/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RunDiscoveryExecutor.java
index 2601bd1..1e6147d 100644
--- a/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RunDiscoveryExecutor.java
+++ b/modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RunDiscoveryExecutor.java
@@ -16,11 +16,11 @@
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
-
package org.rhq.test.arquillian.impl;
import org.jboss.arquillian.test.spi.event.suite.TestEvent;
+import org.rhq.core.clientapi.server.discovery.InventoryReport;
import org.rhq.core.pc.PluginContainer;
import org.rhq.test.arquillian.RunDiscovery;
import org.rhq.test.arquillian.spi.PluginContainerOperation;
@@ -53,10 +53,17 @@ public class RunDiscoveryExecutor implements PluginContainerOperation {
private void runDiscovery(RunDiscovery annotation, PluginContainer pluginContainer) {
if (annotation.discoverServers()) {
- pluginContainer.getInventoryManager().executeServerScanImmediately();
+ InventoryReport serverScanReport = pluginContainer.getInventoryManager().executeServerScanImmediately();
+ if (!serverScanReport.getErrors().isEmpty()) {
+ throw new RuntimeException("Errors occurred during server scan: " + serverScanReport.getErrors());
+ }
}
if (annotation.discoverServices()) {
- pluginContainer.getInventoryManager().executeServiceScanImmediately();
+ InventoryReport serviceScanReport = pluginContainer.getInventoryManager().executeServiceScanImmediately();
+ if (!serviceScanReport.getErrors().isEmpty()) {
+ throw new RuntimeException("Errors occurred during service scan: " + serviceScanReport.getErrors());
+ }
}
}
+
}
commit e796134ae6db224b63314b4bea25dfe4e75e467e
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Tue Mar 27 11:05:02 2012 -0400
fix invalid ordering of "Transactions Subsystem" service element (the xsd requires service elements to come after sibling server elements)
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 dc502e2..6ad5105 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
@@ -51,7 +51,6 @@
displayName="JBoss Application Server 7.x"
description="Management of JBossAS 7"
package="org.rhq.modules.plugins.jbossas7"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="urn:xmlns:rhq-plugin"
xmlns:c="urn:xmlns:rhq-configuration"
>
@@ -961,64 +960,6 @@
</server>
- <service name="Transactions Subsystem"
- discovery="SubsystemDiscovery"
- class="BaseComponent"
- singleton="true"
- description="The transactions subsystem."
- >
-
- <runs-inside>
- <parent-resource-type name="Profile" plugin="jboss-as-7"/>
- <parent-resource-type name="JBossAS7 Standalone Server" plugin="jboss-as-7"/>
- </runs-inside>
-
- <plugin-configuration>
- <c:simple-property name="path" readOnly="true" default="subsystem=transactions"/>
- </plugin-configuration>
-
- <metric property="number-of-nested-transactions" description="The total number of nested (sub) transactions created."
- measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
- <metric property="number-of-timed-out-transactions" description="The number of transactions that have rolled back due to timeout."
- measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
- <metric property="number-of-committed-transactions" description="The number of committed transactions."
- measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
- <metric property="number-of-transactions" description="The total number of transactions (top-level and nested) created"
- measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
- <metric property="number-of-heuristics" description="The number of transactions which have terminated with heuristic outcomes."
- measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
- <metric property="number-of-aborted-transactions" description="The number of aborted (i.e. rolledback) transactions."
- measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
- <metric property="number-of-inflight-transactions" description="The number of transactions that have begun but not yet terminated."
- measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
- <metric property="number-of-application-rollbacks" description="The number of transactions that have been rolled back by application request. This includes those that timeout, since the timeout behaviour is considered an attribute of the application configuration."
- measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
- <metric property="number-of-resource-rollbacks" description="The number of transactions that rolled back due to resource (participant) failure."
- measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
-
- <resource-configuration>
- <c:simple-property name="relative-to" required="false" type="string" readOnly="false" defaultValue="jboss.server.data.dir"
- description="References a global path configuration in the domain model, defaulting to the JBoss Application Server data directory (jboss.server.data.dir). The value of the 'path' attribute will treated as relative to this path. Use an empty string to disable the default behavior and force the value of the 'path' attribute to be treated as an absolute path."/>
- <c:simple-property name="process-id-uuid" required="false" type="boolean" readOnly="false" description="Indicates whether the transaction manager should use a UUID based process id."/>
- <c:simple-property name="socket-binding" required="false" type="string" readOnly="false" description="Used to reference the correct socket binding to use for the recovery environment."/>
- <c:simple-property name="jts" required="false" type="boolean" readOnly="false" defaultValue="false" description="If true this enables the Java Transaction Service"/>
- <c:simple-property name="object-store-path" required="false" type="string" readOnly="false" defaultValue="tx-object-store"
- description="Denotes a relative or absolute filesystem path denoting where the transaction manager object store should store data. By default the value is treated as relative to the path denoted by the 'relative-to' attribute."/>
- <c:simple-property name="path" required="false" type="string" readOnly="false" defaultValue="var" description="Denotes a relative or absolute filesystem path denoting where the transaction manager core should store data. By default the value is treated as relative to the path denoted by the 'relative-to' attribute."/>
- <c:simple-property name="process-id-socket-binding" required="false" type="string" readOnly="false" description="The name of the socket binding configuration to use if the transaction manager should use a socket-based process id. Will be 'undefined' if 'process-id-uuid' is 'true'; otherwise must be set."/>
- <c:simple-property name="default-timeout" required="false" type="integer" readOnly="false" defaultValue="300" description="The default timeout."/>
- <c:simple-property name="process-id-socket-max-ports" required="false" type="integer" readOnly="false" defaultValue="10" description="The maximum number of ports to search for an open port if the transaction manager should use a socket-based process id. If the port specified by the socket binding referenced in 'process-id-socket-binding' is occupied, the next higher port will be tried until an open port is found or the number of ports specified by this attribute have been tried. Will be 'undefined' if 'process-id-uuid' is 'true'."/>
- <c:simple-property name="recovery-listener" required="false" type="boolean" readOnly="false" defaultValue="false" description="Used to specify if the recovery system should listen on a network socket or not."/>
- <c:simple-property name="status-socket-binding" required="false" type="string" readOnly="false" description="Used to reference the correct socket binding to use for the transaction status manager."/>
- <c:simple-property name="node-identifier" required="false" type="string" readOnly="false" defaultValue="1" description="Used to set the node identifier on the core environment."/>
- <c:simple-property name="enable-tsm-status" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether the transaction status manager (TSM) service, needed for out of process recovery, should be provided or not.."/>
- <c:simple-property name="object-store-relative-to" required="false" type="string" readOnly="false" defaultValue="jboss.server.data.dir"
- description="References a global path configuration in the domain model, defaulting to the JBoss Application Server data directory (jboss.server.data.dir). The value of the 'path' attribute will treated as relative to this path. Use an empty string to disable the default behavior and force the value of the 'path' attribute to be treated as an absolute path."/>
- <c:simple-property name="enable-statistics" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether statistics should be enabled."/>
- </resource-configuration>
-
- </service>
-
<server name="Datasources"
discovery="SubsystemDiscovery"
class="DatasourceComponent"
@@ -2408,6 +2349,65 @@ working area for individual server instances</li></ul>"/>
</server>
+ <service name="Transactions Subsystem"
+ discovery="SubsystemDiscovery"
+ class="BaseComponent"
+ singleton="true"
+ description="The transactions subsystem."
+ >
+
+ <runs-inside>
+ <parent-resource-type name="Profile" plugin="jboss-as-7"/>
+ <parent-resource-type name="JBossAS7 Standalone Server" plugin="jboss-as-7"/>
+ </runs-inside>
+
+ <plugin-configuration>
+ <c:simple-property name="path" readOnly="true" default="subsystem=transactions"/>
+ </plugin-configuration>
+
+ <metric property="number-of-nested-transactions" description="The total number of nested (sub) transactions created."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
+ <metric property="number-of-timed-out-transactions" description="The number of transactions that have rolled back due to timeout."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
+ <metric property="number-of-committed-transactions" description="The number of committed transactions."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
+ <metric property="number-of-transactions" description="The total number of transactions (top-level and nested) created"
+ measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
+ <metric property="number-of-heuristics" description="The number of transactions which have terminated with heuristic outcomes."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
+ <metric property="number-of-aborted-transactions" description="The number of aborted (i.e. rolledback) transactions."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
+ <metric property="number-of-inflight-transactions" description="The number of transactions that have begun but not yet terminated."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="false"/>
+ <metric property="number-of-application-rollbacks" description="The number of transactions that have been rolled back by application request. This includes those that timeout, since the timeout behaviour is considered an attribute of the application configuration."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
+ <metric property="number-of-resource-rollbacks" description="The number of transactions that rolled back due to resource (participant) failure."
+ measurementType="trendsup" defaultInterval="300000" defaultOn="true"/>
+
+ <resource-configuration>
+ <c:simple-property name="relative-to" required="false" type="string" readOnly="false" defaultValue="jboss.server.data.dir"
+ description="References a global path configuration in the domain model, defaulting to the JBoss Application Server data directory (jboss.server.data.dir). The value of the 'path' attribute will treated as relative to this path. Use an empty string to disable the default behavior and force the value of the 'path' attribute to be treated as an absolute path."/>
+ <c:simple-property name="process-id-uuid" required="false" type="boolean" readOnly="false" description="Indicates whether the transaction manager should use a UUID based process id."/>
+ <c:simple-property name="socket-binding" required="false" type="string" readOnly="false" description="Used to reference the correct socket binding to use for the recovery environment."/>
+ <c:simple-property name="jts" required="false" type="boolean" readOnly="false" defaultValue="false" description="If true this enables the Java Transaction Service"/>
+ <c:simple-property name="object-store-path" required="false" type="string" readOnly="false" defaultValue="tx-object-store"
+ description="Denotes a relative or absolute filesystem path denoting where the transaction manager object store should store data. By default the value is treated as relative to the path denoted by the 'relative-to' attribute."/>
+ <c:simple-property name="path" required="false" type="string" readOnly="false" defaultValue="var" description="Denotes a relative or absolute filesystem path denoting where the transaction manager core should store data. By default the value is treated as relative to the path denoted by the 'relative-to' attribute."/>
+ <c:simple-property name="process-id-socket-binding" required="false" type="string" readOnly="false" description="The name of the socket binding configuration to use if the transaction manager should use a socket-based process id. Will be 'undefined' if 'process-id-uuid' is 'true'; otherwise must be set."/>
+ <c:simple-property name="default-timeout" required="false" type="integer" readOnly="false" defaultValue="300" description="The default timeout."/>
+ <c:simple-property name="process-id-socket-max-ports" required="false" type="integer" readOnly="false" defaultValue="10" description="The maximum number of ports to search for an open port if the transaction manager should use a socket-based process id. If the port specified by the socket binding referenced in 'process-id-socket-binding' is occupied, the next higher port will be tried until an open port is found or the number of ports specified by this attribute have been tried. Will be 'undefined' if 'process-id-uuid' is 'true'."/>
+ <c:simple-property name="recovery-listener" required="false" type="boolean" readOnly="false" defaultValue="false" description="Used to specify if the recovery system should listen on a network socket or not."/>
+ <c:simple-property name="status-socket-binding" required="false" type="string" readOnly="false" description="Used to reference the correct socket binding to use for the transaction status manager."/>
+ <c:simple-property name="node-identifier" required="false" type="string" readOnly="false" defaultValue="1" description="Used to set the node identifier on the core environment."/>
+ <c:simple-property name="enable-tsm-status" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether the transaction status manager (TSM) service, needed for out of process recovery, should be provided or not.."/>
+ <c:simple-property name="object-store-relative-to" required="false" type="string" readOnly="false" defaultValue="jboss.server.data.dir"
+ description="References a global path configuration in the domain model, defaulting to the JBoss Application Server data directory (jboss.server.data.dir). The value of the 'path' attribute will treated as relative to this path. Use an empty string to disable the default behavior and force the value of the 'path' attribute to be treated as an absolute path."/>
+ <c:simple-property name="enable-statistics" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether statistics should be enabled."/>
+ </resource-configuration>
+
+ </service>
+
+
<service name="Network Interface"
discovery="SubsystemDiscovery"
class="BaseComponent"
commit 0ac145f94e7e217457506c1460bf607a90b628e4
Author: Simeon Pinder <spinder(a)redhat.com>
Date: Tue Mar 27 09:29:04 2012 -0400
enable remaing operations for modcluster.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
index 9ddb1ec..e90bd03 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
@@ -24,7 +24,6 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
@Override
public OperationResult invokeOperation(String name, Configuration parameters) throws Exception {
-
Operation op = new Operation(name, getAddress());
OperationResult operationResult = new OperationResult();
Result result = null;
@@ -54,14 +53,42 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
addAdditionalToOp(op, parameters, "host", false);
addAdditionalToOp(op, parameters, "port", false);
result = getASConnection().execute(op);
- if (result.isSuccess()) {
+ if (result != null && result.isSuccess()) {
operationResult.setSimpleResult("Success");
}
} else if ("remove-proxy".equals(name)) {
addAdditionalToOp(op, parameters, "host", false);
addAdditionalToOp(op, parameters, "port", false);
result = getASConnection().execute(op);
- if (result.isSuccess()) {
+ if (result != null && result.isSuccess()) {
+ operationResult.setSimpleResult("Success");
+ }
+ } else if ("disable-context".equals(name)) {
+ addAdditionalToOp(op, parameters, "virtualhost", false);
+ addAdditionalToOp(op, parameters, "context", false);
+ result = getASConnection().execute(op);
+ if ((result != null) && (result.isSuccess())) {
+ operationResult.setSimpleResult("Success");
+ }
+ } else if ("enable-context".equals(name)) {
+ addAdditionalToOp(op, parameters, "virtualhost", false);
+ addAdditionalToOp(op, parameters, "context", false);
+ result = getASConnection().execute(op);
+ if ((result != null) && (result.isSuccess())) {
+ operationResult.setSimpleResult("Success");
+ }
+ } else if ("stop".equals(name)) {
+ addAdditionalToOp(op, parameters, "waittime", true);
+ result = getASConnection().execute(op);
+ if ((result != null) && (result.isSuccess())) {
+ operationResult.setSimpleResult("Success");
+ }
+ } else if ("stop-context".equals(name)) {
+ addAdditionalToOp(op, parameters, "virtualhost", false);
+ addAdditionalToOp(op, parameters, "context", false);
+ addAdditionalToOp(op, parameters, "waittime", true);
+ result = getASConnection().execute(op);
+ if ((result != null) && (result.isSuccess())) {
operationResult.setSimpleResult("Success");
}
} else if ("read-proxies-configuration".equals(name)) {
@@ -114,7 +141,10 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
/*
* This is a catch all for operations that are not explicitly treated above.
*/
- op = new Operation(name, address);
+ result = getASConnection().execute(op);
+ if (result.isSuccess()) {
+ operationResult.setSimpleResult("Success");
+ }
}
if (!result.isSuccess()) {
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 7cc8415..dc502e2 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
@@ -2255,13 +2255,13 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="context" required="true" type="string" readOnly="false" description="Context (like /myapp for example)."/>
</parameters>
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Tell Apache httpd that the context can't process new requests."/>
</results>
</operation>
<operation name="enable" description="Tell Apache httpd that all contexts of the node are ready receive requests.">
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Tell Apache httpd that all contexts of the node are ready receive requests."/>
</results>
</operation>
@@ -2271,7 +2271,7 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="context" required="true" type="string" readOnly="false" description="Context (like /myapp for example)."/>
</parameters>
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Tell Apache httpd that the context is ready receive requests."/>
</results>
</operation>
@@ -2298,7 +2298,7 @@ working area for individual server instances</li></ul>"/>
<operation name="refresh" description="Refresh the node sending a new CONFIG message to Apache httpd.">
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Refresh the node sending a new CONFIG message to Apache httpd."/>
</results>
</operation>
@@ -2320,7 +2320,7 @@ working area for individual server instances</li></ul>"/>
<operation name="reset" description="Reset the node connection to Apache httpd.">
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Reset the node connection to Apache httpd."/>
</results>
</operation>
@@ -2329,7 +2329,7 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="waittime" required="false" type="integer" readOnly="false" description="Max amount of time modcluster will for the STOP operation. In seconds. Default 10s"/>
</parameters>
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Tell Apache httpd that the context can't process requests."/>
</results>
</operation>
@@ -2340,7 +2340,7 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="waittime" required="false" type="integer" readOnly="false" description="Max amount of time modcluster will for the STOP operation. In seconds. Default 10s"/>
</parameters>
<results>
- <c:simple-property name="operationResult"/>
+ <c:simple-property name="operationResult" description="Tell Apache httpd that all contexts of the node can't process requests."/>
</results>
</operation>
commit 9227c9fba8ec99ba6fcde22a3e2f2b148336feaf
Author: Simeon Pinder <spinder(a)redhat.com>
Date: Tue Mar 27 04:44:22 2012 -0400
-remove add/remove operations from modcluster server as both seem to be lifecycle operations for container
-add read-proxies-configuration and read-proxies-info methods. Not sure how much more we can do here as
we're just getting unstructured content dumps directly from the http server about the current mod_cluster setup.
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 d1724bc..e0f57d0 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
@@ -71,10 +71,8 @@ import org.rhq.modules.plugins.jbossas7.json.ReadResource;
import org.rhq.modules.plugins.jbossas7.json.Remove;
import org.rhq.modules.plugins.jbossas7.json.Result;
-public class BaseComponent<T extends ResourceComponent<?>> implements ResourceComponent<T>, MeasurementFacet, ConfigurationFacet,
- DeleteResourceFacet,
- CreateChildResourceFacet, OperationFacet
-{
+public class BaseComponent<T extends ResourceComponent<?>> implements ResourceComponent<T>, MeasurementFacet,
+ ConfigurationFacet, DeleteResourceFacet, CreateChildResourceFacet, OperationFacet {
private static final String INTERNAL = "_internal:";
private static final int INTERNAL_SIZE = INTERNAL.length();
private static final String LOCALHOST = "localhost";
@@ -106,10 +104,9 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
ReadResource op = new ReadResource(address);
Result res = connection.execute(op);
- return (res!=null && res.isSuccess()) ? AvailabilityType.UP: AvailabilityType.DOWN;
+ return (res != null && res.isSuccess()) ? AvailabilityType.UP : AvailabilityType.DOWN;
}
-
/**
* Start the resource connection
* @see org.rhq.core.pluginapi.inventory.ResourceComponent#start(org.rhq.core.pluginapi.inventory.ResourceContext)
@@ -122,112 +119,107 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
host = pluginConfiguration.getSimpleValue("hostname", LOCALHOST);
String portString = pluginConfiguration.getSimpleValue("port", DEFAULT_HTTP_MANAGEMENT_PORT);
port = Integer.parseInt(portString);
- managementUser = pluginConfiguration.getSimpleValue("user","-unset-");
- managementPassword = pluginConfiguration.getSimpleValue("password","-unset-");
- connection = new ASConnection(host,port, managementUser, managementPassword);
+ managementUser = pluginConfiguration.getSimpleValue("user", "-unset-");
+ managementPassword = pluginConfiguration.getSimpleValue("password", "-unset-");
+ connection = new ASConnection(host, port, managementUser, managementPassword);
logFileEventDelegate = new LogFileEventResourceComponentHelper(context);
logFileEventDelegate.startLogFileEventPollers();
- }
- else {
- connection = ((BaseComponent)context.getParentResourceComponent()).getASConnection();
+ } else {
+ connection = ((BaseComponent) context.getParentResourceComponent()).getASConnection();
}
path = pluginConfiguration.getSimpleValue("path", null);
address = new Address(path);
key = context.getResourceKey();
- myServerName = context.getResourceKey().substring(context.getResourceKey().lastIndexOf("/")+1);
-
+ myServerName = context.getResourceKey().substring(context.getResourceKey().lastIndexOf("/") + 1);
}
-
/**
* Tear down the resource connection
* @see org.rhq.core.pluginapi.inventory.ResourceComponent#stop()
*/
public void stop() {
- if (!(context.getParentResourceComponent() instanceof BaseComponent)) {
- logFileEventDelegate.stopLogFileEventPollers();
- }
+ if (!(context.getParentResourceComponent() instanceof BaseComponent)) {
+ logFileEventDelegate.stopLogFileEventPollers();
+ }
}
-
-
/**
* Gather measurement data
* @see org.rhq.core.pluginapi.measurement.MeasurementFacet#getValues(org.rhq.core.domain.measurement.MeasurementReport, java.util.Set)
*/
- public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) throws Exception {
-
+ public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) throws Exception {
for (MeasurementScheduleRequest req : metrics) {
if (req.getName().startsWith(INTERNAL))
- processPluginStats(req,report);
+ processPluginStats(req, report);
else {
// Metrics from the application server
- String reqName = req.getName();
+ String reqName = req.getName();
- ComplexRequest request = null;
- Operation op = null;
- if (reqName.contains(":")) {
- request = ComplexRequest.create(reqName);
- op = new ReadAttribute(address, request.getProp());
- } else {
- op = new ReadAttribute(address,reqName); // TODO batching
- }
+ ComplexRequest request = null;
+ Operation op = null;
+ if (reqName.contains(":")) {
+ request = ComplexRequest.create(reqName);
+ op = new ReadAttribute(address, request.getProp());
+ } else {
+ op = new ReadAttribute(address, reqName); // TODO batching
+ }
Result res = connection.execute(op);
if (!res.isSuccess()) {
- log.warn("Getting metric [" + req.getName() +"] at [ " + address + "] failed: " + res.getFailureDescription());
+ log.warn("Getting metric [" + req.getName() + "] at [ " + address + "] failed: "
+ + res.getFailureDescription());
continue;
}
Object val = res.getResult();
- if (val==null) // One of the AS7 ways of telling "This is not implemented" See also AS7-1454
+ if (val == null) // One of the AS7 ways of telling "This is not implemented" See also AS7-1454
continue;
- if (req.getDataType()== DataType.MEASUREMENT) {
+ if (req.getDataType() == DataType.MEASUREMENT) {
if (!val.equals("no metrics available")) { // AS 7 returns this
try {
- if (request != null) {
- HashMap<String,Number> myValues = (HashMap<String, Number>) val;
- for (String key : myValues.keySet()) {
- String sub = request.getSub();
- if (key.equals(sub)) {
- addMetric2Report(report, req, myValues.get(key));
- }
- }
- } else {
- addMetric2Report(report, req, val);
- }
+ if (request != null) {
+ HashMap<String, Number> myValues = (HashMap<String, Number>) val;
+ for (String key : myValues.keySet()) {
+ String sub = request.getSub();
+ if (key.equals(sub)) {
+ addMetric2Report(report, req, myValues.get(key));
+ }
+ }
+ } else {
+ addMetric2Report(report, req, val);
+ }
} catch (NumberFormatException e) {
log.warn("Non numeric input for [" + req.getName() + "] : [" + val + "]");
}
}
- } else if (req.getDataType()== DataType.TRAIT) {
+ } else if (req.getDataType() == DataType.TRAIT) {
String realVal = getStringValue(val);
- MeasurementDataTrait data = new MeasurementDataTrait(req,realVal);
+ MeasurementDataTrait data = new MeasurementDataTrait(req, realVal);
report.addData(data);
}
}
}
}
- private void addMetric2Report(MeasurementReport report, MeasurementScheduleRequest req, Object val) {
- Double d = Double.parseDouble(getStringValue(val));
- MeasurementDataNumeric data = new MeasurementDataNumeric(req, d);
- report.addData(data);
- }
+ private void addMetric2Report(MeasurementReport report, MeasurementScheduleRequest req, Object val) {
+ Double d = Double.parseDouble(getStringValue(val));
+ MeasurementDataNumeric data = new MeasurementDataNumeric(req, d);
+ report.addData(data);
+ }
protected String getStringValue(Object val) {
- String realVal;
+ String realVal = "";
if (val instanceof String)
- realVal = (String)val;
+ realVal = (String) val;
else
realVal = String.valueOf(val);
return realVal;
@@ -250,18 +242,15 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
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.getRequestCount();
+ } else if (name.equals("requestTime")) {
+ val = (double) stats.getRequestTime();
+ } else if (name.equals("maxTime")) {
val = (double) stats.getMaxTime();
- }
- else
+ } else
val = Double.NaN;
- data = new MeasurementDataNumeric(req,val);
+ data = new MeasurementDataNumeric(req, val);
report.addData(data);
}
@@ -269,35 +258,35 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
return connection;
}
-
- protected String getPath() { return path; }
+ protected String getPath() {
+ return path;
+ }
public Configuration loadResourceConfiguration() throws Exception {
ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition();
- ConfigurationLoadDelegate delegate = new ConfigurationLoadDelegate(configDef,connection,address);
+ ConfigurationLoadDelegate delegate = new ConfigurationLoadDelegate(configDef, connection, address);
return delegate.loadResourceConfiguration();
}
-
public void updateResourceConfiguration(ConfigurationUpdateReport report) {
ConfigurationDefinition configDef = context.getResourceType().getResourceConfigurationDefinition();
- ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(configDef,connection,address);
+ ConfigurationWriteDelegate delegate = new ConfigurationWriteDelegate(configDef, connection, address);
delegate.updateResourceConfiguration(report);
}
-
@Override
public void deleteResource() throws Exception {
log.info("delete resource: " + path + " ...");
if (context.getResourceType().getName().equals(MANAGED_SERVER)) {
// We need to do two steps because of AS7-4032
- Operation stop = new Operation("stop",getAddress());
+ Operation stop = new Operation("stop", getAddress());
Result res = getASConnection().execute(stop);
if (!res.isSuccess()) {
- throw new IllegalStateException("Managed server @ " + path + " is still running and can't be stopped. Can't remove it");
+ throw new IllegalStateException("Managed server @ " + path
+ + " is still running and can't be stopped. Can't remove it");
}
}
Operation op = new Remove(address);
@@ -306,22 +295,21 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
throw new IllegalArgumentException("Delete for [" + path + "] failed: " + res.getFailureDescription());
if (path.contains("server-group")) {
// This was a server group level deployment - TODO do we also need to remove the entry in /deployments ?
-/*
-
- for (PROPERTY_VALUE val : address) {
- if (val.getKey().equals("deployment")) {
- ComplexResult res2 = connection.executeComplex(new Operation("remove",val.getKey(),val.getValue()));
- if (!res2.isSuccess())
- throw new IllegalArgumentException("Removal of [" + path + "] falied : " + res2.getFailureDescription());
- }
- }
-*/
+ /*
+
+ for (PROPERTY_VALUE val : address) {
+ if (val.getKey().equals("deployment")) {
+ ComplexResult res2 = connection.executeComplex(new Operation("remove",val.getKey(),val.getValue()));
+ if (!res2.isSuccess())
+ throw new IllegalArgumentException("Removal of [" + path + "] falied : " + res2.getFailureDescription());
+ }
+ }
+ */
}
log.info(" ... done");
}
-
@Override
public CreateResourceReport createResource(CreateResourceReport report) {
@@ -330,8 +318,9 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
} else {
report.setStatus(CreateResourceStatus.INVALID_CONFIGURATION);
Address createAddress = new Address(address);
- createAddress.add(report.getPluginConfiguration().getSimpleValue("path",""),report.getUserSpecifiedResourceName());
- Operation op = new Operation("add",createAddress);
+ createAddress.add(report.getPluginConfiguration().getSimpleValue("path", ""),
+ report.getUserSpecifiedResourceName());
+ Operation op = new Operation("add", createAddress);
for (Property prop : report.getResourceConfiguration().getProperties()) {
if (prop instanceof PropertySimple) {
PropertySimple ps = (PropertySimple) prop;
@@ -365,7 +354,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
ContentServices contentServices = cctx.getContentServices();
String resourceTypeName = report.getResourceType().getName();
- ASUploadConnection uploadConnection = new ASUploadConnection(host,port, managementUser, managementPassword);
+ ASUploadConnection uploadConnection = new ASUploadConnection(host, port, managementUser, managementPassword);
OutputStream out = uploadConnection.getOutputStream(details.getFileName());
contentServices.downloadPackageBitsForChildResource(cctx, resourceTypeName, details.getKey(), out);
@@ -382,14 +371,15 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
String fileName = details.getFileName();
- if (fileName.startsWith("C:\\fakepath\\")) { // TODO this is a hack as the server adds the fake path somehow
- fileName=fileName.substring("C:\\fakepath\\".length());
+ if (fileName.startsWith("C:\\fakepath\\")) { // TODO this is a hack as the server adds the fake path somehow
+ fileName = fileName.substring("C:\\fakepath\\".length());
}
String runtimeName = fileName;
- PropertySimple rtNameProp = report.getPackageDetails().getDeploymentTimeConfiguration().getSimple("runtimeName");
+ PropertySimple rtNameProp = report.getPackageDetails().getDeploymentTimeConfiguration()
+ .getSimple("runtimeName");
if (rtNameProp != null) {
String rtn = rtNameProp.getStringValue();
- if (rtn!=null && !rtn.isEmpty())
+ if (rtn != null && !rtn.isEmpty())
runtimeName = rtn;
}
@@ -408,27 +398,26 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
* @return the passed report with success or failure settings
*/
public CreateResourceReport runDeploymentMagicOnServer(CreateResourceReport report, String runtimeName,
- String deploymentName, String hash) {
+ String deploymentName, String hash) {
boolean toServerGroup = context.getResourceKey().contains("server-group=");
log.info("Deploying [" + runtimeName + "] to domain only= " + !toServerGroup + " ...");
-
ASConnection connection = getASConnection();
- Operation step1 = new Operation("add","deployment",runtimeName);
-// step1.addAdditionalProperty("hash", new PROPERTY_VALUE("BYTES_VALUE", hash));
+ Operation step1 = new Operation("add", "deployment", runtimeName);
+ // step1.addAdditionalProperty("hash", new PROPERTY_VALUE("BYTES_VALUE", hash));
List<Object> content = new ArrayList<Object>(1);
- Map<String,Object> contentValues = new HashMap<String,Object>();
- contentValues.put("hash",new PROPERTY_VALUE("BYTES_VALUE",hash));
+ Map<String, Object> contentValues = new HashMap<String, Object>();
+ contentValues.put("hash", new PROPERTY_VALUE("BYTES_VALUE", hash));
content.add(contentValues);
- step1.addAdditionalProperty("content",content);
+ step1.addAdditionalProperty("content", content);
step1.addAdditionalProperty("name", deploymentName);
step1.addAdditionalProperty("runtime-name", runtimeName);
String resourceKey;
- Result result ;
+ Result result;
CompositeOperation cop = new CompositeOperation();
cop.addStep(step1);
@@ -441,23 +430,22 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
// if standalone, then :deploy the deployment anyway
if (context.getResourceType().getName().contains("Standalone")) {
- Operation step2 = new Operation("deploy",step1.getAddress());
+ Operation step2 = new Operation("deploy", step1.getAddress());
cop.addStep(step2);
}
result = connection.execute(cop);
resourceKey = step1.getAddress().getPath();
- }
- else {
+ } else {
Address serverGroupAddress = new Address(context.getResourceKey());
serverGroupAddress.add("deployment", deploymentName);
- Operation step2 = new Operation("add",serverGroupAddress);
+ Operation step2 = new Operation("add", serverGroupAddress);
cop.addStep(step2);
- Operation step3 = new Operation("deploy",serverGroupAddress);
+ Operation step3 = new Operation("deploy", serverGroupAddress);
cop.addStep(step3);
resourceKey = serverGroupAddress.getPath();
@@ -473,22 +461,21 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
report.setErrorMessage(failureDescription);
report.setStatus(CreateResourceStatus.FAILURE);
log.warn(" ... done with failure: " + failureDescription);
- }
- else {
+ } else {
report.setStatus(CreateResourceStatus.SUCCESS);
report.setResourceName(runtimeName);
report.setResourceKey(resourceKey);
report.getPackageDetails().setSHA256(hash);
report.getPackageDetails().setInstallationTimestamp(System.currentTimeMillis());
- log.info(" ... with success and key [" + resourceKey + "]" );
+ log.info(" ... with success and key [" + resourceKey + "]");
}
return report;
}
@Override
- public OperationResult invokeOperation(String name,
- Configuration parameters) throws InterruptedException, Exception {
+ public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException,
+ Exception {
if (!name.contains(":")) {
String simpleResult = "Operation with name [" + name + "] did not contain a ':'";
@@ -499,26 +486,26 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
int colonPos = name.indexOf(':');
String what = name.substring(0, colonPos);
- String op = name.substring(colonPos+1);
- Operation operation=null;
+ String op = name.substring(colonPos + 1);
+ Operation operation = null;
Address theAddress = new Address();
if (what.equals("server-group")) {
- String groupName = parameters.getSimpleValue("name","");
- String profile = parameters.getSimpleValue("profile","default");
+ String groupName = parameters.getSimpleValue("name", "");
+ String profile = parameters.getSimpleValue("profile", "default");
theAddress.add("server-group", groupName);
- operation = new Operation(op,theAddress);
- operation.addAdditionalProperty("profile",profile);
+ operation = new Operation(op, theAddress);
+ operation.addAdditionalProperty("profile", profile);
} else if (what.equals("destination")) {
theAddress.add(address);
- String newName = parameters.getSimpleValue("name","");
- String type = parameters.getSimpleValue("type","jms-queue").toLowerCase();
+ String newName = parameters.getSimpleValue("name", "");
+ String type = parameters.getSimpleValue("type", "jms-queue").toLowerCase();
theAddress.add(type, newName);
PropertyList jndiNamesProp = parameters.getList("entries");
- if (jndiNamesProp==null || jndiNamesProp.getList().isEmpty()) {
+ if (jndiNamesProp == null || jndiNamesProp.getList().isEmpty()) {
OperationResult fail = new OperationResult();
fail.setErrorMessage("No jndi bindings given");
return fail;
@@ -529,51 +516,49 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
jndiNames.add(ps.getStringValue());
}
- operation = new Operation(op,theAddress);
- operation.addAdditionalProperty("entries",jndiNames);
+ operation = new Operation(op, theAddress);
+ operation.addAdditionalProperty("entries", jndiNames);
if (type.equals("jms-queue")) {
PropertySimple ps = (PropertySimple) parameters.get("durable");
- if (ps!=null) {
+ if (ps != null) {
boolean durable = ps.getBooleanValue();
- operation.addAdditionalProperty("durable",durable);
+ operation.addAdditionalProperty("durable", durable);
}
- String selector = parameters.getSimpleValue("selector","");
+ String selector = parameters.getSimpleValue("selector", "");
if (!selector.isEmpty())
operation.addAdditionalProperty("selector", selector);
}
-
} else if (what.equals("domain")) {
- operation = new Operation(op,new Address());
+ operation = new Operation(op, new Address());
} else if (what.equals("domain-deployment")) {
if (op.equals("promote")) {
- String serverGroup = parameters.getSimpleValue("server-group","-not set-");
+ String serverGroup = parameters.getSimpleValue("server-group", "-not set-");
List<String> serverGroups = new ArrayList<String>();
if (serverGroup.equals("__all")) {
serverGroups.addAll(getServerGroups());
- }
- else {
+ } else {
serverGroups.add(serverGroup);
}
String resourceKey = context.getResourceKey();
- resourceKey = resourceKey.substring(resourceKey.indexOf("=")+1);
+ resourceKey = resourceKey.substring(resourceKey.indexOf("=") + 1);
log.info("Promoting [" + resourceKey + "] to server group(s) [" + Arrays.asList(serverGroups) + "]");
PropertySimple simple = parameters.getSimple("enabled");
Boolean enabled = false;
- if (simple!=null && simple.getBooleanValue()!=null)
- enabled= simple.getBooleanValue();
+ if (simple != null && simple.getBooleanValue() != null)
+ enabled = simple.getBooleanValue();
operation = new CompositeOperation();
for (String theGroup : serverGroups) {
theAddress = new Address();
- theAddress.add("server-group",theGroup);
+ theAddress.add("server-group", theGroup);
theAddress.add("deployment", resourceKey);
- Operation step = new Operation("add",theAddress);
- step.addAdditionalProperty("enabled",enabled);
- ((CompositeOperation)operation).addStep(step);
+ Operation step = new Operation("add", theAddress);
+ step.addAdditionalProperty("enabled", enabled);
+ ((CompositeOperation) operation).addStep(step);
}
}
} else if (what.equals("subsystem")) {
@@ -581,27 +566,25 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
}
OperationResult operationResult = new OperationResult();
- if (operation!=null) {
+ if (operation != null) {
Result result = connection.execute(operation);
- if (result==null) {
+ if (result == null) {
operationResult.setErrorMessage("Connection was null - is the server running?");
return operationResult;
}
if (!result.isSuccess()) {
operationResult.setErrorMessage(result.getFailureDescription());
- }
- else {
+ } else {
String tmp;
- if (result.getResult()==null)
+ if (result.getResult() == null)
tmp = "-none provided by the server-";
else
tmp = result.getResult().toString();
operationResult.setSimpleResult(tmp);
}
- }
- else {
+ } else {
operationResult.setErrorMessage("No valid operation was given for input [" + name + "]");
}
return operationResult;
@@ -609,7 +592,7 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
@SuppressWarnings("unchecked")
private Collection<String> getServerGroups() {
- Operation op = new ReadChildrenNames(new Address(),"server-group");
+ Operation op = new ReadChildrenNames(new Address(), "server-group");
Result res = connection.execute(op);
return (Collection<String>) res.getResult();
@@ -619,23 +602,22 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
PropertySimpleType type = propDef.getType();
switch (type) {
- case STRING:
- return prop.getStringValue();
- case INTEGER:
- return prop.getIntegerValue();
- case BOOLEAN:
- return prop.getBooleanValue();
- case LONG:
- return prop.getLongValue();
- case FLOAT:
- return prop.getFloatValue();
- case DOUBLE:
- return prop.getDoubleValue();
- default:
- return prop.getStringValue();
+ case STRING:
+ return prop.getStringValue();
+ case INTEGER:
+ return prop.getIntegerValue();
+ case BOOLEAN:
+ return prop.getBooleanValue();
+ case LONG:
+ return prop.getLongValue();
+ case FLOAT:
+ return prop.getFloatValue();
+ case DOUBLE:
+ return prop.getDoubleValue();
+ default:
+ return prop.getStringValue();
}
-
}
///// Those two are used to 'inject' the connection and the path from tests.
@@ -648,32 +630,30 @@ public class BaseComponent<T extends ResourceComponent<?>> implements ResourceCo
this.address = new Address(path);
}
-
public Address getAddress() {
return address;
}
-
private static class ComplexRequest {
- private String prop;
- private String sub;
-
- private ComplexRequest(String prop, String sub) {
- this.prop = prop;
- this.sub = sub;
- }
-
- public String getProp() {
- return prop;
- }
-
- public String getSub() {
- return sub;
- }
-
- public static ComplexRequest create(String requestName) {
- StringTokenizer tokenizer = new StringTokenizer(requestName, ":");
- return new ComplexRequest(tokenizer.nextToken(), tokenizer.nextToken());
- }
- }
+ private String prop;
+ private String sub;
+
+ private ComplexRequest(String prop, String sub) {
+ this.prop = prop;
+ this.sub = sub;
+ }
+
+ public String getProp() {
+ return prop;
+ }
+
+ public String getSub() {
+ return sub;
+ }
+
+ public static ComplexRequest create(String requestName) {
+ StringTokenizer tokenizer = new StringTokenizer(requestName, ":");
+ return new ComplexRequest(tokenizer.nextToken(), tokenizer.nextToken());
+ }
+ }
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
index 34222d3..9ddb1ec 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
@@ -31,22 +31,24 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
if ("list-proxies".equals(name)) {
result = getASConnection().execute(op);
- ArrayList container = (ArrayList) result.getResult();
- if ((container != null) && !container.isEmpty()) {
- Object type = container.get(0);
- String values = "";
- if (type instanceof String) {
- for (int i = 0; i < container.size(); i++) {
- values += container.get(i) + ",";
+ if ((result != null) && (result.isSuccess())) {
+ ArrayList container = (ArrayList) result.getResult();
+ if ((container != null) && !container.isEmpty()) {
+ Object type = container.get(0);
+ String values = "";
+ if (type instanceof String) {
+ for (int i = 0; i < container.size(); i++) {
+ values += container.get(i) + ",";
+ }
+ values = values.substring(0, values.length() - 1);
+ } else {
+ values = container.toString();
}
- values = values.substring(0, values.length() - 1);
- } else {
- values = container.toString();
- }
- operationResult.getComplexResults().put(new PropertySimple("proxy-list", values));
+ operationResult.getComplexResults().put(new PropertySimple("proxy-list", values));
- } else {//return empty value.
- operationResult.getComplexResults().put(new PropertySimple("proxy-list", ""));
+ } else {//return empty value.
+ operationResult.getComplexResults().put(new PropertySimple("proxy-list", ""));
+ }
}
} else if ("add-proxy".equals(name)) {
addAdditionalToOp(op, parameters, "host", false);
@@ -62,6 +64,57 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
if (result.isSuccess()) {
operationResult.setSimpleResult("Success");
}
+ } else if ("read-proxies-configuration".equals(name)) {
+ //spinder 3/25/12: Can we do better than displaying all content as massive string?
+ // Content is unstructured/variable from httpd server.
+ result = getASConnection().execute(op);
+ if ((result != null) && (result.isSuccess())) {
+ ArrayList container = (ArrayList) result.getResult();
+ if ((container != null) && !container.isEmpty()) {
+ Object type = container.get(0);
+ String values = "";
+ if (type instanceof String) {
+ for (int i = 0; i < container.size(); i++) {
+ values += container.get(i) + ",";
+ }
+ values = values.substring(0, values.length() - 1);
+ } else {
+ values = container.toString();
+ }
+ operationResult.getComplexResults().put(new PropertySimple("current-proxy-config", values));
+
+ } else {//return empty value.
+ operationResult.getComplexResults().put(new PropertySimple("current-proxy-config", ""));
+ }
+ }
+ } else if ("read-proxies-info".equals(name)) {
+ //spinder 3/25/12: Can we do better than displaying all content as massive string?
+ // Content is unstructured/variable from httpd server.
+ result = getASConnection().execute(op);
+ if ((result != null) && (result.isSuccess())) {
+ ArrayList container = (ArrayList) result.getResult();
+ if ((container != null) && !container.isEmpty()) {
+ Object type = container.get(0);
+ String values = "";
+ if (type instanceof String) {
+ for (int i = 0; i < container.size(); i++) {
+ values += container.get(i) + ",";
+ }
+ values = values.substring(0, values.length() - 1);
+ } else {
+ values = container.toString();
+ }
+ operationResult.getComplexResults().put(new PropertySimple("current-proxy-info", values));
+
+ } else {//return empty value.
+ operationResult.getComplexResults().put(new PropertySimple("current-proxy-info", ""));
+ }
+ }
+ } else {
+ /*
+ * This is a catch all for operations that are not explicitly treated above.
+ */
+ op = new Operation(name, address);
}
if (!result.isSuccess()) {
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 798a7c0..7cc8415 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
@@ -2208,7 +2208,7 @@ working area for individual server instances</li></ul>"/>
</service>
</server>
- <serice name="ModCluster"
+ <server name="ModCluster"
class="ModClusterComponent"
discovery="SubsystemDiscovery"
description="Mod_cluster support"
@@ -2224,14 +2224,14 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="path" readOnly="true" default="subsystem=modcluster"/>
</plugin-configuration>
- <operation name="add" description="Operation adding the modcluster subsystem.">
+ <!--<operation name="add" description="Operation adding the modcluster subsystem.">
<parameters>
<c:simple-property name="mod-cluster-config" required="false" type="-object-" readOnly="false" description="The common modcluster configuration."/>
</parameters>
<results>
<c:simple-property name="operationResult"/>
</results>
- </operation>
+ </operation>-->
<operation name="add-proxy" description="Add the proxy to the list of httpd connected to the node.">
<parameters>
@@ -2282,17 +2282,31 @@ working area for individual server instances</li></ul>"/>
</results>
</operation>
+ <operation name="read-proxies-configuration" description="Send a DUMP to httpd and display the result.">
+ <results>
+ <!-- Result of the DUMP command.-->
+ <c:simple-property name="current-proxy-config" description="Result of the DUMP command. Snapshot of httpd/modcluster configuration."/>
+ </results>
+ </operation>
+
+ <operation name="read-proxies-info" description="Send a INFO to httpd and display the result.">
+ <results>
+ <!-- Result of the INFO command.-->
+ <c:simple-property name="current-proxy-info" description="Result of the INFO command. Snapshot of httpd/modcluster proxy information."/>
+ </results>
+ </operation>
+
<operation name="refresh" description="Refresh the node sending a new CONFIG message to Apache httpd.">
<results>
<c:simple-property name="operationResult"/>
</results>
</operation>
- <operation name="remove" description="Operation removing the modcluster subsystem.">
+ <!--<operation name="remove" description="Operation removing the modcluster subsystem.">
<results>
<c:simple-property name="operationResult"/>
</results>
- </operation>
+ </operation>-->
<operation name="remove-proxy" description="Remove the proxy to the list of httpd connected to the node.">
<parameters>
@@ -2356,7 +2370,7 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="balancer" required="false" type="string" readOnly="false" defaultValue="mycluster" description="The balancer name."/>
<c:simple-property name="domain" required="false" type="string" readOnly="false" description="loadBalancingGroup name."/>
</resource-configuration>
- </service>
+ </server>
<server name="Naming"
discovery="SubsystemDiscovery"
commit d1f9fbfc2b09d26db259edfebd76c8f775587031
Author: Simeon Pinder <spinder(a)redhat.com>
Date: Tue Mar 27 02:06:06 2012 -0400
enable http-proxy operations.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
index 5dc7b11..34222d3 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/ModClusterComponent.java
@@ -1,9 +1,8 @@
package org.rhq.modules.plugins.jbossas7;
-import java.util.Map;
+import java.util.ArrayList;
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.domain.configuration.definition.ConfigurationDefinition;
import org.rhq.core.pluginapi.configuration.ConfigurationFacet;
@@ -27,20 +26,48 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
public OperationResult invokeOperation(String name, Configuration parameters) throws Exception {
Operation op = new Operation(name, getAddress());
- Result result = getASConnection().execute(op);
+ OperationResult operationResult = new OperationResult();
+ Result result = null;
+
+ if ("list-proxies".equals(name)) {
+ result = getASConnection().execute(op);
+ ArrayList container = (ArrayList) result.getResult();
+ if ((container != null) && !container.isEmpty()) {
+ Object type = container.get(0);
+ String values = "";
+ if (type instanceof String) {
+ for (int i = 0; i < container.size(); i++) {
+ values += container.get(i) + ",";
+ }
+ values = values.substring(0, values.length() - 1);
+ } else {
+ values = container.toString();
+ }
+ operationResult.getComplexResults().put(new PropertySimple("proxy-list", values));
- 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());
+ } else {//return empty value.
+ operationResult.getComplexResults().put(new PropertySimple("proxy-list", ""));
+ }
+ } else if ("add-proxy".equals(name)) {
+ addAdditionalToOp(op, parameters, "host", false);
+ addAdditionalToOp(op, parameters, "port", false);
+ result = getASConnection().execute(op);
+ if (result.isSuccess()) {
+ operationResult.setSimpleResult("Success");
+ }
+ } else if ("remove-proxy".equals(name)) {
+ addAdditionalToOp(op, parameters, "host", false);
+ addAdditionalToOp(op, parameters, "port", false);
+ result = getASConnection().execute(op);
+ if (result.isSuccess()) {
+ operationResult.setSimpleResult("Success");
+ }
}
- OperationResult operationResult = new OperationResult();
- if (result.isSuccess()) {
- operationResult.setSimpleResult(result.getResult().toString());
- } else {
+ if (!result.isSuccess()) {
operationResult.setErrorMessage(result.getFailureDescription());
}
+
return operationResult;
}
@@ -69,4 +96,16 @@ public class ModClusterComponent extends BaseComponent implements OperationFacet
delegate.updateResourceConfiguration(report);
}
+
+ void addAdditionalToOp(Operation op, Configuration parameters, String parameterName, boolean optional) {
+ String value = parameters.getSimpleValue(parameterName, null);
+ if (value == null) {
+ if (!optional) {
+ throw new IllegalArgumentException("Required parameter [" + parameterName + "] for operation ["
+ + op.getName() + "] is not defined.");
+ }
+ } else {
+ op.addAdditionalProperty(parameterName, value);
+ }
+ }
}
commit ba149d0361008bc06d1a7d2c724359a8d13bf551
Author: Simeon Pinder <spinder(a)redhat.com>
Date: Tue Mar 27 02:03:46 2012 -0400
-Move modcluster server -> service.
-enable several modcluster operations
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 ca285ef..798a7c0 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
@@ -2208,7 +2208,7 @@ working area for individual server instances</li></ul>"/>
</service>
</server>
- <server name="ModCluster"
+ <serice name="ModCluster"
class="ModClusterComponent"
discovery="SubsystemDiscovery"
description="Mod_cluster support"
@@ -2224,12 +2224,111 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="path" readOnly="true" default="subsystem=modcluster"/>
</plugin-configuration>
- <!-- Disable for now. This is available and modifiable by Configuration options.
- <operation name="list-proxies" description="Read the list of httpd connected to the nodes.">
- <results>
- <c:simple-property name="operationResult"/>
- </results>
- </operation>-->
+ <operation name="add" description="Operation adding the modcluster subsystem.">
+ <parameters>
+ <c:simple-property name="mod-cluster-config" required="false" type="-object-" readOnly="false" description="The common modcluster configuration."/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="add-proxy" description="Add the proxy to the list of httpd connected to the node.">
+ <parameters>
+ <c:simple-property name="host" required="true" type="string" readOnly="false" description="Hostname of the proxy (Apache httpd)"/>
+ <c:simple-property name="port" required="true" type="integer" readOnly="false" description="Port where the proxy (Apache httpd) is receiving the MCMP"/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="disable" description="Tell Apache httpd that all contexts of the node can't process new requests.">
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="disable-context" description="Tell Apache httpd that the context can't process new requests.">
+ <parameters>
+ <c:simple-property name="virtualhost" required="true" type="string" readOnly="false" description="Name of the virtual-host containing the context."/>
+ <c:simple-property name="context" required="true" type="string" readOnly="false" description="Context (like /myapp for example)."/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="enable" description="Tell Apache httpd that all contexts of the node are ready receive requests.">
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="enable-context" description="Tell Apache httpd that the context is ready receive requests.">
+ <parameters>
+ <c:simple-property name="virtualhost" required="true" type="string" readOnly="false" description="Name of the virtual-host containing the context."/>
+ <c:simple-property name="context" required="true" type="string" readOnly="false" description="Context (like /myapp for example)."/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="list-proxies" description="Read the list of httpd connected to the node.">
+ <results>
+ <!-- List of proxies the node is connected to. Format (hostname:port) separated with comas.-->
+ <c:simple-property name="proxy-list" description="List of proxies the node is connected to. Format (hostname:port) separated with comas"/>
+ </results>
+ </operation>
+
+ <operation name="refresh" description="Refresh the node sending a new CONFIG message to Apache httpd.">
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="remove" description="Operation removing the modcluster subsystem.">
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="remove-proxy" description="Remove the proxy to the list of httpd connected to the node.">
+ <parameters>
+ <c:simple-property name="host" required="true" type="string" readOnly="false" description="Hostname of the proxy (Apache httpd)"/>
+ <c:simple-property name="port" required="true" type="integer" readOnly="false" description="Port where the proxy (Apache httpd) is receiving the MCMP"/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="reset" description="Reset the node connection to Apache httpd.">
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="stop" description="Tell Apache httpd that all contexts of the node can't process requests.">
+ <parameters>
+ <c:simple-property name="waittime" required="false" type="integer" readOnly="false" description="Max amount of time modcluster will for the STOP operation. In seconds. Default 10s"/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
+
+ <operation name="stop-context" description="Tell Apache httpd that the context can't process requests.">
+ <parameters>
+ <c:simple-property name="virtualhost" required="true" type="string" readOnly="false" description="Name of the virtual-host containing the context."/>
+ <c:simple-property name="context" required="true" type="string" readOnly="false" description="Context (like /myapp for example)."/>
+ <c:simple-property name="waittime" required="false" type="integer" readOnly="false" description="Max amount of time modcluster will for the STOP operation. In seconds. Default 10s"/>
+ </parameters>
+ <results>
+ <c:simple-property name="operationResult"/>
+ </results>
+ </operation>
<resource-configuration>
<c:simple-property name="advertise-socket" required="false" type="string" readOnly="false" defaultValue="224.0.1.105:23364"
@@ -2255,9 +2354,9 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="ttl" required="false" type="integer" readOnly="false" defaultValue="60" description="Time to live (in seconds) for idle connections above smax"/>
<c:simple-property name="node-timeout" required="false" type="integer" readOnly="false" defaultValue="-1" description="Timeout (in seconds) for proxy connections to a node."/>
<c:simple-property name="balancer" required="false" type="string" readOnly="false" defaultValue="mycluster" description="The balancer name."/>
- <c:simple-property name="domain" required="false" type="string" readOnly="false" description="loadBalancingGroup name."/>
+ <c:simple-property name="domain" required="false" type="string" readOnly="false" description="loadBalancingGroup name."/>
</resource-configuration>
- </server>
+ </service>
<server name="Naming"
discovery="SubsystemDiscovery"
commit f771ea21552eee45704f67401e37b3995f2dd3a2
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Tue Mar 27 15:04:25 2012 +0200
Trivial - formatting the Apache plugin source code. It was a beeping mess.
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryComponent.java
index f8ebd79..661f556 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryComponent.java
@@ -71,16 +71,16 @@ public class ApacheDirectoryComponent implements ResourceComponent<ApacheVirtual
public Configuration loadResourceConfiguration() throws Exception {
if (!isAugeasEnabled()) {
- throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
+ throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
ApacheVirtualHostServiceComponent parentVirtualHost = resourceContext.getParentResourceComponent();
AugeasComponent comp = getAugeas();
try {
AugeasTree tree = comp.getAugeasTree(ApacheServerComponent.AUGEAS_HTTP_MODULE_NAME);
- ConfigurationDefinition resourceConfigDef = resourceContext.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition resourceConfigDef =
+ resourceContext.getResourceType().getResourceConfigurationDefinition();
AugeasNode virtualHostNode = parentVirtualHost.getNode(tree);
ApacheAugeasMapping mapping = new ApacheAugeasMapping(tree);
@@ -96,13 +96,13 @@ public class ApacheDirectoryComponent implements ResourceComponent<ApacheVirtual
report.setErrorMessage(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
return;
}
-
+
AugeasComponent comp = getAugeas();
AugeasTree tree = null;
try {
tree = comp.getAugeasTree(ApacheServerComponent.AUGEAS_HTTP_MODULE_NAME);
- ConfigurationDefinition resourceConfigDef = resourceContext.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition resourceConfigDef =
+ resourceContext.getResourceType().getResourceConfigurationDefinition();
ApacheAugeasMapping mapping = new ApacheAugeasMapping(tree);
AugeasNode directoryNode = getNode(tree.getRootNode());
mapping.updateAugeas(directoryNode, report.getConfiguration(), resourceConfigDef);
@@ -127,9 +127,9 @@ public class ApacheDirectoryComponent implements ResourceComponent<ApacheVirtual
if (!isAugeasEnabled()) {
throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
ApacheVirtualHostServiceComponent parentVirtualHost = resourceContext.getParentResourceComponent();
-
+
AugeasComponent comp = getAugeas();
try {
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryDiscoveryComponent.java
index 8a3cac8..2ea5be2 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryDiscoveryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheDirectoryDiscoveryComponent.java
@@ -78,8 +78,8 @@ public class ApacheDirectoryDiscoveryComponent implements ResourceDiscoveryCompo
try {
AugeasNode parentNode = context.getParentResourceComponent().getNode(tree);
- List<AugeasNode> directories = AugeasNodeSearch.searchNode(PARENT_DIRECTIVES, DIRECTORY_DIRECTIVE,
- parentNode);
+ List<AugeasNode> directories =
+ AugeasNodeSearch.searchNode(PARENT_DIRECTIVES, DIRECTORY_DIRECTIVE, parentNode);
ResourceType resourceType = context.getResourceType();
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheErrorLogEntryProcessor.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheErrorLogEntryProcessor.java
index 8fe3e14..077337c 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheErrorLogEntryProcessor.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheErrorLogEntryProcessor.java
@@ -78,8 +78,7 @@ public class ApacheErrorLogEntryProcessor extends MultiLineLogEntryProcessor {
SeverityLevel severityLevel;
try {
severityLevel = SeverityLevel.valueOf(severityLevelString.toUpperCase());
- }
- catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException e) {
throw new ParseException("Unknown severity level: " + severityLevelString);
}
EventSeverity severity = LEVEL_TO_SEVERITY_MAP.get(severityLevel);
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheFilesComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheFilesComponent.java
index 58b823c..55250c8 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheFilesComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheFilesComponent.java
@@ -39,11 +39,13 @@ import org.rhq.core.pluginapi.inventory.ResourceContext;
*
* @author Lukas Krejci
*/
-public class ApacheFilesComponent implements ResourceComponent<ApacheServerComponent>, ConfigurationFacet, DeleteResourceFacet {
+public class ApacheFilesComponent implements ResourceComponent<ApacheServerComponent>, ConfigurationFacet,
+ DeleteResourceFacet {
ResourceContext<ApacheServerComponent> resourceContext;
-
- public void start(ResourceContext<ApacheServerComponent> context) throws InvalidPluginConfigurationException, Exception {
+
+ public void start(ResourceContext<ApacheServerComponent> context) throws InvalidPluginConfigurationException,
+ Exception {
// TODO Auto-generated method stub
resourceContext = context;
}
@@ -62,7 +64,8 @@ public class ApacheFilesComponent implements ResourceComponent<ApacheServerCompo
*/
public Configuration loadResourceConfiguration() throws Exception {
// TODO Auto-generated method stub
- return resourceContext.getResourceType().getResourceConfigurationDefinition().getDefaultTemplate().createConfiguration();
+ return resourceContext.getResourceType().getResourceConfigurationDefinition().getDefaultTemplate()
+ .createConfiguration();
}
/* (non-Javadoc)
@@ -77,8 +80,7 @@ public class ApacheFilesComponent implements ResourceComponent<ApacheServerCompo
*/
public void deleteResource() throws Exception {
// TODO Auto-generated method stub
-
- }
+ }
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleComponent.java
index 8554038..010b0f6 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleComponent.java
@@ -68,7 +68,7 @@ public class ApacheIfModuleComponent implements ResourceComponent<ApacheVirtualH
if (!isAugeasEnabled()) {
throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
AugeasComponent comp = null;
try {
comp = parentComponent.getAugeas();
@@ -90,7 +90,7 @@ public class ApacheIfModuleComponent implements ResourceComponent<ApacheVirtualH
report.setErrorMessage(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
return;
}
-
+
AugeasComponent comp = null;
AugeasTree tree = null;
try {
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryComponent.java
index c97c28c..ba6e85f 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryComponent.java
@@ -64,9 +64,9 @@ public class ApacheIfModuleDirectoryComponent implements ResourceComponent<Apach
public Configuration loadResourceConfiguration() throws Exception {
if (!isAugeasEnabled()) {
- throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
+ throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
ConfigurationDefinition resourceConfigDef = context.getResourceType().getResourceConfigurationDefinition();
AugeasComponent comp = parentComponent.getAugeas();
AugeasTree tree = null;
@@ -86,7 +86,7 @@ public class ApacheIfModuleDirectoryComponent implements ResourceComponent<Apach
report.setStatus(ConfigurationUpdateStatus.FAILURE);
report.setErrorMessage(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
AugeasComponent comp = parentComponent.getAugeas();
AugeasTree tree = null;
try {
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryDiscoveryComponent.java
index d3bbe15..ad00dfa 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryDiscoveryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDirectoryDiscoveryComponent.java
@@ -77,4 +77,4 @@ public class ApacheIfModuleDirectoryDiscoveryComponent implements ResourceDiscov
comp.close();
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDiscoveryComponent.java
index e7165fd..277a5de 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDiscoveryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheIfModuleDiscoveryComponent.java
@@ -79,4 +79,4 @@ public class ApacheIfModuleDiscoveryComponent implements ResourceDiscoveryCompon
comp.close();
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheLocationComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheLocationComponent.java
index 8ebbfde..ed27cca 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheLocationComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheLocationComponent.java
@@ -40,11 +40,13 @@ import org.rhq.plugins.platform.PlatformComponent;
*
* @author Lukas Krejci
*/
-public class ApacheLocationComponent implements ResourceComponent<ApacheServerComponent>, ConfigurationFacet, DeleteResourceFacet {
+public class ApacheLocationComponent implements ResourceComponent<ApacheServerComponent>, ConfigurationFacet,
+ DeleteResourceFacet {
ResourceContext<ApacheServerComponent> resourceContext;
-
- public void start(ResourceContext<ApacheServerComponent> context) throws InvalidPluginConfigurationException, Exception {
+
+ public void start(ResourceContext<ApacheServerComponent> context) throws InvalidPluginConfigurationException,
+ Exception {
// TODO Auto-generated method stub
resourceContext = context;
}
@@ -63,7 +65,8 @@ public class ApacheLocationComponent implements ResourceComponent<ApacheServerCo
*/
public Configuration loadResourceConfiguration() throws Exception {
// TODO Auto-generated method stub
- return resourceContext.getResourceType().getResourceConfigurationDefinition().getDefaultTemplate().createConfiguration();
+ return resourceContext.getResourceType().getResourceConfigurationDefinition().getDefaultTemplate()
+ .createConfiguration();
}
/* (non-Javadoc)
@@ -78,8 +81,7 @@ public class ApacheLocationComponent implements ResourceComponent<ApacheServerCo
*/
public void deleteResource() throws Exception {
// TODO Auto-generated method stub
-
- }
+ }
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApachePluginLifecycleListener.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApachePluginLifecycleListener.java
index 5b7e750..78fdcee 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApachePluginLifecycleListener.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApachePluginLifecycleListener.java
@@ -53,7 +53,7 @@ public class ApachePluginLifecycleListener implements PluginLifecycleListener {
if (!destination.canWrite()) {
throw new Exception("Creating of temporary file for lens failed. Destination file "
- + destination.getAbsolutePath() + " is not accessible.");
+ + destination.getAbsolutePath() + " is not accessible.");
}
OutputStream out = new FileOutputStream(destination);
@@ -88,6 +88,3 @@ public class ApachePluginLifecycleListener implements PluginLifecycleListener {
}
}
}
-
-
-
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java
index e1e3207..6fff23f 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerComponent.java
@@ -103,9 +103,10 @@ import org.rhq.rhqtransform.AugeasRHQComponent;
public class ApacheServerComponent implements AugeasRHQComponent, ResourceComponent<PlatformComponent>,
MeasurementFacet, OperationFacet, ConfigurationFacet, CreateChildResourceFacet {
- public static final String CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE = "Configuration and child resource creation/deletion support for Apache is optional. "
- + "If you switched it on by enabling Augeas support in the connection settings of the Apache server resource and still get this message, "
- + "it means that either your Apache version is not supported (only Apache 2.x is supported) or Augeas is not available on your platform.";
+ public static final String CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE =
+ "Configuration and child resource creation/deletion support for Apache is optional. "
+ + "If you switched it on by enabling Augeas support in the connection settings of the Apache server resource and still get this message, "
+ + "it means that either your Apache version is not supported (only Apache 2.x is supported) or Augeas is not available on your platform.";
private final Log log = LogFactory.getLog(this.getClass());
@@ -215,19 +216,20 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
File executablePath = getExecutablePath();
try {
- this.binaryInfo = ApacheBinaryInfo.getInfo(executablePath.getPath(),
- this.resourceContext.getSystemInformation());
+ this.binaryInfo =
+ ApacheBinaryInfo.getInfo(executablePath.getPath(), this.resourceContext.getSystemInformation());
} catch (Exception e) {
throw new InvalidPluginConfigurationException("'" + executablePath
+ "' is not a valid Apache executable (" + e + ").");
}
- this.operationsDelegate = new ApacheServerOperationsDelegate(this, pluginConfig,
- this.resourceContext.getSystemInformation());
+ this.operationsDelegate =
+ new ApacheServerOperationsDelegate(this, pluginConfig, this.resourceContext.getSystemInformation());
//init the module names with the defaults
- moduleNames = new HashMap<String, String>(ApacheServerDiscoveryComponent.getDefaultModuleNames(binaryInfo
- .getVersion()));
+ moduleNames =
+ new HashMap<String, String>(ApacheServerDiscoveryComponent.getDefaultModuleNames(binaryInfo
+ .getVersion()));
//and add the user-provided overrides/additions
PropertyList list = resourceContext.getPluginConfiguration().getList(PLUGIN_CONFIG_CUSTOM_MODULE_NAMES);
@@ -345,8 +347,8 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
AugeasComponent comp = getAugeas();
try {
- ConfigurationDefinition resourceConfigDef = resourceContext.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition resourceConfigDef =
+ resourceContext.getResourceType().getResourceConfigurationDefinition();
AugeasTree tree = comp.getAugeasTree(AUGEAS_HTTP_MODULE_NAME);
ApacheAugeasMapping mapping = new ApacheAugeasMapping(tree);
@@ -372,8 +374,8 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
AugeasTree tree = null;
try {
tree = comp.getAugeasTree(AUGEAS_HTTP_MODULE_NAME);
- ConfigurationDefinition resourceConfigDef = resourceContext.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition resourceConfigDef =
+ resourceContext.getResourceType().getResourceConfigurationDefinition();
ApacheAugeasMapping mapping = new ApacheAugeasMapping(tree);
mapping.updateAugeas(tree.getRootNode(), report.getConfiguration(), resourceConfigDef);
@@ -409,8 +411,8 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
File tempDir = resourceContext.getDataDirectory();
if (!tempDir.exists())
throw new RuntimeException("Loading of lens failed");
- AugeasConfigurationApache config = new AugeasConfigurationApache(tempDir.getAbsolutePath(),
- resourceContext.getPluginConfiguration());
+ AugeasConfigurationApache config =
+ new AugeasConfigurationApache(tempDir.getAbsolutePath(), resourceContext.getPluginConfiguration());
return config;
}
@@ -432,13 +434,13 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
if (ApacheVirtualHostServiceComponent.RESOURCE_TYPE_NAME.equals(report.getResourceType().getName())) {
Configuration vhostResourceConfig = report.getResourceConfiguration();
- ConfigurationDefinition vhostResourceConfigDef = report.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition vhostResourceConfigDef =
+ report.getResourceType().getResourceConfigurationDefinition();
Configuration vhostPluginConfig = report.getPluginConfiguration();
String vhostDef = report.getUserSpecifiedResourceName();
- String serverName = vhostResourceConfig.getSimpleValue(
- ApacheVirtualHostServiceComponent.SERVER_NAME_CONFIG_PROP, null);
+ String serverName =
+ vhostResourceConfig.getSimpleValue(ApacheVirtualHostServiceComponent.SERVER_NAME_CONFIG_PROP, null);
//determine the resource key
String resourceKey = vhostDef;
@@ -490,8 +492,9 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
int seq = existingVhosts.size() + 1;
Configuration pluginConfig = resourceContext.getPluginConfiguration();
- String creationType = pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_VHOST_CREATION_POLICY,
- PLUGIN_CONFIG_VHOST_PER_FILE_PROP_VALUE);
+ String creationType =
+ pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_VHOST_CREATION_POLICY,
+ PLUGIN_CONFIG_VHOST_PER_FILE_PROP_VALUE);
AugeasNode vhost = null;
@@ -526,8 +529,8 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
//that would load the file, so we have to
//add the include directive to the main conf.
List<AugeasNode> includes = tree.matchRelative(tree.getRootNode(), "Include");
- AugeasNode include = tree.createNode(tree.getRootNode(), "Include", null,
- includes.size() + 1);
+ AugeasNode include =
+ tree.createNode(tree.getRootNode(), "Include", null, includes.size() + 1);
tree.createNode(include, "param", vhostFile, 0);
tree.save();
}
@@ -756,8 +759,9 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
@NotNull
public ConfigurationTimestamp getConfigurationTimestamp() {
- AugeasConfigurationApache config = new AugeasConfigurationApache(resourceContext.getTemporaryDirectory()
- .getAbsolutePath(), resourceContext.getPluginConfiguration());
+ AugeasConfigurationApache config =
+ new AugeasConfigurationApache(resourceContext.getTemporaryDirectory().getAbsolutePath(),
+ resourceContext.getPluginConfiguration());
return new ConfigurationTimestamp(config.getAllConfigurationFiles());
}
@@ -897,15 +901,16 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
private void startEventPollers() {
Configuration pluginConfig = this.resourceContext.getPluginConfiguration();
- Boolean enabled = Boolean.valueOf(pluginConfig
- .getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_EVENTS_ENABLED, null));
+ Boolean enabled =
+ Boolean.valueOf(pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_EVENTS_ENABLED, null));
if (enabled) {
- File errorLogFile = resolvePathRelativeToServerRoot(pluginConfig.getSimpleValue(
- PLUGIN_CONFIG_PROP_ERROR_LOG_FILE_PATH, DEFAULT_ERROR_LOG_PATH));
- ApacheErrorLogEntryProcessor processor = new ApacheErrorLogEntryProcessor(ERROR_LOG_ENTRY_EVENT_TYPE,
- errorLogFile);
- String includesPatternString = pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_INCLUDES_PATTERN,
- null);
+ File errorLogFile =
+ resolvePathRelativeToServerRoot(pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_FILE_PATH,
+ DEFAULT_ERROR_LOG_PATH));
+ ApacheErrorLogEntryProcessor processor =
+ new ApacheErrorLogEntryProcessor(ERROR_LOG_ENTRY_EVENT_TYPE, errorLogFile);
+ String includesPatternString =
+ pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_INCLUDES_PATTERN, null);
if (includesPatternString != null) {
try {
Pattern includesPattern = Pattern.compile(includesPatternString);
@@ -915,22 +920,23 @@ public class ApacheServerComponent implements AugeasRHQComponent, ResourceCompon
+ "] is not a valid regular expression.");
}
}
- String minimumSeverityString = pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_MINIMUM_SEVERITY,
- null);
+ String minimumSeverityString =
+ pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_MINIMUM_SEVERITY, null);
if (minimumSeverityString != null) {
EventSeverity minimumSeverity = EventSeverity.valueOf(minimumSeverityString.toUpperCase());
processor.setMinimumSeverity(minimumSeverity);
}
- EventPoller poller = new LogFileEventPoller(this.eventContext, ERROR_LOG_ENTRY_EVENT_TYPE, errorLogFile,
- processor);
+ EventPoller poller =
+ new LogFileEventPoller(this.eventContext, ERROR_LOG_ENTRY_EVENT_TYPE, errorLogFile, processor);
this.eventContext.registerEventPoller(poller, 60, errorLogFile.getPath());
}
}
private void stopEventPollers() {
Configuration pluginConfig = this.resourceContext.getPluginConfiguration();
- File errorLogFile = resolvePathRelativeToServerRoot(pluginConfig.getSimpleValue(
- PLUGIN_CONFIG_PROP_ERROR_LOG_FILE_PATH, DEFAULT_ERROR_LOG_PATH));
+ File errorLogFile =
+ resolvePathRelativeToServerRoot(pluginConfig.getSimpleValue(PLUGIN_CONFIG_PROP_ERROR_LOG_FILE_PATH,
+ DEFAULT_ERROR_LOG_PATH));
this.eventContext.unregisterEventPoller(ERROR_LOG_ENTRY_EVENT_TYPE, errorLogFile.getPath());
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java
index 2a913f9..0773472 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerDiscoveryComponent.java
@@ -89,7 +89,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
public DiscoveryFailureException(String message) {
super(message);
}
-
+
public DiscoveryFailureException(String message, Throwable cause) {
super(message, cause);
}
@@ -97,10 +97,10 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
public static final Map<String, String> MODULE_SOURCE_FILE_TO_MODULE_NAME_20;
public static final Map<String, String> MODULE_SOURCE_FILE_TO_MODULE_NAME_13;
-
+
static {
MODULE_SOURCE_FILE_TO_MODULE_NAME_20 = new LinkedHashMap<String, String>();
-
+
//these are extracted from http://httpd.apache.org/docs/current/mod/
//and linked pages
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("beos.c", "mpm_beos_module");
@@ -185,13 +185,13 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("mod_usertrack.c", "usertrack_module");
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("mod_version.c", "version_module");
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("mod_vhost_alias.c", "vhost_alias_module");
-
+
//some hand picked modules
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("mod_jk.c", "jk_module");
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("mod-snmpcommon.c", "snmpcommon_module");
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("mod-snmpagt.c", "snmpagt_module");
MODULE_SOURCE_FILE_TO_MODULE_NAME_20.put("covalent-snmp-v20.c", "snmp_agt_module");
-
+
//this list is for apache 1.3
MODULE_SOURCE_FILE_TO_MODULE_NAME_13 = new LinkedHashMap<String, String>();
MODULE_SOURCE_FILE_TO_MODULE_NAME_13.put("mod_access.c", "access_module");
@@ -237,9 +237,9 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
//and some hand-picks
MODULE_SOURCE_FILE_TO_MODULE_NAME_13.put("mod_jk.c", "jk_module");
- MODULE_SOURCE_FILE_TO_MODULE_NAME_13.put("covalent-snmp-v13.c", "snmp_agt_module");
+ MODULE_SOURCE_FILE_TO_MODULE_NAME_13.put("covalent-snmp-v13.c", "snmp_agt_module");
}
-
+
public Set<DiscoveredResourceDetails>
discoverResources(ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws Exception {
Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
@@ -272,28 +272,29 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
* the process info.
* @throws Exception other unhandled exception
*/
- private DiscoveredResourceDetails discoverSingleProcess(ResourceDiscoveryContext<PlatformComponent> discoveryContext,
- ProcessScanResult process) throws DiscoveryFailureException, Exception {
+ private DiscoveredResourceDetails discoverSingleProcess(
+ ResourceDiscoveryContext<PlatformComponent> discoveryContext, ProcessScanResult process)
+ throws DiscoveryFailureException, Exception {
if (isWindowsServiceRootInstance(process)) {
return null;
- }
-
+ }
+
File executablePath = getExecutableAbsolutePath(process);
log.debug("Apache executable path: " + executablePath);
-
+
ApacheBinaryInfo binaryInfo;
try {
- binaryInfo = ApacheBinaryInfo
- .getInfo(executablePath.getPath(), discoveryContext.getSystemInformation());
+ binaryInfo = ApacheBinaryInfo.getInfo(executablePath.getPath(), discoveryContext.getSystemInformation());
} catch (Exception e) {
- throw new DiscoveryFailureException("'" + executablePath + "' is not a valid Apache executable (" + e + ").");
+ throw new DiscoveryFailureException("'" + executablePath + "' is not a valid Apache executable (" + e
+ + ").");
}
if (!isSupportedVersion(binaryInfo.getVersion())) {
throw new DiscoveryFailureException("Apache " + binaryInfo.getVersion() + " is not suppported.");
}
-
+
String serverRoot = getServerRoot(binaryInfo, process.getProcessInfo());
if (serverRoot == null) {
throw new DiscoveryFailureException("Unable to determine server root.");
@@ -306,26 +307,27 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
Configuration pluginConfig = discoveryContext.getDefaultPluginConfiguration();
- PropertySimple executablePathProp = new PropertySimple(
- ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, executablePath);
+ PropertySimple executablePathProp =
+ new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH, executablePath);
pluginConfig.put(executablePathProp);
- PropertySimple serverRootProp = new PropertySimple(
- ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT, serverRoot);
+ PropertySimple serverRootProp =
+ new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT, serverRoot);
pluginConfig.put(serverRootProp);
- PropertySimple configFile = new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF,
- serverConfigFile);
+ PropertySimple configFile =
+ new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF, serverConfigFile);
pluginConfig.put(configFile);
- PropertySimple inclusionGlobs = new PropertySimple(
- PluginDescriptorBasedAugeasConfiguration.INCLUDE_GLOBS_PROP, serverConfigFile);
+ PropertySimple inclusionGlobs =
+ new PropertySimple(PluginDescriptorBasedAugeasConfiguration.INCLUDE_GLOBS_PROP, serverConfigFile);
pluginConfig.put(inclusionGlobs);
pluginConfig.put(new PropertyList(ApacheServerComponent.PLUGIN_CONFIG_CUSTOM_MODULE_NAMES));
-
- ApacheDirectiveTree serverConfig = parseRuntimeConfiguration(serverConfigFile.getAbsolutePath(), process.getProcessInfo(), binaryInfo);
-
+
+ ApacheDirectiveTree serverConfig =
+ parseRuntimeConfiguration(serverConfigFile.getAbsolutePath(), process.getProcessInfo(), binaryInfo);
+
String serverUrl = null;
String vhostsGlobInclude = null;
@@ -335,7 +337,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
serverRoot = AugeasNodeValueUtil.unescape(serverRoots.get(0).getValuesAsString());
serverRootProp.setValue(serverRoot);
}
-
+
serverUrl = getUrl(serverConfig, binaryInfo.getVersion());
vhostsGlobInclude = scanForGlobInclude(serverConfig);
@@ -358,18 +360,18 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
InetSocketAddress addr = snmpAddresses.get(0);
int port = addr.getPort();
InetAddress host = addr.getAddress() == null ? InetAddress.getLocalHost() : addr.getAddress();
-
- pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_HOST, host.getHostAddress()));
+
+ pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_HOST, host
+ .getHostAddress()));
pluginConfig.put(new PropertySimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SNMP_AGENT_PORT, port));
}
-
- return createResourceDetails(discoveryContext, pluginConfig, process.getProcessInfo(),
- binaryInfo);
+
+ return createResourceDetails(discoveryContext, pluginConfig, process.getProcessInfo(), binaryInfo);
}
public ResourceUpgradeReport upgrade(ResourceUpgradeContext<PlatformComponent> context) {
String inventoriedResourceKey = context.getResourceKey();
-
+
//check if the inventoried resource has the old format of the resource key.
//the old format was "server-root", while the new format
//is "server-root||httpd-conf". Checking for "||" in the resource key is therefore
@@ -377,7 +379,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
if (inventoriedResourceKey.contains("||")) {
return null;
}
-
+
//all the information we need for the new style resource key is
//actually present in the plugin configuration of the existing resource
//already, so let's just generate the new style resource key from it.
@@ -393,10 +395,11 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
ResourceDiscoveryContext<PlatformComponent> discoveryContext) throws InvalidPluginConfigurationException {
validateServerRootAndServerConfigFile(pluginConfig);
- String executablePath = pluginConfig.getSimpleValue(ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH,
- ApacheServerComponent.DEFAULT_EXECUTABLE_PATH);
- String absoluteExecutablePath = ApacheServerComponent.resolvePathRelativeToServerRoot(pluginConfig,
- executablePath).getPath();
+ String executablePath =
+ pluginConfig.getSimpleValue(ApacheServerComponent.PLUGIN_CONFIG_PROP_EXECUTABLE_PATH,
+ ApacheServerComponent.DEFAULT_EXECUTABLE_PATH);
+ String absoluteExecutablePath =
+ ApacheServerComponent.resolvePathRelativeToServerRoot(pluginConfig, executablePath).getPath();
ApacheBinaryInfo binaryInfo;
try {
binaryInfo = ApacheBinaryInfo.getInfo(absoluteExecutablePath, discoveryContext.getSystemInformation());
@@ -413,8 +416,8 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
ProcessInfo processInfo = null;
try {
- DiscoveredResourceDetails resourceDetails = createResourceDetails(discoveryContext, pluginConfig,
- processInfo, binaryInfo);
+ DiscoveredResourceDetails resourceDetails =
+ createResourceDetails(discoveryContext, pluginConfig, processInfo, binaryInfo);
return resourceDetails;
} catch (Exception e) {
throw new RuntimeException("Failed to create resource details during manual add.");
@@ -443,8 +446,9 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
String key = formatResourceKey(pluginConfig);
- DiscoveredResourceDetails resourceDetails = new DiscoveredResourceDetails(discoveryContext.getResourceType(),
- key, name, version, PRODUCT_DESCRIPTION, pluginConfig, processInfo);
+ DiscoveredResourceDetails resourceDetails =
+ new DiscoveredResourceDetails(discoveryContext.getResourceType(), key, name, version, PRODUCT_DESCRIPTION,
+ pluginConfig, processInfo);
log.debug("Apache Server resource details created: " + resourceDetails);
return resourceDetails;
}
@@ -576,12 +580,16 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
if (!executablePath.isAbsolute()) {
//try to figure out the full path... this might fail due to lack of privs
//if the agent is running as a different user than the httpd process
- String errorMessage = "Executable path (" + executablePath + ") is not absolute. "
- + "Please restart Apache specifying an absolute path for the executable or "
- + "make sure that the user running the RHQ agent is able to access the commandline parameters of the " + executableName + " process.";
+ String errorMessage =
+ "Executable path ("
+ + executablePath
+ + ") is not absolute. "
+ + "Please restart Apache specifying an absolute path for the executable or "
+ + "make sure that the user running the RHQ agent is able to access the commandline parameters of the "
+ + executableName + " process.";
Throwable cause = null;
boolean success = false;
-
+
//the OsProcessUtility.getProcExe does an excelent job at figuring the full path and I never saw it fail
//when the agent process has enough privs to get at the info at all. Nevertheless, let's be paranoid
//and try yet another method..
@@ -589,24 +597,24 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
String cwd = process.getProcessInfo().getCurrentWorkingDirectory();
if (cwd != null) {
executablePath = new File(cwd, executablePath.getPath());
-
+
success = executablePath.isAbsolute() && executablePath.isFile();
}
} catch (Exception e) {
- cause = e;
+ cause = e;
}
-
+
if (!success) {
throw new DiscoveryFailureException(errorMessage, cause);
}
}
-
+
return executablePath;
}
-
+
private static void validateServerRootAndServerConfigFile(Configuration pluginConfig) {
- String serverRoot = pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT)
- .getStringValue();
+ String serverRoot =
+ pluginConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT).getStringValue();
File serverRootFile;
try {
serverRootFile = new File(serverRoot).getCanonicalFile(); // this will resolve symlinks
@@ -641,26 +649,27 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
public static ApacheDirectiveTree parseRuntimeConfiguration(String path, ProcessInfo processInfo,
ApacheBinaryInfo binaryInfo) {
-
+
String httpdVersion = binaryInfo.getVersion();
Map<String, String> defaultModuleNames = getDefaultModuleNames(httpdVersion);
-
+
return parseRuntimeConfiguration(path, processInfo, binaryInfo, defaultModuleNames, true);
}
- public static ApacheDirectiveTree parseRuntimeConfiguration(String path, ProcessInfo processInfo, ApacheBinaryInfo binaryInfo, Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
+ public static ApacheDirectiveTree parseRuntimeConfiguration(String path, ProcessInfo processInfo,
+ ApacheBinaryInfo binaryInfo, Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
String defaultServerRoot = binaryInfo.getRoot();
-
+
RuntimeApacheConfiguration.NodeInspector insp =
- RuntimeApacheConfiguration.getNodeInspector(processInfo, binaryInfo,
- moduleNames, suppressUnknownModuleWarnings);
+ RuntimeApacheConfiguration.getNodeInspector(processInfo, binaryInfo, moduleNames,
+ suppressUnknownModuleWarnings);
ApacheDirectiveTree tree = new ApacheDirectiveTree();
ApacheParser parser = new ApacheParserImpl(tree, defaultServerRoot, insp);
ApacheConfigReader.buildTree(path, parser);
return tree;
}
-
+
public static String scanForGlobInclude(ApacheDirectiveTree tree) {
try {
List<ApacheDirective> includes = tree.search("/Include");
@@ -691,17 +700,19 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
}
return null;
}
-
+
public static String formatResourceKey(Configuration pluginConfiguration) {
- String serverRoot = pluginConfiguration.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT).getStringValue();
- String httpdConf = pluginConfiguration.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF).getStringValue();
-
+ String serverRoot =
+ pluginConfiguration.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT).getStringValue();
+ String httpdConf =
+ pluginConfiguration.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_HTTPD_CONF).getStringValue();
+
return formatResourceKey(serverRoot, httpdConf);
}
-
+
public static String formatResourceKey(String serverRoot, String httpdConf) {
serverRoot = FileUtils.getCanonicalPath(serverRoot);
-
+
//we could have inherited the configuration from
//RHQ 1.x times, when the httpdConf was relative.
File httpdConfF = new File(httpdConf);
@@ -710,10 +721,10 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
httpdConf = httpdConfF.getAbsolutePath();
}
httpdConf = FileUtils.getCanonicalPath(httpdConf);
-
+
return serverRoot + "||" + httpdConf;
}
-
+
private static List<InetSocketAddress> findSNMPAddresses(ApacheDirectiveTree tree, File serverRoot) {
List<InetSocketAddress> ret = new ArrayList<InetSocketAddress>();
@@ -723,14 +734,13 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
log.info("SNMPConf directive not found. Skipping SNMP configuration.");
return ret;
}
-
+
String confDirName = confs.get(0).getValuesAsString();
if (confDirName == null || confDirName.isEmpty()) {
log.warn("The SNMPConf directive seems to not have a value. Skipping SNMP configuration.");
return ret;
}
-
-
+
File confDir = new File(confDirName);
if (!confDir.isAbsolute()) {
@@ -744,7 +754,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
+ "'. Skipping SNMP configuration.");
return ret;
}
-
+
try {
String agentAddressLine = findSNMPAgentAddressConfigLine(snmpdConf);
@@ -752,7 +762,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
log.warn("Could not find the 'agentaddress' property in the snmpd.conf. Skipping SNMP configuration.");
return ret;
}
-
+
int specStartIdx = agentAddressLine.indexOf("agentaddress") + "agentaddress".length() + 1;
while (Character.isWhitespace(agentAddressLine.charAt(specStartIdx)))
@@ -787,16 +797,15 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
ret.add(address);
}
} catch (Exception e) {
- log.warn("Failed to parse the SNMP 'agentaddress' configuration property: "
- + agentAddressLine, e);
+ log.warn("Failed to parse the SNMP 'agentaddress' configuration property: " + agentAddressLine, e);
}
} catch (IOException e) {
log.warn("Failed to read in the configured snmpd.conf file: " + snmpdConf.getAbsolutePath(), e);
}
-
+
return ret;
}
-
+
private static String findSNMPAgentAddressConfigLine(File snmpdConf) throws IOException {
BufferedReader rdr = new BufferedReader(new FileReader(snmpdConf));
@@ -809,7 +818,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
return line;
}
}
-
+
return null;
} finally {
rdr.close();
@@ -818,14 +827,15 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
public static Map<String, String> getDefaultModuleNames(String version) {
switch (HttpdAddressUtility.get(version)) {
- case APACHE_1_3 :
+ case APACHE_1_3:
return MODULE_SOURCE_FILE_TO_MODULE_NAME_13;
case APACHE_2_x:
return MODULE_SOURCE_FILE_TO_MODULE_NAME_20;
- default: throw new IllegalStateException("Unknown HttpdAddressUtility instance.");
- }
+ default:
+ throw new IllegalStateException("Unknown HttpdAddressUtility instance.");
+ }
}
-
+
/**
* We need this because of PIQL limitations.
*
@@ -843,7 +853,7 @@ public class ApacheServerDiscoveryComponent implements ResourceDiscoveryComponen
*/
private static boolean isWindowsServiceRootInstance(ProcessScanResult process) {
String kArg = getCommandLineOption(process.getProcessInfo().getCommandLine(), "-k");
-
+
return kArg != null && kArg.equalsIgnoreCase("runservice");
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerOperationsDelegate.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerOperationsDelegate.java
index 3c0c23f..281bcf3 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerOperationsDelegate.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheServerOperationsDelegate.java
@@ -145,9 +145,10 @@ public class ApacheServerOperationsDelegate implements OperationFacet {
// in the GUI -- see RHQ-627
// We might want to investigate this again later.
if (processExecutionResults.getError() != null || (exitCode != null && exitCode != 0)) {
- String msg = "Operation " + operation + " failed. Exit code: [" + exitCode + "]\n, Output : ["
- + processExecutionResults.getCapturedOutput() + "]\n" + "Error: [" + processExecutionResults.getError()
- + "]";
+ String msg =
+ "Operation " + operation + " failed. Exit code: [" + exitCode + "]\n, Output : ["
+ + processExecutionResults.getCapturedOutput() + "]\n" + "Error: ["
+ + processExecutionResults.getError() + "]";
throw new Exception(msg);
}
@@ -216,6 +217,11 @@ public class ApacheServerOperationsDelegate implements OperationFacet {
* Enumeration of supported operations for an Apache server.
*/
private enum Operation {
- START, STOP, RESTART, START_SSL, GRACEFUL_RESTART, CONFIG_TEST
+ START,
+ STOP,
+ RESTART,
+ START_SSL,
+ GRACEFUL_RESTART,
+ CONFIG_TEST
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceComponent.java
index 5dd9192..c070807 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceComponent.java
@@ -75,13 +75,16 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
public static final String URL_CONFIG_PROP = "url";
public static final String MAIN_SERVER_RESOURCE_KEY = "MainServer";
-
- public static final String RESPONSE_TIME_LOG_FILE_CONFIG_PROP = ResponseTimeConfiguration.RESPONSE_TIME_LOG_FILE_CONFIG_PROP;
- public static final String RESPONSE_TIME_URL_EXCLUDES_CONFIG_PROP = ResponseTimeConfiguration.RESPONSE_TIME_URL_EXCLUDES_CONFIG_PROP;
- public static final String RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP = ResponseTimeConfiguration.RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP;
+
+ public static final String RESPONSE_TIME_LOG_FILE_CONFIG_PROP =
+ ResponseTimeConfiguration.RESPONSE_TIME_LOG_FILE_CONFIG_PROP;
+ public static final String RESPONSE_TIME_URL_EXCLUDES_CONFIG_PROP =
+ ResponseTimeConfiguration.RESPONSE_TIME_URL_EXCLUDES_CONFIG_PROP;
+ public static final String RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP =
+ ResponseTimeConfiguration.RESPONSE_TIME_URL_TRANSFORMS_CONFIG_PROP;
public static final String SERVER_NAME_CONFIG_PROP = "ServerName";
-
+
private static final String RESPONSE_TIME_METRIC = "ResponseTime";
/** Multiply by 1/1000 to convert logged response times, which are in microseconds, to milliseconds. */
private static final double RESPONSE_TIME_LOG_TIME_MULTIPLIER = 0.001;
@@ -140,14 +143,15 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
if (getWwwServiceIndex() < 1) {
return AvailabilityType.DOWN;
}
-
+
//ok, so the vhost is present. Now let's just ping the SNMP module to see
//if it is reachable and base our availability on that...
SNMPSession snmpSession = resourceContext.getParentResourceComponent().getSNMPSession();
-
+
return snmpSession.ping() ? AvailabilityType.UP : AvailabilityType.DOWN;
} catch (Exception e) {
- log.debug("Determining the availability of the vhost [" + resourceContext.getResourceKey() + "] using SNMP failed.", e);
+ log.debug("Determining the availability of the vhost [" + resourceContext.getResourceKey()
+ + "] using SNMP failed.", e);
return AvailabilityType.DOWN;
}
}
@@ -157,14 +161,14 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
if (!isAugeasEnabled()) {
throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
ApacheServerComponent parent = resourceContext.getParentResourceComponent();
AugeasComponent comp = getAugeas();
try {
AugeasTree tree = comp.getAugeasTree(ApacheServerComponent.AUGEAS_HTTP_MODULE_NAME);
- ConfigurationDefinition resourceConfigDef = resourceContext.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition resourceConfigDef =
+ resourceContext.getResourceType().getResourceConfigurationDefinition();
ApacheAugeasMapping mapping = new ApacheAugeasMapping(tree);
return mapping.updateConfiguration(getNode(tree), resourceConfigDef);
@@ -179,13 +183,13 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
report.setErrorMessage(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
return;
}
-
+
AugeasComponent comp = getAugeas();
AugeasTree tree = null;
try {
tree = comp.getAugeasTree(ApacheServerComponent.AUGEAS_HTTP_MODULE_NAME);
- ConfigurationDefinition resourceConfigDef = resourceContext.getResourceType()
- .getResourceConfigurationDefinition();
+ ConfigurationDefinition resourceConfigDef =
+ resourceContext.getResourceType().getResourceConfigurationDefinition();
ApacheAugeasMapping mapping = new ApacheAugeasMapping(tree);
AugeasNode virtHostNode = getNode(tree);
mapping.updateAugeas(virtHostNode, report.getConfiguration(), resourceConfigDef);
@@ -214,7 +218,7 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
if (!isAugeasEnabled()) {
throw new IllegalStateException(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
}
-
+
ApacheServerComponent parent = resourceContext.getParentResourceComponent();
if (MAIN_SERVER_RESOURCE_KEY.equals(resourceContext.getResourceKey())) {
@@ -293,7 +297,7 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
report.setErrorMessage(ApacheServerComponent.CONFIGURATION_NOT_SUPPORTED_ERROR_MESSAGE);
return report;
}
-
+
ResourceType resourceType = report.getResourceType();
AugeasComponent comp = null;
try {
@@ -406,8 +410,8 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
ApacheServerComponent server = resourceContext.getParentResourceComponent();
if (snmpIdx < 1) {
- throw new IllegalStateException(
- "Could not determine the index of the virtual host [" + resourceKey + "] in the runtime configuration. This is very strange.");
+ throw new IllegalStateException("Could not determine the index of the virtual host [" + resourceKey
+ + "] in the runtime configuration. This is very strange.");
}
if (snmpIdx == 1) {
@@ -525,7 +529,7 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
return oid;
}
- public static int getWwwServiceIndex(ApacheServerComponent parent, String resourceKey) {
+ public static int getWwwServiceIndex(ApacheServerComponent parent, String resourceKey) {
//figure out the servername and addresses of this virtual host
//from the resource key.
String vhostServerName = null;
@@ -536,53 +540,55 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
if (vhostServerName.isEmpty()) {
vhostServerName = null;
}
- }
+ }
vhostAddressStrings = resourceKey.substring(pipeIdx + 1).split(" ");
int foundIdx = 0;
-
+
//only look for the vhost entry if the vhost we're looking for isn't the main server
if (!MAIN_SERVER_RESOURCE_KEY.equals(vhostAddressStrings[0])) {
- ApacheDirectiveTree tree = parent.parseRuntimeConfiguration(false);
-
+ ApacheDirectiveTree tree = parent.parseRuntimeConfiguration(false);
+
//find the vhost entry the resource key represents
List<ApacheDirective> vhosts = tree.search("/<VirtualHost");
- for(ApacheDirective vhost : vhosts) {
+ for (ApacheDirective vhost : vhosts) {
List<ApacheDirective> serverNames = vhost.getChildByName("ServerName");
- String serverName = serverNames.size() > 0 ? serverNames.get(0).getValuesAsString() : null;
-
+ String serverName = serverNames.size() > 0 ? serverNames.get(0).getValuesAsString() : null;
+
List<String> addrs = vhost.getValues();
-
- boolean serverNamesMatch = (serverName == null && vhostServerName == null) ||
- (serverName != null && serverName.equals(vhostServerName));
+
+ boolean serverNamesMatch =
+ (serverName == null && vhostServerName == null)
+ || (serverName != null && serverName.equals(vhostServerName));
boolean addrsMatch = true;
-
+
if (addrs.size() != vhostAddressStrings.length) {
addrsMatch = false;
} else {
- for(int i = 0; i < vhostAddressStrings.length; ++i) {
+ for (int i = 0; i < vhostAddressStrings.length; ++i) {
if (!addrs.contains(vhostAddressStrings[i])) {
addrsMatch = false;
break;
}
}
}
-
+
if (serverNamesMatch && addrsMatch) {
break;
}
-
+
++foundIdx;
}
-
+
if (foundIdx == vhosts.size()) {
- log.debug("The virtual host with resource key [" + resourceKey + "] doesn't seem to be present in the apache configuration anymore.");
+ log.debug("The virtual host with resource key [" + resourceKey
+ + "] doesn't seem to be present in the apache configuration anymore.");
return -1;
} else {
//httpd vhosts are internally (in httpd internal data structures) ordered like this:
//1) the main server entry is always first
//2) all the vhosts are ordered from the last to appear in the joined config files to the first one
-
+
//we now have an index to the list of the vhosts in the order they are defined.
//so let's swap it over.
//just subtracting from the size will give us the "room" for the first index
@@ -591,24 +597,26 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
foundIdx = vhosts.size() - foundIdx;
}
}
-
+
//the snmp indices are 1-based
return foundIdx + 1;
}
-
+
/**
* @return the index of the virtual host that identifies it in SNMP
* @throws Exception on SNMP error
*/
private int getWwwServiceIndex() {
- ConfigurationTimestamp currentTimestamp = resourceContext.getParentResourceComponent().getConfigurationTimestamp();
+ ConfigurationTimestamp currentTimestamp =
+ resourceContext.getParentResourceComponent().getConfigurationTimestamp();
if (!lastConfigurationTimeStamp.equals(currentTimestamp)) {
snmpWwwServiceIndex = -1;
//don't go through this configuration again even if we fail further below.. we'd fail again.
lastConfigurationTimeStamp = currentTimestamp;
-
+
//configuration has changed. re-read the service index of this virtual host
- snmpWwwServiceIndex = getWwwServiceIndex(resourceContext.getParentResourceComponent(), resourceContext.getResourceKey());
+ snmpWwwServiceIndex =
+ getWwwServiceIndex(resourceContext.getParentResourceComponent(), resourceContext.getResourceKey());
}
return snmpWwwServiceIndex;
}
@@ -621,4 +629,4 @@ public class ApacheVirtualHostServiceComponent implements ResourceComponent<Apac
ApacheServerComponent parent = resourceContext.getParentResourceComponent();
return parent.isAugeasEnabled();
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceDiscoveryComponent.java
index daf27fd..2d41fcf 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceDiscoveryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ApacheVirtualHostServiceDiscoveryComponent.java
@@ -63,18 +63,20 @@ import org.rhq.plugins.www.snmp.SNMPValue;
* @author Ian Springer
* @author Lukas Krejci
*/
-public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDiscoveryComponent<ApacheServerComponent>, ResourceUpgradeFacet<ApacheServerComponent> {
+public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDiscoveryComponent<ApacheServerComponent>,
+ ResourceUpgradeFacet<ApacheServerComponent> {
- private static final String COULD_NOT_DETERMINE_THE_VIRTUAL_HOST_ADDRESS = "*** Could not determine the virtual host address ***";
+ private static final String COULD_NOT_DETERMINE_THE_VIRTUAL_HOST_ADDRESS =
+ "*** Could not determine the virtual host address ***";
public static final String LOGS_DIRECTORY_NAME = "logs";
private static final String RT_LOG_FILE_NAME_SUFFIX = "_rt.log";
private static final String LEGACY_SNMP_SERVICE_INDEX_CONFIG_PROP = "snmpWwwServiceIndex";
-
+
private static final Log log = LogFactory.getLog(ApacheVirtualHostServiceDiscoveryComponent.class);
-
+
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ApacheServerComponent> context)
throws InvalidPluginConfigurationException, Exception {
@@ -82,7 +84,7 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
ApacheServerComponent serverComponent = context.getParentResourceComponent();
ApacheDirectiveTree tree = serverComponent.parseRuntimeConfiguration(false);
-
+
//first define the root server as one virtual host
discoverMainServer(context, tree, discoveredResources);
@@ -91,8 +93,8 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
File configPath = serverComponent.getServerRoot();
File logsDir = new File(configPath, LOGS_DIRECTORY_NAME);
- for(VHostSpec vhost : VHostSpec.detect(tree)) {
-
+ for (VHostSpec vhost : VHostSpec.detect(tree)) {
+
String firstAddress = vhost.hosts.get(0);
String resourceKey = createResourceKey(vhost.serverName, vhost.hosts);
@@ -100,13 +102,16 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
Configuration pluginConfiguration = context.getDefaultPluginConfiguration();
- Address address = serverComponent.getAddressUtility().getVirtualHostSampleAddress(tree, firstAddress, vhost.serverName, false);
+ Address address =
+ serverComponent.getAddressUtility().getVirtualHostSampleAddress(tree, firstAddress, vhost.serverName,
+ false);
if (address != null) {
String scheme = address.scheme;
String hostToPing = address.host;
int portToPing = address.port;
if (address.isPortWildcard() || !address.isPortDefined()) {
- Address serverAddress = serverComponent.getAddressUtility().getMainServerSampleAddress(tree, hostToPing, 0);
+ Address serverAddress =
+ serverComponent.getAddressUtility().getMainServerSampleAddress(tree, hostToPing, 0);
if (serverAddress != null) {
portToPing = serverAddress.port;
} else {
@@ -114,17 +119,19 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
}
}
if (address.isHostDefault() || address.isHostWildcard()) {
- Address serverAddress = serverComponent.getAddressUtility().getMainServerSampleAddress(tree, null, portToPing);
-
+ Address serverAddress =
+ serverComponent.getAddressUtility().getMainServerSampleAddress(tree, null, portToPing);
+
if (serverAddress != null) {
hostToPing = serverAddress.host;
} else {
hostToPing = null;
}
}
-
+
String url;
- if (hostToPing != null && portToPing != Address.PORT_WILDCARD_VALUE && portToPing != Address.NO_PORT_SPECIFIED_VALUE) {
+ if (hostToPing != null && portToPing != Address.PORT_WILDCARD_VALUE
+ && portToPing != Address.NO_PORT_SPECIFIED_VALUE) {
url = scheme + "://" + hostToPing + ":" + portToPing + "/";
} else {
url = COULD_NOT_DETERMINE_THE_VIRTUAL_HOST_ADDRESS;
@@ -132,17 +139,18 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
PropertySimple urlProp = new PropertySimple(ApacheVirtualHostServiceComponent.URL_CONFIG_PROP, url);
pluginConfiguration.put(urlProp);
-
+
File rtLogFile = new File(logsDir, address.host + address.port + RT_LOG_FILE_NAME_SUFFIX);
-
- PropertySimple rtLogProp = new PropertySimple(
- ApacheVirtualHostServiceComponent.RESPONSE_TIME_LOG_FILE_CONFIG_PROP, rtLogFile.toString());
+
+ PropertySimple rtLogProp =
+ new PropertySimple(ApacheVirtualHostServiceComponent.RESPONSE_TIME_LOG_FILE_CONFIG_PROP,
+ rtLogFile.toString());
pluginConfiguration.put(rtLogProp);
//redefine the resourcename using the virtual host sample address
resourceName = address.toString(false, true);
}
-
+
discoveredResources.add(new DiscoveredResourceDetails(resourceType, resourceKey, resourceName, null, null,
pluginConfiguration, null));
}
@@ -165,13 +173,13 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
ApacheDirectiveTree tree = serverComponent.parseRuntimeConfiguration(false);
List<VHostSpec> vhosts = VHostSpec.detect(tree);
- VirtualHostLegacyResourceKeyUtil legacyResourceKeyUtil = new VirtualHostLegacyResourceKeyUtil(serverComponent, tree);
-
+ VirtualHostLegacyResourceKeyUtil legacyResourceKeyUtil =
+ new VirtualHostLegacyResourceKeyUtil(serverComponent, tree);
//first, let's see if the inventoried resource has the snmpWwwServiceIndex property set
//if it does, use that to determine what vhost this corresponds to.
- String snmpServiceIndexString = inventoriedResource.getPluginConfiguration().getSimpleValue(
- LEGACY_SNMP_SERVICE_INDEX_CONFIG_PROP, null);
+ String snmpServiceIndexString =
+ inventoriedResource.getPluginConfiguration().getSimpleValue(LEGACY_SNMP_SERVICE_INDEX_CONFIG_PROP, null);
if (snmpServiceIndexString != null) {
Integer snmpServiceIndex = null;
try {
@@ -207,10 +215,11 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
//the SNMP indices are in the reverse order of the definitions in the config files
//+1, where the main server is always on index 1.
VHostSpec vhost = vhosts.get(vhosts.size() - snmpServiceIndex + 1);
-
+
//right, let's do a cross-check before we actually create the resource key so
//that we catch user-generated errors.
- Set<String> legacyResourceKeys = legacyResourceKeyUtil.getLegacyVirtualHostResourceKeys(vhost);
+ Set<String> legacyResourceKeys =
+ legacyResourceKeyUtil.getLegacyVirtualHostResourceKeys(vhost);
if (legacyResourceKeys.contains(resourceKey)) {
newResourceKey = createResourceKey(vhost.serverName, vhost.hosts);
} else {
@@ -233,31 +242,35 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
return report;
}
-
+
Map<String, Set<VHostSpec>> possibleMatchesPerRK = new HashMap<String, Set<VHostSpec>>();
- for (VHostSpec vhost : vhosts) {
+ for (VHostSpec vhost : vhosts) {
Set<String> legacyResourceKeys = legacyResourceKeyUtil.getLegacyVirtualHostResourceKeys(vhost);
- for(String legacyRK : legacyResourceKeys) {
+ for (String legacyRK : legacyResourceKeys) {
addPossibleRKMatch(legacyRK, vhost, possibleMatchesPerRK);
}
}
- for(String legacyRK : legacyResourceKeyUtil.getLegacyMainServerResourceKeys()) {
+ for (String legacyRK : legacyResourceKeyUtil.getLegacyMainServerResourceKeys()) {
addPossibleRKMatch(legacyRK, null, possibleMatchesPerRK);
}
Set<VHostSpec> matchingVhosts = possibleMatchesPerRK.get(resourceKey);
if (matchingVhosts == null || matchingVhosts.isEmpty()) {
- throw new IllegalArgumentException("Failed to identify the vhost resource with the old-style resource key '" + resourceKey +
- "' with any of the vhosts in the apache configuration files. This means that the vhost resource is stale and you can safely uninventory it.");
+ throw new IllegalArgumentException(
+ "Failed to identify the vhost resource with the old-style resource key '"
+ + resourceKey
+ + "' with any of the vhosts in the apache configuration files. This means that the vhost resource is stale and you can safely uninventory it.");
} else if (matchingVhosts.size() > 1) {
- String message = "Failed to uniquely identify the vhost from the old-style resource key. The old resource key is '"
- + resourceKey
- + "' which could be matched with any of the following possible new-style resource keys: "
- + matchingVhosts + ". The plugin does not have enough information to successfully upgrade this resource."
- + " Please take note of any alert definitions or operation schedules that you have defined for this resource and manually uninventory it.";
-
+ String message =
+ "Failed to uniquely identify the vhost from the old-style resource key. The old resource key is '"
+ + resourceKey
+ + "' which could be matched with any of the following possible new-style resource keys: "
+ + matchingVhosts
+ + ". The plugin does not have enough information to successfully upgrade this resource."
+ + " Please take note of any alert definitions or operation schedules that you have defined for this resource and manually uninventory it.";
+
throw new IllegalArgumentException(message);
} else {
VHostSpec vhost = matchingVhosts.iterator().next();
@@ -273,7 +286,7 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
return report;
}
-
+
private void discoverMainServer(ResourceDiscoveryContext<ApacheServerComponent> context,
ApacheDirectiveTree runtimeConfig, Set<DiscoveredResourceDetails> discoveredResources) throws Exception {
@@ -283,16 +296,19 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
File configPath = context.getParentResourceComponent().getServerRoot();
File logsDir = new File(configPath, LOGS_DIRECTORY_NAME);
- String mainServerUrl = context.getParentResourceContext().getPluginConfiguration().getSimple(
- ApacheServerComponent.PLUGIN_CONFIG_PROP_URL).getStringValue();
-
+ String mainServerUrl =
+ context.getParentResourceContext().getPluginConfiguration()
+ .getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_URL).getStringValue();
+
if (mainServerUrl == null || mainServerUrl.trim().isEmpty()) {
- HttpdAddressUtility.Address addr = context.getParentResourceComponent().getAddressUtility().getMainServerSampleAddress(runtimeConfig, null, 0);
+ HttpdAddressUtility.Address addr =
+ context.getParentResourceComponent().getAddressUtility()
+ .getMainServerSampleAddress(runtimeConfig, null, 0);
mainServerUrl = addr.toString();
}
-
- PropertySimple mainServerUrlProp = new PropertySimple(ApacheVirtualHostServiceComponent.URL_CONFIG_PROP,
- mainServerUrl);
+
+ PropertySimple mainServerUrlProp =
+ new PropertySimple(ApacheVirtualHostServiceComponent.URL_CONFIG_PROP, mainServerUrl);
mainServerPluginConfig.put(mainServerUrlProp);
@@ -305,18 +321,18 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
File rtLogFile = new File(logsDir, host + port + RT_LOG_FILE_NAME_SUFFIX);
- PropertySimple rtLogProp = new PropertySimple(
- ApacheVirtualHostServiceComponent.RESPONSE_TIME_LOG_FILE_CONFIG_PROP, rtLogFile.toString());
+ PropertySimple rtLogProp =
+ new PropertySimple(ApacheVirtualHostServiceComponent.RESPONSE_TIME_LOG_FILE_CONFIG_PROP,
+ rtLogFile.toString());
mainServerPluginConfig.put(rtLogProp);
String key = ApacheVirtualHostServiceComponent.MAIN_SERVER_RESOURCE_KEY;
-
- DiscoveredResourceDetails mainServer = new DiscoveredResourceDetails(resourceType,
- key, "Main", null, null,
- mainServerPluginConfig, null);
+
+ DiscoveredResourceDetails mainServer =
+ new DiscoveredResourceDetails(resourceType, key, "Main", null, null, mainServerPluginConfig, null);
discoveredResources.add(mainServer);
}
-
+
public static String createResourceKey(String serverName, List<String> hosts) {
StringBuilder keyBuilder = new StringBuilder();
if (serverName != null) {
@@ -324,21 +340,22 @@ public class ApacheVirtualHostServiceDiscoveryComponent implements ResourceDisco
}
keyBuilder.append("|"); //always do this so that we have a clear distinction between old and new style resource keys
keyBuilder.append(hosts.get(0));
-
- for (int i = 1; i < hosts.size(); ++i){
+
+ for (int i = 1; i < hosts.size(); ++i) {
keyBuilder.append(" ").append(hosts.get(i));
}
-
+
return keyBuilder.toString();
}
-
- private static void addPossibleRKMatch(String resourceKey, VHostSpec vhost, Map<String, Set<VHostSpec>> possibleMatches) {
+
+ private static void addPossibleRKMatch(String resourceKey, VHostSpec vhost,
+ Map<String, Set<VHostSpec>> possibleMatches) {
Set<VHostSpec> matches = possibleMatches.get(resourceKey);
if (matches == null) {
matches = new HashSet<VHostSpec>();
possibleMatches.put(resourceKey, matches);
}
-
+
matches.add(vhost);
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKDiscoveryComponent.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKDiscoveryComponent.java
index 64b7810..64314c1 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKDiscoveryComponent.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/ModJKDiscoveryComponent.java
@@ -51,8 +51,8 @@ public class ModJKDiscoveryComponent implements ResourceDiscoveryComponent<Apach
* @throws InvalidPluginConfigurationException
* @throws Exception
*/
- public Set<DiscoveredResourceDetails> discoverResources(
- ResourceDiscoveryContext<ApacheServerComponent> context) throws InvalidPluginConfigurationException, Exception {
+ public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ApacheServerComponent> context)
+ throws InvalidPluginConfigurationException, Exception {
Set<DiscoveredResourceDetails> details = new HashSet<DiscoveredResourceDetails>(1);
@@ -61,22 +61,21 @@ public class ModJKDiscoveryComponent implements ResourceDiscoveryComponent<Apach
// Try to determine the presence of mod_jk and its version via a http request
PropertySimple urlString = parentConfig.getSimple(ApacheServerComponent.PLUGIN_CONFIG_PROP_URL);
String modJkVersion = null;
- if (urlString!=null) {
+ if (urlString != null) {
try {
URL url = new URL(urlString.getStringValue());
String header = WWWUtils.getServerHeader(url);
- if (header!=null) {
+ if (header != null) {
if (header.contains("mod_jk")) {
- header = header.substring(header.indexOf("mod_jk")+7);
+ header = header.substring(header.indexOf("mod_jk") + 7);
int blankPos = header.indexOf(" ");
- if (blankPos>0)
- modJkVersion = header.substring(0,header.indexOf(" "));
+ if (blankPos > 0)
+ modJkVersion = header.substring(0, header.indexOf(" "));
else
modJkVersion = header;
}
}
- }
- catch (MalformedURLException e) {
+ } catch (MalformedURLException e) {
// nothing to do
}
}
@@ -98,18 +97,18 @@ public class ModJKDiscoveryComponent implements ResourceDiscoveryComponent<Apach
if (parser.parse(confPath) && parser.isModJkInstalled()) {
Configuration config = context.getDefaultPluginConfiguration();
- if (parser.getWorkerPropertiesFile()!=null) {
+ if (parser.getWorkerPropertiesFile() != null) {
PropertySimple workers = new PropertySimple("workerFile", parser.getWorkerPropertiesFile());
config.put(workers);
}
- if (parser.getUriWorkerLocation()!=null) {
+ if (parser.getUriWorkerLocation() != null) {
PropertySimple workers = new PropertySimple("uriWorkerFile", parser.getUriWorkerLocation());
config.put(workers);
}
-
- DiscoveredResourceDetails detail = new DiscoveredResourceDetails(context.getResourceType(),
- confPath,"mod_jk",modJkVersion,"Mod_JK", config, null);
+ DiscoveredResourceDetails detail =
+ new DiscoveredResourceDetails(context.getResourceType(), confPath, "mod_jk", modJkVersion, "Mod_JK",
+ config, null);
details.add(detail);
return details;
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/SNMPConstants.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/SNMPConstants.java
index f7c9ef6..c964d98 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/SNMPConstants.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/SNMPConstants.java
@@ -25,4 +25,4 @@ public abstract class SNMPConstants {
public static final String COLUMN_VHOST_ADM = "wwwServiceContact";
public static final String TCP_PROTO_ID = "1.3.6.1.2.1.6";
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasNode.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasNode.java
index 99cc8cb..4699cba 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasNode.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasNode.java
@@ -76,18 +76,18 @@ public class ApacheAugeasNode extends AugeasNodeLazy implements AugeasNode {
public List<AugeasNode> getChildNodes() {
List<AugeasNode> nodes = null;
nodes = ag.match(getFullPath() + File.separatorChar + "*");
-
+
if (includedNodes != null) {
//to avoid having to recompute indexes to insert the included nodes into the
//list of nodes as seen by augeas, let's include them from the biggest index
//to the lowest.
List<Integer> includeNodeIndexes = new ArrayList<Integer>(includedNodes.keySet());
Collections.sort(includeNodeIndexes, Collections.reverseOrder());
-
- for(Integer idx : includeNodeIndexes) {
+
+ for (Integer idx : includeNodeIndexes) {
//remove the include node itself
nodes.remove(idx);
-
+
//add the included nodes instead of it
nodes.addAll(idx, includedNodes.get(idx));
}
@@ -111,16 +111,16 @@ public class ApacheAugeasNode extends AugeasNodeLazy implements AugeasNode {
List<AugeasNode> childNodes = super.getChildNodes();
int idx = 0;
boolean found = false;
-
- for(AugeasNode child : childNodes) {
+
+ for (AugeasNode child : childNodes) {
if (child.getLabel().equals(includeNode.getLabel()) && child.getSeq() == includeNode.getSeq()) {
found = true;
break;
}
-
+
++idx;
}
-
+
if (found) {
List<AugeasNode> alreadyIncluded = includedNodes.get(idx);
if (alreadyIncluded == null) {
@@ -160,8 +160,8 @@ public class ApacheAugeasNode extends AugeasNodeLazy implements AugeasNode {
//else if this node is included from another file
//and we would destroy that association here.
}
-
- public void setParentNode(AugeasNode node){
- this.parentNode = node;
- }
+
+ public void setParentNode(AugeasNode node) {
+ this.parentNode = node;
+ }
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasTree.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasTree.java
index 3d10d59..b4188b7 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasTree.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/ApacheAugeasTree.java
@@ -49,7 +49,7 @@ public class ApacheAugeasTree extends AugeasTreeLazy {
private Map<AugeasNode, List<String>> includes;
private List<String> includeGlobs;
-
+
public ApacheAugeasTree(String serverRootPath, Augeas ag, AugeasModuleConfig moduleConfig) {
super(ag, moduleConfig);
this.includeGlobs = initIncludeGlobs(serverRootPath);
@@ -58,7 +58,7 @@ public class ApacheAugeasTree extends AugeasTreeLazy {
protected AugeasNode instantiateNode(String fullPath) {
return new ApacheAugeasNode(fullPath, this);
}
-
+
public Map<AugeasNode, List<String>> getIncludes() {
return includes;
}
@@ -110,7 +110,7 @@ public class ApacheAugeasTree extends AugeasTreeLazy {
private int subExpressionIndex(String expr) {
//we have to parse the expression carefully because of the
//potential xpath qualifier that can contain path separators.
-
+
//0 = normal
//1 = in xpath qualifier
//2 = in double-quoted string (inside the qualifier)
@@ -167,10 +167,10 @@ public class ApacheAugeasTree extends AugeasTreeLazy {
}
idx++;
}
-
+
return idx == expr.length() ? -1 : idx;
}
-
+
private List<AugeasNode> parseExpr(AugeasNode nd, String expr) throws Exception {
int index = subExpressionIndex(expr);
@@ -199,7 +199,7 @@ public class ApacheAugeasTree extends AugeasTreeLazy {
if (includes.containsKey(nd)) {
List<String> files = includes.get(nd);
for (String fileName : files) {
- List<AugeasNode> nds = this.matchInternal(fileName + PATH_SEPARATOR+ expr);
+ List<AugeasNode> nds = this.matchInternal(fileName + PATH_SEPARATOR + expr);
for (AugeasNode node : nds) {
if (!nodes.contains(node))
nodes.add(node);
@@ -230,8 +230,8 @@ public class ApacheAugeasTree extends AugeasTreeLazy {
*/
private List<String> initIncludeGlobs(String serverRootPath) {
ArrayList<String> ret = new ArrayList<String>();
-
- for(String glob : getModuleConfig().getIncludedGlobs()) {
+
+ for (String glob : getModuleConfig().getIncludedGlobs()) {
File f = new File(glob);
if (f.isAbsolute()) {
ret.add(glob);
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
index ba52e77..59be7c1 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasConfigurationApache.java
@@ -61,7 +61,7 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
private final Pattern serverRootPattern = Pattern.compile(SERVER_ROOT_PATTERN);
private static final Log LOG = LogFactory.getLog(AugeasConfigurationApache.class);
-
+
private String serverRootPath;
private AugeasModuleConfig module;
private List<File> allConfigFiles;
@@ -70,8 +70,8 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
return serverRootPath;
}
- public AugeasConfigurationApache(String path,Configuration configuration) throws AugeasRhqException {
- super(path,configuration);
+ public AugeasConfigurationApache(String path, Configuration configuration) throws AugeasRhqException {
+ super(path, configuration);
serverRootPath = configuration.getSimpleValue(ApacheServerComponent.PLUGIN_CONFIG_PROP_SERVER_ROOT, null);
@@ -103,42 +103,42 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
return allConfigFiles;
}
- private void loadIncludes(String expression, List<String> foundIncludes) {
- try {
+ private void loadIncludes(String expression, List<String> foundIncludes) {
+ try {
List<File> files = new ArrayList<File>();
- File check = new File(expression);
- File root = new File(check.isAbsolute() ? Glob.rootPortion(expression) : serverRootPath);
+ File check = new File(expression);
+ File root = new File(check.isAbsolute() ? Glob.rootPortion(expression) : serverRootPath);
files.addAll(Glob.match(root, expression, Glob.ALPHABETICAL_COMPARATOR));
-
- for (File fl : files){
- if (fl.exists() && fl.isFile()) {
- foundIncludes.add(fl.getAbsolutePath());
-
- BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(new FileInputStream(fl)));
- String strLine;
- while ((strLine = br.readLine()) != null) {
- Matcher m = includePattern.matcher(strLine);
- if (m.matches()) {
- String glob = m.group(1);
-
- module.addIncludedGlob(glob);
- loadIncludes(glob, foundIncludes);
+
+ for (File fl : files) {
+ if (fl.exists() && fl.isFile()) {
+ foundIncludes.add(fl.getAbsolutePath());
+
+ BufferedReader br = null;
+ try {
+ br = new BufferedReader(new InputStreamReader(new FileInputStream(fl)));
+ String strLine;
+ while ((strLine = br.readLine()) != null) {
+ Matcher m = includePattern.matcher(strLine);
+ if (m.matches()) {
+ String glob = m.group(1);
+
+ module.addIncludedGlob(glob);
+ loadIncludes(glob, foundIncludes);
+ }
+ Matcher serverRootMatcher = serverRootPattern.matcher(strLine);
+ if (serverRootMatcher.matches()) {
+ serverRootPath = serverRootMatcher.group(1);
+ }
}
- Matcher serverRootMatcher = serverRootPattern.matcher(strLine);
- if (serverRootMatcher.matches()) {
- serverRootPath = serverRootMatcher.group(1);
+ } finally {
+ if (br != null) {
+ br.close();
}
}
- } finally {
- if (br != null) {
- br.close();
- }
}
}
- }
} catch (Exception e) {
throw new IllegalStateException(e);
@@ -146,7 +146,7 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
}
public void loadFiles() {
-
+
for (AugeasModuleConfig module : modules) {
List<String> includeGlobs = module.getIncludedGlobs();
@@ -157,10 +157,10 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
ArrayList<File> files = new ArrayList<File>();
for (String incl : includeGlobs) {
- File check = new File(incl);
+ File check = new File(incl);
File root = new File(check.isAbsolute() ? Glob.rootPortion(incl) : serverRootPath);
-
- files.addAll(Glob.match(root, incl, Glob.ALPHABETICAL_COMPARATOR));
+
+ files.addAll(Glob.match(root, incl, Glob.ALPHABETICAL_COMPARATOR));
}
if (module.getExcludedGlobs() != null) {
@@ -173,17 +173,17 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
LOG.warn("Configuration files inclusion patterns contain a non-absolute file: " + configFile);
continue;
}
-
+
if (!configFile.exists()) {
LOG.warn("Configuration files inclusion patterns refer to a non-existent file: " + configFile);
continue;
}
-
+
if (configFile.isDirectory()) {
LOG.warn("Configuration files inclusion patterns refer to a directory: " + configFile);
continue;
}
-
+
if (!module.getConfigFiles().contains(configFile.getAbsolutePath())) {
module.addConfigFile(configFile.getAbsolutePath());
}
@@ -194,9 +194,9 @@ public class AugeasConfigurationApache extends PluginDescriptorBasedAugeasConfig
private static List<File> getIncludeFiles(String serverRoot, List<String> foundIncludes) {
List<File> ret = new ArrayList<File>();
for (String path : foundIncludes) {
- File check = new File(path);
- File root = new File(check.isAbsolute() ? Glob.rootPortion(path) : serverRoot);
- for (File f :Glob.match(root, path, Glob.ALPHABETICAL_COMPARATOR)){
+ File check = new File(path);
+ File root = new File(check.isAbsolute() ? Glob.rootPortion(path) : serverRoot);
+ for (File f : Glob.match(root, path, Glob.ALPHABETICAL_COMPARATOR)) {
ret.add(f);
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasTreeBuilderApache.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasTreeBuilderApache.java
index fbde74f..105d3f3 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasTreeBuilderApache.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/AugeasTreeBuilderApache.java
@@ -75,10 +75,10 @@ public class AugeasTreeBuilderApache implements AugeasTreeBuilder {
List<File> files = new ArrayList<File>();
- File check = new File(inclName);
- File root = new File(check.isAbsolute() ? Glob.rootPortion(inclName) : apacheConfig.getServerRootPath());
+ File check = new File(inclName);
+ File root = new File(check.isAbsolute() ? Glob.rootPortion(inclName) : apacheConfig.getServerRootPath());
files.addAll(Glob.match(root, inclName, Glob.ALPHABETICAL_COMPARATOR));
-
+
if (module.getExcludedGlobs() != null)
Glob.excludeAll(files, module.getExcludedGlobs());
@@ -115,8 +115,8 @@ public class AugeasTreeBuilderApache implements AugeasTreeBuilder {
for (AugeasNode node : createdNodes) {
if (canContainNestedNodes(node.getLabel())) {
- String labelName = node.getLabel()
- + ((node.getSeq() != 0) ? "[" + String.valueOf(node.getSeq()) + "]" : "");
+ String labelName =
+ node.getLabel() + ((node.getSeq() != 0) ? "[" + String.valueOf(node.getSeq()) + "]" : "");
updateIncludes((ApacheAugeasNode) node, tree, fileName + File.separator + labelName, null);
}
if (node.getLabel().equals("Include")) {
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingPositionToConfiguration.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingPositionToConfiguration.java
index a205296..a4d13d2 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingPositionToConfiguration.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingPositionToConfiguration.java
@@ -36,50 +36,50 @@ import org.rhq.rhqtransform.impl.AugeasToConfigurationSimple;
public class MappingPositionToConfiguration extends AugeasToConfigurationSimple {
public static final String LIST_PROPERTY_NAME = "IfModules";
- public static final String MAP_PROPERTY_NAME="IfModule";
- public static final String SIMPLE_PROPERTY_NAME="condition";
-
+ public static final String MAP_PROPERTY_NAME = "IfModule";
+ public static final String SIMPLE_PROPERTY_NAME = "condition";
+
public Configuration loadResourceConfiguration(AugeasNode startNode, ConfigurationDefinition resourceConfigDef)
- throws AugeasRhqException {
- if (startNode == null)
- return null;
-
- Configuration resourceConfig = new Configuration();
- String nodeName = startNode.getLabel();
- AugeasNode parentNode = getParentName(startNode);
- List<String> params = AugeasNodeSearch.getParams(startNode, parentNode);
-
- if (nodeName.equals("<Directory"))
- if (params.size()>0)
- params.remove(0);
-
- PropertyList list = new PropertyList(LIST_PROPERTY_NAME);
- for (String parameter : params){
- PropertyMap map = new PropertyMap(MAP_PROPERTY_NAME);
- PropertySimple condition = new PropertySimple(SIMPLE_PROPERTY_NAME,parameter);
- map.put(condition);
- list.add(map);
+ throws AugeasRhqException {
+ if (startNode == null)
+ return null;
+
+ Configuration resourceConfig = new Configuration();
+ String nodeName = startNode.getLabel();
+ AugeasNode parentNode = getParentName(startNode);
+ List<String> params = AugeasNodeSearch.getParams(startNode, parentNode);
+
+ if (nodeName.equals("<Directory"))
+ if (params.size() > 0)
+ params.remove(0);
+
+ PropertyList list = new PropertyList(LIST_PROPERTY_NAME);
+ for (String parameter : params) {
+ PropertyMap map = new PropertyMap(MAP_PROPERTY_NAME);
+ PropertySimple condition = new PropertySimple(SIMPLE_PROPERTY_NAME, parameter);
+ map.put(condition);
+ list.add(map);
+ }
+
+ resourceConfig.put(list);
+ return resourceConfig;
}
-
- resourceConfig.put(list);
- return resourceConfig;
-}
-
- private AugeasNode getParentName(AugeasNode node){
-
- AugeasNode tempNode = node.getParentNode();
-
- while (!tempNode.equals(tree.getRootNode())){
- if (tempNode.getLabel().equals("<Directory"))
- return tempNode;
-
- if (tempNode.getLabel().equals("<VirtualHost"))
- return tempNode;
-
- tempNode = tempNode.getParentNode();
- }
-
+
+ private AugeasNode getParentName(AugeasNode node) {
+
+ AugeasNode tempNode = node.getParentNode();
+
+ while (!tempNode.equals(tree.getRootNode())) {
+ if (tempNode.getLabel().equals("<Directory"))
+ return tempNode;
+
+ if (tempNode.getLabel().equals("<VirtualHost"))
+ return tempNode;
+
+ tempNode = tempNode.getParentNode();
+ }
+
return tree.getRootNode();
- }
-
+ }
+
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectiveToSimple.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectiveToSimple.java
index 5369514..52e884b 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectiveToSimple.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasDirectiveToSimple.java
@@ -33,67 +33,65 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
import org.rhq.plugins.apache.mapping.ConfigurationToAugeasApacheBase;
import org.rhq.rhqtransform.AugeasRhqException;
+
/**
*
* @author Filip Drabek
*
*/
-public class MappingToAugeasDirectiveToSimple extends ConfigurationToAugeasApacheBase{
+public class MappingToAugeasDirectiveToSimple extends ConfigurationToAugeasApacheBase {
-
- public void updateList(PropertyDefinitionList propDef, Property prop,
- AugeasNode listNode, int seq) throws AugeasRhqException {
- throw new AugeasRhqException("Error in configuration. There can not be any ListProperty in simple directive.");
-
- }
+ public void updateList(PropertyDefinitionList propDef, Property prop, AugeasNode listNode, int seq)
+ throws AugeasRhqException {
+ throw new AugeasRhqException("Error in configuration. There can not be any ListProperty in simple directive.");
- public void updateMap(PropertyDefinitionMap propDefMap, Property prop,
- AugeasNode mapNode, int seq) throws AugeasRhqException {
- throw new AugeasRhqException("Error in configuration. There can not be any MapProperty in simple directive.");
- }
+ }
+
+ public void updateMap(PropertyDefinitionMap propDefMap, Property prop, AugeasNode mapNode, int seq)
+ throws AugeasRhqException {
+ throw new AugeasRhqException("Error in configuration. There can not be any MapProperty in simple directive.");
+ }
- public void updateSimple(AugeasNode parentNode,
- PropertyDefinitionSimple propDef, Property prop, int seq)
- throws AugeasRhqException {
-
- String propName = propDef.getName();
- String propertyValue = ((PropertySimple) prop).getStringValue();
-
- List<AugeasNode> nodes = tree.matchRelative(parentNode, propName);
- try {
- //NODE WAS DELETED IN CONFIGURATION
- if (propertyValue == null || propertyValue.equals(""))
- {
- for (AugeasNode nod : nodes)
- nod.remove(false);
+ public void updateSimple(AugeasNode parentNode, PropertyDefinitionSimple propDef, Property prop, int seq)
+ throws AugeasRhqException {
+
+ String propName = propDef.getName();
+ String propertyValue = ((PropertySimple) prop).getStringValue();
+
+ List<AugeasNode> nodes = tree.matchRelative(parentNode, propName);
+ try {
+ //NODE WAS DELETED IN CONFIGURATION
+ if (propertyValue == null || propertyValue.equals("")) {
+ for (AugeasNode nod : nodes)
+ nod.remove(false);
return;
- }
-
+ }
+
//NODE IS NOT PRESENT IN AUGEAS
- if (nodes.isEmpty())
- {
- tree.createNode(parentNode, propName+File.separator+"param", propertyValue, 0);
- return;
- }
-
+ if (nodes.isEmpty()) {
+ tree.createNode(parentNode, propName + File.separator + "param", propertyValue, 0);
+ return;
+ }
+
//NODE IS PRESENT IN AUGEAS AND IN CONFIGURATION AND WILL BE UPDATED
- if (nodes.size()>1)
- throw new AugeasRhqException("Error in configuration. Directive"+propName+" is declared multiple times.");
-
+ if (nodes.size() > 1)
+ throw new AugeasRhqException("Error in configuration. Directive" + propName
+ + " is declared multiple times.");
+
List<AugeasNode> params = nodes.get(0).getChildByLabel("param");
-
+
if (params.isEmpty())
- throw new AugeasRhqException("Error in configuration. Directive"+propName+" has no value.");
-
+ throw new AugeasRhqException("Error in configuration. Directive" + propName + " has no value.");
+
if (params.size() > 1)
- throw new AugeasRhqException("Too many parameters in directive"+propName+" .");
-
+ throw new AugeasRhqException("Too many parameters in directive" + propName + " .");
+
AugeasNode node = params.get(0);
node.setValue(propertyValue);
-
- }catch(Exception e){
- throw new AugeasRhqException("Mapping configuration to Augeas failed. "+e.getMessage());
- }
+
+ } catch (Exception e) {
+ throw new AugeasRhqException("Mapping configuration to Augeas failed. " + e.getMessage());
}
+ }
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
index 1381861..a12374f 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
@@ -37,151 +37,141 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
import org.rhq.plugins.apache.mapping.ApacheDirectiveRegExpression;
import org.rhq.plugins.apache.mapping.ConfigurationToAugeasApacheBase;
import org.rhq.rhqtransform.AugeasRhqException;
+
/**
*
* @author Filip Drabek
*
*/
-public class MappingToAugeasParamPerMap extends ConfigurationToAugeasApacheBase{
-
- public void updateList(PropertyDefinitionList propDef, Property prop,
- AugeasNode listNode, int seq) throws AugeasRhqException {
-
- String propertyName = propDef.getName();
- PropertyDefinitionMap memberPropDef = (PropertyDefinitionMap)propDef.getMemberDefinition();
-
- List<AugeasNode> nodes = tree.matchRelative(listNode, propertyName);
-
- //THERE IS NO CONFIGURATION ALL NODES RELATED TO THE CONFIGURATION DEFINITION WILL BE DELETED
- if (prop==null)
- {
- for (AugeasNode node : nodes){
- node.remove(false);
- }
- return;
- }
-
- PropertyList list = (PropertyList) prop;
- List<List<PropertyMap>> map = sort(list);
-
- nodes = tree.matchRelative(listNode, propertyName);
-
-
- //THERE IS MORE CONFIGURATIONS THAN NODES, NEW NODES WILL BE CREATED
-
- if (map.size()>nodes.size())
- {
- for (int i=0;i<map.size()-nodes.size();i++){
- tree.createNode(listNode,propertyName,null,nodes.size()+i+1);
- }
- }
-
- //THERE IS LESS CONFIGURATIONS THAN NODES, REDUDANT NODES WILL BE DELETED
- if (map.size()<nodes.size())
- {
- for (int i=0;i<nodes.size()-map.size();i++){
- nodes.get(nodes.size()-i-1).remove(false);
- }
- }
-
-
+public class MappingToAugeasParamPerMap extends ConfigurationToAugeasApacheBase {
+
+ public void updateList(PropertyDefinitionList propDef, Property prop, AugeasNode listNode, int seq)
+ throws AugeasRhqException {
+
+ String propertyName = propDef.getName();
+ PropertyDefinitionMap memberPropDef = (PropertyDefinitionMap) propDef.getMemberDefinition();
+
+ List<AugeasNode> nodes = tree.matchRelative(listNode, propertyName);
+
+ //THERE IS NO CONFIGURATION ALL NODES RELATED TO THE CONFIGURATION DEFINITION WILL BE DELETED
+ if (prop == null) {
+ for (AugeasNode node : nodes) {
+ node.remove(false);
+ }
+ return;
+ }
+
+ PropertyList list = (PropertyList) prop;
+ List<List<PropertyMap>> map = sort(list);
+
nodes = tree.matchRelative(listNode, propertyName);
-
- int i=0;
- StringBuffer param= new StringBuffer();
- for (List<PropertyMap> directive: map){
- for (PropertyMap propMap : directive){
- for (PropertyDefinition propDefMap : memberPropDef.getPropertyDefinitions())
- {//for (Property propVal : propMap.getMap().values()){
- Property propVal = propMap.get(propDefMap.getName());
- if (propVal!=null)
- if (!propVal.getName().equals("_index")){
- param.append(" "+((PropertySimple) propVal).getStringValue());
- }
- }
-
- }
- List<String> params = ApacheDirectiveRegExpression.createParams(param.toString(), propertyName);
- updateNodeParams(nodes.get(i), params);
- param = new StringBuffer();
- i++;
- }
- }
-
-
- public void updateMap(PropertyDefinitionMap propDefMap, Property prop,
- AugeasNode mapNode, int seq) throws AugeasRhqException {
+
+ //THERE IS MORE CONFIGURATIONS THAN NODES, NEW NODES WILL BE CREATED
+
+ if (map.size() > nodes.size()) {
+ for (int i = 0; i < map.size() - nodes.size(); i++) {
+ tree.createNode(listNode, propertyName, null, nodes.size() + i + 1);
+ }
}
- public void updateSimple(AugeasNode parentNode,
- PropertyDefinitionSimple propDef, Property prop, int seq)
- throws AugeasRhqException {
-
+ //THERE IS LESS CONFIGURATIONS THAN NODES, REDUDANT NODES WILL BE DELETED
+ if (map.size() < nodes.size()) {
+ for (int i = 0; i < nodes.size() - map.size(); i++) {
+ nodes.get(nodes.size() - i - 1).remove(false);
+ }
}
-
- private List<List<PropertyMap>> sort(PropertyList list){
- List<List<PropertyMap>> map = new ArrayList<List<PropertyMap>>();
-
- int next = Integer.MAX_VALUE;
- int min=0;
- int count = 0;
-
- List<PropertyMap> tempList = new ArrayList<PropertyMap>();
-
- while(count<list.getList().size()){
- for (Property prop : list.getList()){
- PropertyMap propMap = (PropertyMap)prop;
- PropertySimple propSim = ((PropertySimple)propMap.get("_index"));
- int value;
- if (propSim ==null || propSim.getIntegerValue() == null)
- value = 0;
- else
- value = propSim.getIntegerValue().intValue();
-
- if (value == min){
- tempList.add(propMap);
- count = count + 1;
- }
- if (value > min && value<next){
- next = value;
- }
- }
- min = next;
- next = Integer.MAX_VALUE;
- if (!tempList.isEmpty())
- {
- map.add(tempList);
- tempList = new ArrayList<PropertyMap>();
- }
+
+ nodes = tree.matchRelative(listNode, propertyName);
+
+ int i = 0;
+ StringBuffer param = new StringBuffer();
+ for (List<PropertyMap> directive : map) {
+ for (PropertyMap propMap : directive) {
+ for (PropertyDefinition propDefMap : memberPropDef.getPropertyDefinitions()) {//for (Property propVal : propMap.getMap().values()){
+ Property propVal = propMap.get(propDefMap.getName());
+ if (propVal != null)
+ if (!propVal.getName().equals("_index")) {
+ param.append(" " + ((PropertySimple) propVal).getStringValue());
+ }
}
- return map;
+
+ }
+ List<String> params = ApacheDirectiveRegExpression.createParams(param.toString(), propertyName);
+ updateNodeParams(nodes.get(i), params);
+ param = new StringBuffer();
+ i++;
}
-
- private void updateNodeParams(AugeasNode node,List<String> params){
- List<AugeasNode> nodes = tree.matchRelative(node,"param");
-
- //THERE IS MORE CONFIGURATIONS THAN NODES, NEW NODES WILL BE CREATED
- if (params.size()>nodes.size())
- {
- for (int i=0;i<params.size()-nodes.size();i++){
- tree.createNode(node,"param",null,nodes.size()+i+1);
+ }
+
+ public void updateMap(PropertyDefinitionMap propDefMap, Property prop, AugeasNode mapNode, int seq)
+ throws AugeasRhqException {
+ }
+
+ public void updateSimple(AugeasNode parentNode, PropertyDefinitionSimple propDef, Property prop, int seq)
+ throws AugeasRhqException {
+
+ }
+
+ private List<List<PropertyMap>> sort(PropertyList list) {
+ List<List<PropertyMap>> map = new ArrayList<List<PropertyMap>>();
+
+ int next = Integer.MAX_VALUE;
+ int min = 0;
+ int count = 0;
+
+ List<PropertyMap> tempList = new ArrayList<PropertyMap>();
+
+ while (count < list.getList().size()) {
+ for (Property prop : list.getList()) {
+ PropertyMap propMap = (PropertyMap) prop;
+ PropertySimple propSim = ((PropertySimple) propMap.get("_index"));
+ int value;
+ if (propSim == null || propSim.getIntegerValue() == null)
+ value = 0;
+ else
+ value = propSim.getIntegerValue().intValue();
+
+ if (value == min) {
+ tempList.add(propMap);
+ count = count + 1;
+ }
+ if (value > min && value < next) {
+ next = value;
}
+ }
+ min = next;
+ next = Integer.MAX_VALUE;
+ if (!tempList.isEmpty()) {
+ map.add(tempList);
+ tempList = new ArrayList<PropertyMap>();
+ }
}
-
+ return map;
+ }
+
+ private void updateNodeParams(AugeasNode node, List<String> params) {
+ List<AugeasNode> nodes = tree.matchRelative(node, "param");
+
+ //THERE IS MORE CONFIGURATIONS THAN NODES, NEW NODES WILL BE CREATED
+ if (params.size() > nodes.size()) {
+ for (int i = 0; i < params.size() - nodes.size(); i++) {
+ tree.createNode(node, "param", null, nodes.size() + i + 1);
+ }
+ }
+
//THERE IS LESS CONFIGURATIONS THAN NODES, REDUDANT NODES WILL BE DELETED
- if (params.size() < nodes.size())
- {
- for (int i=0;i<nodes.size()-params.size();i++){
- nodes.get(nodes.size()-i-1).remove(false);
- }
+ if (params.size() < nodes.size()) {
+ for (int i = 0; i < nodes.size() - params.size(); i++) {
+ nodes.get(nodes.size() - i - 1).remove(false);
+ }
}
-
+
nodes = tree.matchRelative(node, "param");
- int i =0;
- for (AugeasNode tempNode : nodes){
+ int i = 0;
+ for (AugeasNode tempNode : nodes) {
tempNode.setValue(params.get(i));
- i++;
- }
-
+ i++;
}
+
+ }
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/Util.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/Util.java
index 6258771..aa53a17 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/Util.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/Util.java
@@ -35,9 +35,9 @@ import org.rhq.core.domain.configuration.definition.PropertySimpleType;
*/
class Util {
private Util() {
-
+
}
-
+
/**
* Creates a simple property from given definition and given value.
*
@@ -58,8 +58,9 @@ class Util {
if (!definition.getEnumeratedValues().isEmpty()) {
//options with empty values correspond to null values
- if (value == null) value = "";
-
+ if (value == null)
+ value = "";
+
//apache configuration values are usually case-insensitive.
String valLowerCase = value.toLowerCase();
for (PropertyDefinitionEnumeration option : definition.getEnumeratedValues()) {
@@ -68,7 +69,7 @@ class Util {
}
}
}
-
+
return new PropertySimple(name, value);
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheAugeasMapping.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheAugeasMapping.java
index 8146de9..4c3d102 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheAugeasMapping.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheAugeasMapping.java
@@ -32,6 +32,7 @@ import org.rhq.core.domain.configuration.Property;
import org.rhq.core.domain.configuration.definition.ConfigurationDefinition;
import org.rhq.core.domain.configuration.definition.PropertyDefinition;
import org.rhq.rhqtransform.RhqAugeasMapping;
+
/**
*
* @author Filip Drabek
@@ -39,48 +40,48 @@ import org.rhq.rhqtransform.RhqAugeasMapping;
*/
public class ApacheAugeasMapping implements RhqAugeasMapping {
- private AugeasTree tree;
- public ApacheAugeasMapping(AugeasTree tree) {
- this.tree = tree;
- }
-
- public Configuration updateConfiguration(AugeasNode node,ConfigurationDefinition configDef){
+ private AugeasTree tree;
+
+ public ApacheAugeasMapping(AugeasTree tree) {
+ this.tree = tree;
+ }
+
+ public Configuration updateConfiguration(AugeasNode node, ConfigurationDefinition configDef) {
Configuration resourceConfig = new Configuration();
Collection<PropertyDefinition> propDefs = configDef.getPropertyDefinitions().values();
for (PropertyDefinition propDef : propDefs) {
- DirectiveMapping mapping = ApacheDirectiveRegExpression.getMappingType(propDef.getName());
- ConfigurationDefinition def = new ConfigurationDefinition("temp","");
- def.put(propDef);
- Configuration conf = mapping.mapToConfiguration(tree, node, def);
- for (Property prop : conf.getProperties())
- {
- resourceConfig.put(prop);
- }
+ DirectiveMapping mapping = ApacheDirectiveRegExpression.getMappingType(propDef.getName());
+ ConfigurationDefinition def = new ConfigurationDefinition("temp", "");
+ def.put(propDef);
+ Configuration conf = mapping.mapToConfiguration(tree, node, def);
+ for (Property prop : conf.getProperties()) {
+ resourceConfig.put(prop);
+ }
}
return resourceConfig;
- }
-
+ }
+
public void updateAugeas(AugeasProxy augeasComponent, Configuration config, ConfigurationDefinition configDef) {
-
+
}
public Configuration updateConfiguration(AugeasProxy augeasComponent, ConfigurationDefinition configDef) {
return null;
}
-
- public void updateAugeas(AugeasNode node,Configuration config,ConfigurationDefinition configDef){
-
- Collection<PropertyDefinition> propDefs = configDef.getPropertyDefinitions().values();
-
- for (PropertyDefinition propDef : propDefs) {
- DirectiveMapping mapping = ApacheDirectiveRegExpression.getMappingType(propDef.getName());
- ConfigurationDefinition def = new ConfigurationDefinition("temp","");
- def.put(propDef);
- mapping.mapToAugeas(tree, node, config, def);
- }
+
+ public void updateAugeas(AugeasNode node, Configuration config, ConfigurationDefinition configDef) {
+
+ Collection<PropertyDefinition> propDefs = configDef.getPropertyDefinitions().values();
+
+ for (PropertyDefinition propDef : propDefs) {
+ DirectiveMapping mapping = ApacheDirectiveRegExpression.getMappingType(propDef.getName());
+ ConfigurationDefinition def = new ConfigurationDefinition("temp", "");
+ def.put(propDef);
+ mapping.mapToAugeas(tree, node, config, def);
+ }
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
index 404fb5d..a2f8570 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ApacheDirectiveRegExpression.java
@@ -64,7 +64,7 @@ public class ApacheDirectiveRegExpression {
MAPPING_TYPE.put("AllowOverride", DirectiveMapping.PARAM_PER_MAP);
MAPPING_TYPE.put("DirectoryIndex", DirectiveMapping.PARAM_PER_MAP);
MAPPING_TYPE.put("NameVirtualHost", DirectiveMapping.DIRECTIVE_PER_MAP_INDEX);
- MAPPING_TYPE.put("IfModules",DirectiveMapping.POSITION_PROPERTY);
+ MAPPING_TYPE.put("IfModules", DirectiveMapping.POSITION_PROPERTY);
}
public static final String WORD = "\"(?:[^\"\n]|\\\")*\"|'(?:[^'\n]|\\\')*'|[^'\" \t\n]+";
@@ -82,45 +82,48 @@ public class ApacheDirectiveRegExpression {
DIRECTIVE_REGEX = new HashMap<String, Pattern[]>();
DIRECTIVE_REGEX.put("Alias",
new Pattern[] { Pattern.compile(WS + "(" + WORD + ")" + WS + "(" + WORD + ")" + WS) });
- DIRECTIVE_REGEX.put("CustomLog", new Pattern[] { Pattern.compile(WS + "(" + WORD + ")" + "(?:" + WS_MAN + "("
- + WORD + ")" + ")?" + WS) });
- DIRECTIVE_REGEX.put("ErrorDocument", new Pattern[] { Pattern.compile(WS + "(" + NUM + ")" + WS_MAN + "(" + WORD
- + ")" + WS) });
- DIRECTIVE_REGEX.put("Options", new Pattern[] {Pattern.compile(WS+"(Add|Remove|Set)"+WS+"([a-zA-Z]+)") });
- DIRECTIVE_REGEX.put("Allow", new Pattern[] { Pattern.compile("from"),
- Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
- DIRECTIVE_REGEX.put("Deny", new Pattern[] { Pattern.compile("from"),
- Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
- DIRECTIVE_REGEX.put("Listen", new Pattern[] { Pattern
- .compile("(?:((?:\\[[a-zA-Z0-9:]+\\])|(?:[0-9\\.]+)):)?([0-9]+)(?:" + WS_MAN + "(" + WORD + "))?") });
+ DIRECTIVE_REGEX.put("CustomLog",
+ new Pattern[] { Pattern.compile(WS + "(" + WORD + ")" + "(?:" + WS_MAN + "(" + WORD + ")" + ")?" + WS) });
+ DIRECTIVE_REGEX.put("ErrorDocument",
+ new Pattern[] { Pattern.compile(WS + "(" + NUM + ")" + WS_MAN + "(" + WORD + ")" + WS) });
+ DIRECTIVE_REGEX.put("Options", new Pattern[] { Pattern.compile(WS + "(Add|Remove|Set)" + WS + "([a-zA-Z]+)") });
+ DIRECTIVE_REGEX.put("Allow",
+ new Pattern[] { Pattern.compile("from"), Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
+ DIRECTIVE_REGEX.put("Deny",
+ new Pattern[] { Pattern.compile("from"), Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
+ DIRECTIVE_REGEX.put(
+ "Listen",
+ new Pattern[] { Pattern.compile("(?:((?:\\[[a-zA-Z0-9:]+\\])|(?:[0-9\\.]+)):)?([0-9]+)(?:" + WS_MAN + "("
+ + WORD + "))?") });
DIRECTIVE_REGEX.put("ServerAlias", new Pattern[] { Pattern.compile(WS + "(" + WORD + ")") });
- DIRECTIVE_REGEX.put("AllowOverride", new Pattern[] { Pattern
- .compile(WS+"(All|None|AuthConfig|FileInfo|Indexes|Limit|Options)") });
- DIRECTIVE_REGEX.put("DirectoryIndex", new Pattern[] { Pattern.compile(WS+ "(" + WORD + ")" + WS) });
- DIRECTIVE_REGEX.put("NameVirtualHost", new Pattern[] { Pattern.compile(WS+ "(" + WORD + ")"+ WS) });
+ DIRECTIVE_REGEX.put("AllowOverride",
+ new Pattern[] { Pattern.compile(WS + "(All|None|AuthConfig|FileInfo|Indexes|Limit|Options)") });
+ DIRECTIVE_REGEX.put("DirectoryIndex", new Pattern[] { Pattern.compile(WS + "(" + WORD + ")" + WS) });
+ DIRECTIVE_REGEX.put("NameVirtualHost", new Pattern[] { Pattern.compile(WS + "(" + WORD + ")" + WS) });
}
-
private static final Map<String, Pattern[]> DIRECTIVEREGEX_TO_AUGEAS;
static {
- DIRECTIVEREGEX_TO_AUGEAS = new HashMap<String, Pattern[]>();
- DIRECTIVEREGEX_TO_AUGEAS.put("Options", new Pattern[] { Pattern.compile(WS+"([+-]?"+WS+"[a-zA-Z]+)"+WS) });
- DIRECTIVEREGEX_TO_AUGEAS.put("Allow", new Pattern[] { Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
- DIRECTIVEREGEX_TO_AUGEAS.put("Deny", new Pattern[] { Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
- DIRECTIVEREGEX_TO_AUGEAS.put("ServerAlias", new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")") });
- DIRECTIVEREGEX_TO_AUGEAS.put("DirectoryIndex", new Pattern[] { Pattern.compile(WS_MAN+ "(" + WORD + ")") });
- DIRECTIVEREGEX_TO_AUGEAS.put("Alias",
- new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")" + WS_MAN + "(" + WORD + ")" + WS) });
- DIRECTIVEREGEX_TO_AUGEAS.put("CustomLog", new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")" + "(?:" + WS_MAN + "("
- + WORD + ")" + ")?") });
- DIRECTIVEREGEX_TO_AUGEAS.put("AllowOverride", new Pattern[] { Pattern
- .compile(WS+"(All|None|AuthConfig|FileInfo|Indexes|Limit|Options)") });
- DIRECTIVEREGEX_TO_AUGEAS.put("Listen", new Pattern[] { Pattern.compile(WS+ "(" + WORD + ")")});
- DIRECTIVEREGEX_TO_AUGEAS.put("NameVirtualHost", new Pattern[] { Pattern.compile(WS+ "(" + WORD +")" + WS) });
- DIRECTIVEREGEX_TO_AUGEAS.put("ErrorDocument", new Pattern[] { Pattern.compile(WS_MAN + "(" + NUM + ")" + WS_MAN + "(" + WORD
- + ")") });
-
+ DIRECTIVEREGEX_TO_AUGEAS = new HashMap<String, Pattern[]>();
+ DIRECTIVEREGEX_TO_AUGEAS.put("Options",
+ new Pattern[] { Pattern.compile(WS + "([+-]?" + WS + "[a-zA-Z]+)" + WS) });
+ DIRECTIVEREGEX_TO_AUGEAS.put("Allow", new Pattern[] { Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("Deny", new Pattern[] { Pattern.compile("(?:" + WS_MAN + "(" + WORD + "))") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("ServerAlias", new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("DirectoryIndex", new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("Alias",
+ new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")" + WS_MAN + "(" + WORD + ")" + WS) });
+ DIRECTIVEREGEX_TO_AUGEAS.put("CustomLog",
+ new Pattern[] { Pattern.compile(WS_MAN + "(" + WORD + ")" + "(?:" + WS_MAN + "(" + WORD + ")" + ")?") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("AllowOverride",
+ new Pattern[] { Pattern.compile(WS + "(All|None|AuthConfig|FileInfo|Indexes|Limit|Options)") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("Listen", new Pattern[] { Pattern.compile(WS + "(" + WORD + ")") });
+ DIRECTIVEREGEX_TO_AUGEAS.put("NameVirtualHost", new Pattern[] { Pattern.compile(WS + "(" + WORD + ")" + WS) });
+ DIRECTIVEREGEX_TO_AUGEAS.put("ErrorDocument",
+ new Pattern[] { Pattern.compile(WS_MAN + "(" + NUM + ")" + WS_MAN + "(" + WORD + ")") });
+
}
+
/**
* Parses the parameters of the supplied node and returns a list
* of strings, each containing a value for a simple property
@@ -160,64 +163,64 @@ public class ApacheDirectiveRegExpression {
boolean updated = true;
while (updated & startIndex < value.length())
updated = false;
- for (Pattern pattern : patterns) {
- Matcher m = pattern.matcher(value);
- while (m.find(startIndex)) {
- for (int i = 1; i <= m.groupCount(); i++) {
- String val = m.group(i);
- result.add(val);
- }
- updated = true;
- startIndex = m.end();
+ for (Pattern pattern : patterns) {
+ Matcher m = pattern.matcher(value);
+ while (m.find(startIndex)) {
+ for (int i = 1; i <= m.groupCount(); i++) {
+ String val = m.group(i);
+ result.add(val);
}
+ updated = true;
+ startIndex = m.end();
}
+ }
return result;
}
-
- public static List<String> createParams(String params,String name){
- List<String> nodeParams = new ArrayList<String>();
-
+
+ public static List<String> createParams(String params, String name) {
+ List<String> nodeParams = new ArrayList<String>();
+
if (!DIRECTIVEREGEX_TO_AUGEAS.containsKey(name)) {
- nodeParams.add(params);
+ nodeParams.add(params);
return nodeParams;
}
-
- if (name.equals("Allow") || name.equals("Deny")){
- nodeParams.add("from");
+
+ if (name.equals("Allow") || name.equals("Deny")) {
+ nodeParams.add("from");
}
//each regex is applied as long as it matches something
Pattern[] patterns = DIRECTIVEREGEX_TO_AUGEAS.get(name);
int startIndex = 0;
- boolean updated =true;
-
+ boolean updated = true;
+
params = SpecificParams.prepareForAugeas(name, params);
-
- while (updated & startIndex < params.length())
+
+ while (updated & startIndex < params.length())
updated = false;
- for (Pattern pattern : patterns) {
- Matcher m = pattern.matcher(params);
- while (m.find(startIndex)) {
- for (int i = 1; i <= m.groupCount(); i++) {
- String val = m.group(i);
- if (val!=null)
- nodeParams.add(val);
- }
- updated = true;
- startIndex = m.end();
+ for (Pattern pattern : patterns) {
+ Matcher m = pattern.matcher(params);
+ while (m.find(startIndex)) {
+ for (int i = 1; i <= m.groupCount(); i++) {
+ String val = m.group(i);
+ if (val != null)
+ nodeParams.add(val);
}
+ updated = true;
+ startIndex = m.end();
}
-
- if (name.equals("Options")){
- int i=0;
- for (String param : nodeParams){
- param = param.replaceAll(" ", "");
- nodeParams.set(i, param);
- i++;
- }
}
-
+
+ if (name.equals("Options")) {
+ int i = 0;
+ for (String param : nodeParams) {
+ param = param.replaceAll(" ", "");
+ nodeParams.set(i, param);
+ i++;
+ }
+ }
+
return nodeParams;
}
@@ -230,11 +233,11 @@ public class ApacheDirectiveRegExpression {
* @return the mapping type that can be used to perform the mapping to the property.
*/
public static DirectiveMapping getMappingType(String directiveName) {
- DirectiveMapping map = MAPPING_TYPE.get(directiveName);
+ DirectiveMapping map = MAPPING_TYPE.get(directiveName);
if (map == null)
map = DirectiveMapping.SIMPLE_PROP;
return map;
}
-
+
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ConfigurationToAugeasApacheBase.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ConfigurationToAugeasApacheBase.java
index 27e416e..1ca0c84 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ConfigurationToAugeasApacheBase.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/ConfigurationToAugeasApacheBase.java
@@ -35,6 +35,7 @@ import org.rhq.core.domain.configuration.definition.PropertyDefinitionMap;
import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
import org.rhq.rhqtransform.AugeasRhqException;
import org.rhq.rhqtransform.ConfigurationToAugeas;
+
/**
*
* @author Filip Drabek
@@ -52,18 +53,18 @@ public abstract class ConfigurationToAugeasApacheBase implements ConfigurationTo
Configuration resourceConfig) throws AugeasRhqException {
Collection<PropertyDefinition> propDefs = resourceConfigDef.getPropertyDefinitions().values();
-
+
for (PropertyDefinition propDef : propDefs) {
- Property prop = resourceConfig.get(propDef.getName());
+ Property prop = resourceConfig.get(propDef.getName());
updateProperty(propDef, prop, node, 0);
}
}
public abstract void updateMap(PropertyDefinitionMap propDefMap, Property prop, AugeasNode mapNode, int seq)
- throws AugeasRhqException ;
-
+ throws AugeasRhqException;
+
public abstract void updateList(PropertyDefinitionList propDef, Property prop, AugeasNode listNode, int seq)
- throws AugeasRhqException;
+ throws AugeasRhqException;
public abstract void updateSimple(AugeasNode parentNode, PropertyDefinitionSimple propDef, Property prop, int seq)
throws AugeasRhqException;
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/DirectiveMapping.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/DirectiveMapping.java
index 77538ba..b2bd821 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/DirectiveMapping.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/DirectiveMapping.java
@@ -47,71 +47,81 @@ import org.rhq.rhqtransform.ConfigurationToAugeas;
public enum DirectiveMapping {
DIRECTIVE_PER_MAP {
- public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode, ConfigurationDefinition resourceConfigDef) {
+ public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode,
+ ConfigurationDefinition resourceConfigDef) {
AugeasToConfiguration config = new MappingDirectivePerMap();
config.setTree(tree);
return config.loadResourceConfiguration(startNode, resourceConfigDef);
};
-
- public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config, ConfigurationDefinition configDef){
- ConfigurationToAugeas mapping = new MappingToAugeasDirectivePerMap();
- mapping.setTree(tree);
- mapping.updateResourceConfiguration(node, configDef, config);
+
+ public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config,
+ ConfigurationDefinition configDef) {
+ ConfigurationToAugeas mapping = new MappingToAugeasDirectivePerMap();
+ mapping.setTree(tree);
+ mapping.updateResourceConfiguration(node, configDef, config);
}
-
+
},
-
+
PARAM_PER_MAP {
- public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode, ConfigurationDefinition resourceConfigDef) {
+ public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode,
+ ConfigurationDefinition resourceConfigDef) {
AugeasToConfiguration config = new MappingParamPerMap();
config.setTree(tree);
return config.loadResourceConfiguration(startNode, resourceConfigDef);
};
-
- public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config, ConfigurationDefinition configDef) {
- ConfigurationToAugeas mapping = new MappingToAugeasParamPerMap();
- mapping.setTree(tree);
- mapping.updateResourceConfiguration(node, configDef, config);
+
+ public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config,
+ ConfigurationDefinition configDef) {
+ ConfigurationToAugeas mapping = new MappingToAugeasParamPerMap();
+ mapping.setTree(tree);
+ mapping.updateResourceConfiguration(node, configDef, config);
}
},
-
+
DIRECTIVE_PER_MAP_INDEX {
- public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode, ConfigurationDefinition resourceConfigDef) {
+ public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode,
+ ConfigurationDefinition resourceConfigDef) {
AugeasToConfiguration config = new MappingDirectivePerMapIndex();
config.setTree(tree);
return config.loadResourceConfiguration(startNode, resourceConfigDef);
};
-
- public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config, ConfigurationDefinition configDef){
- ConfigurationToAugeas mapping = new MappingToAugeasDirectivePerMapIndex();
- mapping.setTree(tree);
- mapping.updateResourceConfiguration(node, configDef, config);
+
+ public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config,
+ ConfigurationDefinition configDef) {
+ ConfigurationToAugeas mapping = new MappingToAugeasDirectivePerMapIndex();
+ mapping.setTree(tree);
+ mapping.updateResourceConfiguration(node, configDef, config);
}
},
-
+
POSITION_PROPERTY {
- public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode, ConfigurationDefinition resourceConfigDef) {
+ public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode,
+ ConfigurationDefinition resourceConfigDef) {
AugeasToConfiguration config = new MappingPositionToConfiguration();
config.setTree(tree);
return config.loadResourceConfiguration(startNode, resourceConfigDef);
};
-
- public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config, ConfigurationDefinition configDef){
+
+ public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config,
+ ConfigurationDefinition configDef) {
}
},
-
+
SIMPLE_PROP {
- public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode, ConfigurationDefinition resourceConfigDef) {
+ public Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode,
+ ConfigurationDefinition resourceConfigDef) {
AugeasToConfiguration config = new MappingDirectiveToSimpleProperty();
config.setTree(tree);
return config.loadResourceConfiguration(startNode, resourceConfigDef);
};
-
- public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config, ConfigurationDefinition configDef){
- ConfigurationToAugeas mapping = new MappingToAugeasDirectiveToSimple();
- mapping.setTree(tree);
- mapping.updateResourceConfiguration(node, configDef, config);
+
+ public void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config,
+ ConfigurationDefinition configDef) {
+ ConfigurationToAugeas mapping = new MappingToAugeasDirectiveToSimple();
+ mapping.setTree(tree);
+ mapping.updateResourceConfiguration(node, configDef, config);
}
};
@@ -127,5 +137,6 @@ public enum DirectiveMapping {
public abstract Configuration mapToConfiguration(AugeasTree tree, AugeasNode startNode,
ConfigurationDefinition resourceConfigDef);
- public abstract void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config, ConfigurationDefinition configDef) ;
+ public abstract void mapToAugeas(AugeasTree tree, AugeasNode node, Configuration config,
+ ConfigurationDefinition configDef);
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
index e600dce..b0640a7 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/mapping/SpecificParams.java
@@ -20,18 +20,17 @@ public class SpecificParams {
* @param param Parameters of directive.
* @return directive prepared for validation without configuration specific parameters.
*/
- public static String prepareForAugeas(String name,String value){
- if (name.equals("Options"))
- {
+ public static String prepareForAugeas(String name, String value) {
+ if (name.equals("Options")) {
StringBuilder ret = new StringBuilder();
- Pattern pattern = Pattern.compile("[ \t]*(Add|Remove|Set)[ \t]*([a-zA-Z]+)");
+ Pattern pattern = Pattern.compile("[ \t]*(Add|Remove|Set)[ \t]*([a-zA-Z]+)");
int startIndex = 0;
boolean updated = true;
- while (updated && startIndex < value.length()){
+ while (updated && startIndex < value.length()) {
updated = false;
- Matcher m = pattern.matcher(value);
- while (m.find(startIndex)) {
- if (m.groupCount() >0)
+ Matcher m = pattern.matcher(value);
+ while (m.find(startIndex)) {
+ if (m.groupCount() > 0)
for (int i = 1; i <= m.groupCount(); i++) {
String val = m.group(i);
if (val.equals("Add"))
@@ -40,42 +39,42 @@ public class SpecificParams {
val = "-";
if (val.equals("Set"))
val = "";
- ret.append(val+ " ");
+ ret.append(val + " ");
}
- updated = true;
- startIndex = m.end();
- }
+ updated = true;
+ startIndex = m.end();
+ }
}
- if (ret.length()>0)
- ret.deleteCharAt(ret.length()-1);
-
+ if (ret.length() > 0)
+ ret.deleteCharAt(ret.length() - 1);
+
return ret.toString();
}
-
- if (name.equals("Listen")){
+
+ if (name.equals("Listen")) {
int i;
StringBuilder val = new StringBuilder(value);
while (val.charAt(0) == ' ' || val.charAt(0) == '\t')
val.deleteCharAt(0);
-
- String [] str = val.toString().split("[ \t]+");
-
+
+ String[] str = val.toString().split("[ \t]+");
+
Pattern pat = Pattern.compile("[0-9]+");
StringBuilder bld = new StringBuilder();
- for (i =0;i<str.length;i++){
+ for (i = 0; i < str.length; i++) {
Matcher m = pat.matcher(str[i]);
- if (m.matches())
- {if (i==1)
- str[i] = ":"+str[i];
- else
- str[i]=" "+str[i];
- }else
- str[i]=" "+str[i];
+ if (m.matches()) {
+ if (i == 1)
+ str[i] = ":" + str[i];
+ else
+ str[i] = " " + str[i];
+ } else
+ str[i] = " " + str[i];
bld.append(str[i]);
}
- return bld.toString();
+ return bld.toString();
}
-
+
return value;
}
@@ -89,18 +88,17 @@ public class SpecificParams {
* @return directive prepared for validation without configuration specific parameters.
*/
- public static StringBuilder prepareForConfiguration(String name,StringBuilder value){
- if (name.equals("Options"))
- {
+ public static StringBuilder prepareForConfiguration(String name, StringBuilder value) {
+ if (name.equals("Options")) {
StringBuilder ret = new StringBuilder();
- Pattern pattern = Pattern.compile("[ \t]*([+-]?)([a-zA-Z]+)");
+ Pattern pattern = Pattern.compile("[ \t]*([+-]?)([a-zA-Z]+)");
int startIndex = 0;
boolean updated = true;
- while (updated && startIndex < value.length()){
+ while (updated && startIndex < value.length()) {
updated = false;
- Matcher m = pattern.matcher(value);
- while (m.find(startIndex)) {
- if (m.groupCount() >0)
+ Matcher m = pattern.matcher(value);
+ while (m.find(startIndex)) {
+ if (m.groupCount() > 0)
for (int i = 1; i <= m.groupCount(); i++) {
String val = m.group(i);
if (val.equals("+"))
@@ -109,18 +107,18 @@ public class SpecificParams {
val = "Remove";
if (val.equals(""))
val = "Set";
- ret.append(val+ " ");
+ ret.append(val + " ");
}
- updated = true;
- startIndex = m.end();
- }
+ updated = true;
+ startIndex = m.end();
+ }
}
- if (ret.length()>0)
- ret.deleteCharAt(ret.length()-1);
-
+ if (ret.length() > 0)
+ ret.deleteCharAt(ret.length() - 1);
+
return ret;
}
-
+
return value;
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigReader.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigReader.java
index 6fd2cb9..1be3408 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigReader.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigReader.java
@@ -11,53 +11,51 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ApacheConfigReader {
- private static final String EMPTY_LINE="^[\t ]*$";
+ private static final String EMPTY_LINE = "^[\t ]*$";
private static final Pattern emptyLinePattern = Pattern.compile(EMPTY_LINE);
private static final Log log = LogFactory.getLog(ApacheConfigReader.class);
-
- public static void buildTree(String path,ApacheParser parser){
- searchFile(path, parser);
+
+ public static void buildTree(String path, ApacheParser parser) {
+ searchFile(path, parser);
}
-
- public static void searchFile(String path,ApacheParser parser){
+
+ public static void searchFile(String path, ApacheParser parser) {
File configFile = new File(path);
- if (!configFile.exists()){
- log.warn("Apache configuration file "+path+" was not found.");
- throw new ApacheParserException("Apache configuration file "+path+" was not found.");
- }
-
- BufferedReader br=null;
-
- try {
- FileInputStream fstream = new FileInputStream(configFile);
- br = new BufferedReader(new InputStreamReader(fstream));
- String strLine;
-
- while ((strLine = br.readLine()) != null) {
- Matcher matcher = emptyLinePattern.matcher(strLine);
- if (!matcher.matches())
- {
- ApacheDirective dir = new ApacheDirective(strLine);
- dir.setFile(path);
- String name = dir.getName();
- if (!name.equals("#")){
- if (name.startsWith("</"))
- parser.endNestedDirective(dir);
- else
- if (name.startsWith("<"))
+ if (!configFile.exists()) {
+ log.warn("Apache configuration file " + path + " was not found.");
+ throw new ApacheParserException("Apache configuration file " + path + " was not found.");
+ }
+
+ BufferedReader br = null;
+
+ try {
+ FileInputStream fstream = new FileInputStream(configFile);
+ br = new BufferedReader(new InputStreamReader(fstream));
+ String strLine;
+
+ while ((strLine = br.readLine()) != null) {
+ Matcher matcher = emptyLinePattern.matcher(strLine);
+ if (!matcher.matches()) {
+ ApacheDirective dir = new ApacheDirective(strLine);
+ dir.setFile(path);
+ String name = dir.getName();
+ if (!name.equals("#")) {
+ if (name.startsWith("</"))
+ parser.endNestedDirective(dir);
+ else if (name.startsWith("<"))
parser.startNestedDirective(dir);
else
parser.addDirective(dir);
+ }
}
- }
- }
+ }
br.close();
-
- }catch(Exception e){
+
+ } catch (Exception e) {
try {
- if (br!=null)
- br.close();
- }catch(Exception ee){
+ if (br != null)
+ br.close();
+ } catch (Exception ee) {
}
throw new ApacheParserException(e);
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
index 185db68..3c942c3 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheConfigWriter.java
@@ -11,7 +11,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
-@SuppressWarnings({"UnusedDeclaration"})
+@SuppressWarnings({ "UnusedDeclaration" })
public class ApacheConfigWriter {
private static final Log log = LogFactory.getLog(ApacheConfigReader.class);
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
index d02e447..1930fb0 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirective.java
@@ -14,35 +14,35 @@ public class ApacheDirective implements Cloneable {
private boolean isComment;
private static final String WS = "[ \t]*";
private static final String WORD = "\"(?:[^\"\n]|\\\")*\"|'(?:[^'\n]|\\\')*'|[^'\" \t\n]+";
- private static final String DIRECTIVE_REGEX = WS + "(" + WORD + ")" + WS;
- private static final String COMMENT_REGEX="^[\t ]*#.*+$";
- private boolean updated=false;
-
+ private static final String DIRECTIVE_REGEX = WS + "(" + WORD + ")" + WS;
+ private static final String COMMENT_REGEX = "^[\t ]*#.*+$";
+ private boolean updated = false;
+
private static final Pattern DIRECTIVE_PATTERN = Pattern.compile(DIRECTIVE_REGEX);
private static final Pattern COMMENT_PATTERN = Pattern.compile(COMMENT_REGEX);
private List<ApacheDirective> childNodes;
private ApacheDirective parentNode;
private String file;
-
- public ApacheDirective(){
+
+ public ApacheDirective() {
values = new ArrayList<String>();
childNodes = new ArrayList<ApacheDirective>();
}
-
- public ApacheDirective(String directive){
+
+ public ApacheDirective(String directive) {
values = new ArrayList<String>();
childNodes = new ArrayList<ApacheDirective>();
-
+
Matcher matcher = COMMENT_PATTERN.matcher(directive);
- if (matcher.matches()){
+ if (matcher.matches()) {
isComment = true;
values.add(directive);
name = "#";
- }else{
- int startIndex = 0;
- boolean updated = true;
- while (updated && startIndex < directive.length()){
- updated = false;
+ } else {
+ int startIndex = 0;
+ boolean updated = true;
+ while (updated && startIndex < directive.length()) {
+ updated = false;
Matcher m = DIRECTIVE_PATTERN.matcher(directive);
while (m.find(startIndex)) {
for (int i = 1; i <= m.groupCount(); i++) {
@@ -53,20 +53,20 @@ public class ApacheDirective implements Cloneable {
startIndex = m.end();
}
}
- if (values.isEmpty())
- throw new RuntimeException("Directive "+directive+"is not in valid format.");
-
- String lastVal = values.get(values.size()-1);
- if (lastVal.endsWith(">")){
- lastVal = lastVal.substring(0,lastVal.length()-1);
- values.set(values.size()-1, lastVal);
- }
-
- name = values.get(0);
- values.remove(0);
+ if (values.isEmpty())
+ throw new RuntimeException("Directive " + directive + "is not in valid format.");
+
+ String lastVal = values.get(values.size() - 1);
+ if (lastVal.endsWith(">")) {
+ lastVal = lastVal.substring(0, lastVal.length() - 1);
+ values.set(values.size() - 1, lastVal);
+ }
+
+ name = values.get(0);
+ values.remove(0);
}
}
-
+
public String getName() {
return name;
}
@@ -90,39 +90,39 @@ public class ApacheDirective implements Cloneable {
public void setNested(boolean isNested) {
this.isNested = isNested;
}
-
- public String getValuesAsString(){
+
+ public String getValuesAsString() {
StringBuilder buf = new StringBuilder();
- for (String val : values){
+ for (String val : values) {
buf.append(val);
}
return buf.toString();
}
-
- public void addChildDirective(ApacheDirective directive){
+
+ public void addChildDirective(ApacheDirective directive) {
childNodes.add(directive);
}
-
- public List<ApacheDirective> getChildDirectives(){
+
+ public List<ApacheDirective> getChildDirectives() {
return childNodes;
}
-
- public List<ApacheDirective> getChildByName(String name){
+
+ public List<ApacheDirective> getChildByName(String name) {
List<ApacheDirective> kids = new ArrayList<ApacheDirective>();
- for (ApacheDirective dir : childNodes){
- if (dir.getName().equals(name)){
- kids.add(dir);
- }
+ for (ApacheDirective dir : childNodes) {
+ if (dir.getName().equals(name)) {
+ kids.add(dir);
+ }
}
return kids;
}
-
- public ApacheDirective getParentNode(){
+
+ public ApacheDirective getParentNode() {
return parentNode;
}
-
- public void setParentNode(ApacheDirective parent){
- this.parentNode = parent;
+
+ public void setParentNode(ApacheDirective parent) {
+ this.parentNode = parent;
}
public boolean isRootNode() {
@@ -132,7 +132,7 @@ public class ApacheDirective implements Cloneable {
public void setRootNode(boolean isRootNode) {
this.isRootNode = isRootNode;
}
-
+
public boolean isUpdated() {
return updated;
}
@@ -140,75 +140,75 @@ public class ApacheDirective implements Cloneable {
public void setUpdated(boolean updated) {
this.updated = updated;
}
-
+
public String getFile() {
if (isRootNode)
return null;
-
- if (file == null){
+
+ if (file == null) {
List<ApacheDirective> dir = parentNode.getChildByName(name);
- for (int i=0;i<dir.size();i++)
- if (dir.get(i) == this){
- file = dir.get(i-1).getFile();
+ for (int i = 0; i < dir.size(); i++)
+ if (dir.get(i) == this) {
+ file = dir.get(i - 1).getFile();
break;
}
- }
+ }
return file;
}
public void setFile(String file) {
this.file = file;
- }
-
- public void removeChilDirective(ApacheDirective dir){
+ }
+
+ public void removeChilDirective(ApacheDirective dir) {
if (childNodes.contains(dir))
- childNodes.remove(dir);
+ childNodes.remove(dir);
}
-
- public void remove(){
+
+ public void remove() {
parentNode.removeChilDirective(this);
}
-
- public String getText(){
- StringBuilder builder = new StringBuilder();
- builder.append(name+" ");
- for (String temp : values){
- builder.append(temp+" ");
- }
- builder.deleteCharAt(builder.length()-1);
- if (isNested)
- builder.append(">");
-
- return builder.toString();
- }
-
- public int getSeq(){
- List<ApacheDirective> directives = parentNode.getChildByName(name);
- for (int i=0;i<directives.size();i++){
- if (directives.get(i)==this){
- return i;
- }
- }
- return 0;
- }
-
- public void addValue(String val){
+
+ public String getText() {
+ StringBuilder builder = new StringBuilder();
+ builder.append(name + " ");
+ for (String temp : values) {
+ builder.append(temp + " ");
+ }
+ builder.deleteCharAt(builder.length() - 1);
+ if (isNested)
+ builder.append(">");
+
+ return builder.toString();
+ }
+
+ public int getSeq() {
+ List<ApacheDirective> directives = parentNode.getChildByName(name);
+ for (int i = 0; i < directives.size(); i++) {
+ if (directives.get(i) == this) {
+ return i;
+ }
+ }
+ return 0;
+ }
+
+ public void addValue(String val) {
values.add(val);
}
-
+
@Override
public ApacheDirective clone() {
try {
ApacheDirective copy = (ApacheDirective) super.clone();
-
+
List<ApacheDirective> newChildNodes = new ArrayList<ApacheDirective>(childNodes.size());
- for(ApacheDirective child : childNodes) {
+ for (ApacheDirective child : childNodes) {
ApacheDirective childCopy = child.clone();
childCopy.parentNode = copy;
newChildNodes.add(childCopy);
}
copy.childNodes = newChildNodes;
-
+
return copy;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("ApacheDirective not cloneable even though it is declared as such.", e);
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveStack.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveStack.java
index 503a1cb..c301c54 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveStack.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveStack.java
@@ -6,34 +6,34 @@ import java.util.List;
public class ApacheDirectiveStack {
protected List<ApacheDirective> stack;
-
- public ApacheDirectiveStack(){
- stack= new ArrayList<ApacheDirective>();
+
+ public ApacheDirectiveStack() {
+ stack = new ArrayList<ApacheDirective>();
}
-
- public void addDirective(ApacheDirective dir){
+
+ public void addDirective(ApacheDirective dir) {
stack.add(dir);
}
-
- public ApacheDirective getLastDirective(){
- return stack.get(stack.size()-1);
+
+ public ApacheDirective getLastDirective() {
+ return stack.get(stack.size() - 1);
}
-
- public void removeLastDirective(){
- stack.remove(stack.size()-1);
+
+ public void removeLastDirective() {
+ stack.remove(stack.size() - 1);
}
-
- public ApacheDirectiveStack copy(){
+
+ public ApacheDirectiveStack copy() {
ApacheDirectiveStack st = new ApacheDirectiveStack();
- for (ApacheDirective dir : stack){
+ for (ApacheDirective dir : stack) {
st.addDirective(dir);
}
-
+
return st;
}
-
- public boolean isEmpty(){
- if (stack.size()==0)
+
+ public boolean isEmpty() {
+ if (stack.size() == 0)
return true;
else
return false;
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveTree.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveTree.java
index 9e0ad8b..9d66990 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveTree.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheDirectiveTree.java
@@ -6,10 +6,10 @@ import java.util.List;
public class ApacheDirectiveTree implements Cloneable {
private ApacheDirective rootNode;
-
- public ApacheDirectiveTree(){
- rootNode = new ApacheDirective();
- rootNode.setRootNode(true);
+
+ public ApacheDirectiveTree() {
+ rootNode = new ApacheDirective();
+ rootNode.setRootNode(true);
}
public ApacheDirective getRootNode() {
@@ -19,54 +19,54 @@ public class ApacheDirectiveTree implements Cloneable {
public void setRootNode(ApacheDirective rootNode) {
this.rootNode = rootNode;
}
-
- public List<ApacheDirective> search(ApacheDirective nd,String name){
- return parseExpr(nd,name);
+
+ public List<ApacheDirective> search(ApacheDirective nd, String name) {
+ return parseExpr(nd, name);
}
-
- public List<ApacheDirective> search(String name){
+
+ public List<ApacheDirective> search(String name) {
if (name.startsWith("/"))
- return parseExpr(rootNode,name.substring(1));
+ return parseExpr(rootNode, name.substring(1));
else
- return parseExpr(rootNode,name);
+ return parseExpr(rootNode, name);
}
-
- private List<ApacheDirective> parseExpr(ApacheDirective nd, String expr) {
+
+ private List<ApacheDirective> parseExpr(ApacheDirective nd, String expr) {
int index = expr.indexOf("/");
String name;
-
- if (index ==-1)
+
+ if (index == -1)
name = expr;
else
- name = expr.substring(0,index);
-
+ name = expr.substring(0, index);
+
List<ApacheDirective> nds = new ArrayList<ApacheDirective>();
-
- for (ApacheDirective dir : nd.getChildByName(name)){
- if (index ==-1)
+
+ for (ApacheDirective dir : nd.getChildByName(name)) {
+ if (index == -1)
nds.add(dir);
- else{
- List<ApacheDirective> tempNodes = parseExpr(dir, expr.substring(index+1));
- if (tempNodes != null)
- nds.addAll(tempNodes);
+ else {
+ List<ApacheDirective> tempNodes = parseExpr(dir, expr.substring(index + 1));
+ if (tempNodes != null)
+ nds.addAll(tempNodes);
}
}
-
+
return nds;
}
-
- public ApacheDirective createNode(ApacheDirective parentNode,String name){
- ApacheDirective dir = new ApacheDirective(name);
- dir.setParentNode(parentNode);
- parentNode.addChildDirective(dir);
- return dir;
+
+ public ApacheDirective createNode(ApacheDirective parentNode, String name) {
+ ApacheDirective dir = new ApacheDirective(name);
+ dir.setParentNode(parentNode);
+ parentNode.addChildDirective(dir);
+ return dir;
}
-
+
@Override
public ApacheDirectiveTree clone() {
ApacheDirectiveTree copy = new ApacheDirectiveTree();
copy.rootNode = rootNode.clone();
-
+
return copy;
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParser.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParser.java
index a8cb88d..99d08af 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParser.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParser.java
@@ -1,8 +1,10 @@
package org.rhq.plugins.apache.parser;
public interface ApacheParser {
-
+
public void addDirective(ApacheDirective directive) throws Exception;
+
public void startNestedDirective(ApacheDirective directive);
- public void endNestedDirective(ApacheDirective directive);
+
+ public void endNestedDirective(ApacheDirective directive);
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserException.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserException.java
index 4f62dba..3d51724 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserException.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserException.java
@@ -1,6 +1,5 @@
package org.rhq.plugins.apache.parser;
-
public class ApacheParserException extends RuntimeException {
private static final long serialVersionUID = 1L;
@@ -34,5 +33,4 @@ public class ApacheParserException extends RuntimeException {
super(cause);
}
-
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserImpl.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserImpl.java
index bba00bf..b07d2ab 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserImpl.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/parser/ApacheParserImpl.java
@@ -38,19 +38,20 @@ public class ApacheParserImpl implements ApacheParser {
private ApacheDirectiveStack stack;
private String serverRootPath;
private RuntimeApacheConfiguration.NodeInspector nodeInspector;
-
+
/**
*
* @param tree the tree that this parser will fill in
* @param initialServerRootPath the initial server root path as detected by other means
* @param nodeInspector the node inspector to determine the runtime configuration or null, if full configuration tree is needed
*/
- public ApacheParserImpl(ApacheDirectiveTree tree, String initialServerRootPath, RuntimeApacheConfiguration.NodeInspector nodeInspector) {
+ public ApacheParserImpl(ApacheDirectiveTree tree, String initialServerRootPath,
+ RuntimeApacheConfiguration.NodeInspector nodeInspector) {
stack = new ApacheDirectiveStack();
this.serverRootPath = initialServerRootPath;
this.tree = tree;
stack.addDirective(this.tree.getRootNode());
- this.nodeInspector = nodeInspector;
+ this.nodeInspector = nodeInspector;
}
public void addDirective(ApacheDirective directive) throws Exception {
@@ -58,7 +59,7 @@ public class ApacheParserImpl implements ApacheParser {
//we're ignoring until the end of an ignored nested directive
return;
}
-
+
if (directive.getName().equals(INCLUDE_DIRECTIVE)) {
List<File> files = getIncludeFiles(directive.getValuesAsString());
for (File fl : files) {
@@ -69,12 +70,12 @@ public class ApacheParserImpl implements ApacheParser {
} else if (directive.getName().equals(SERVER_ROOT_DIRECTIVE)) {
this.serverRootPath = AugeasNodeValueUtil.unescape(directive.getValuesAsString());
}
-
+
if (nodeInspector != null) {
//let the inspector process this directive in case it sees something of interest
nodeInspector.inspect(directive.getName(), directive.getValues(), directive.getValuesAsString());
}
-
+
directive.setParentNode(stack.getLastDirective());
stack.getLastDirective().addChildDirective(directive);
}
@@ -84,11 +85,12 @@ public class ApacheParserImpl implements ApacheParser {
}
public void startNestedDirective(ApacheDirective directive) {
- if (nodeInspector != null) {
+ if (nodeInspector != null) {
//now we have a node inspector so the tree construction is driven by it - we actually leave out the conditional
//directives and replace them with their contents (if they are to be applied of course)...
-
- RuntimeApacheConfiguration.NodeInspectionResult res = nodeInspector.inspect(directive.getName(), directive.getValues(), directive.getValuesAsString());
+
+ RuntimeApacheConfiguration.NodeInspectionResult res =
+ nodeInspector.inspect(directive.getName(), directive.getValues(), directive.getValuesAsString());
if (res == null || (res.nodeIsConditional && !res.shouldRecurseIntoConditionalNode)) {
//ok, this node should be ignored, mark that fact with a null parent
stack.addDirective(null);
@@ -109,12 +111,12 @@ public class ApacheParserImpl implements ApacheParser {
stack.getLastDirective().addChildDirective(directive);
}
stack.addDirective(directive);
- }
+ }
} else {
//there is no node inspector, so we have no "guidance" on the tree construction.
//Just include all the nested structures so that a full configuration tree is built
//with all the directives.
-
+
//we might be inside an ignored nested directive, so leave all the weaving stuff
//out in that case...
if (stack.getLastDirective() != null) {
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ApacheBinaryInfo.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ApacheBinaryInfo.java
index 724fc19..35f4dc3 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ApacheBinaryInfo.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ApacheBinaryInfo.java
@@ -64,9 +64,8 @@ public class ApacheBinaryInfo {
private long lastModified = 0;
private Set<String> compiledInModules = new HashSet<String>();
private Set<String> compiledInDefines = new HashSet<String>();
-
- protected ApacheBinaryInfo(@NotNull
- String binaryPath) {
+
+ protected ApacheBinaryInfo(@NotNull String binaryPath) {
this.binaryPath = binaryPath;
}
@@ -138,7 +137,7 @@ public class ApacheBinaryInfo {
try {
compiledInDefines.clear();
-
+
ProcessExecution processExecution = new ProcessExecution(binaryPath);
processExecution.setArguments(new String[] { "-V" });
processExecution.setWaitForCompletion(10000L);
@@ -176,7 +175,7 @@ public class ApacheBinaryInfo {
if (equalsIdx >= 0) {
define = define.substring(0, equalsIdx);
}
-
+
compiledInDefines.add(define);
}
}
@@ -192,14 +191,14 @@ public class ApacheBinaryInfo {
}
}
}
-
+
private void getCompiledInModules(String binaryPath, SystemInfo systemInfo) {
BufferedReader is = null;
try {
-
+
compiledInModules.clear();
-
+
ProcessExecution processExecution = new ProcessExecution(binaryPath);
processExecution.setArguments(new String[] { "-l" });
processExecution.setWaitForCompletion(10000L);
@@ -218,7 +217,7 @@ public class ApacheBinaryInfo {
firstLine = false;
continue;
}
-
+
compiledInModules.add(line.trim());
}
} catch (Throwable t) {
@@ -248,7 +247,7 @@ public class ApacheBinaryInfo {
getVersionCommandInfo(binaryPath, systemInfo);
getCompiledInModules(binaryPath, systemInfo);
-
+
File libHttpd = getHttpdSharedLibrary(binaryFile);
this.version = findVersion((libHttpd != null) ? libHttpd.getPath() : this.binaryPath);
@@ -322,8 +321,8 @@ public class ApacheBinaryInfo {
@Override
public String toString() {
- String info = "version=" + this.version + ", root=" + this.root + ", binary=" + this.binaryPath + ", ctl="
- + this.ctl;
+ String info =
+ "version=" + this.version + ", root=" + this.root + ", binary=" + this.binaryPath + ", ctl=" + this.ctl;
if (this.mpm != null) {
info += ", mpm=" + this.mpm;
@@ -373,12 +372,12 @@ public class ApacheBinaryInfo {
private static boolean isUnix() {
return File.separatorChar == '/';
}
-
+
public Set<String> getCompiledInModules() {
return compiledInModules;
}
-
+
public Set<String> getCompiledInDefines() {
return compiledInDefines;
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
index 077d263..f9459a3 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeSearch.java
@@ -6,8 +6,8 @@ import java.util.List;
import org.rhq.augeas.node.AugeasNode;
public class AugeasNodeSearch {
- public static String [] NESTED_DIRECTIVES = {"<IfModule","<Directive","<VirtualHost","<Files"};
-
+ public static String[] NESTED_DIRECTIVES = { "<IfModule", "<Directive", "<VirtualHost", "<Files" };
+
/**
* Searches for all nodes in parent nodes's subtree which matches specified criteria.
*
@@ -16,81 +16,81 @@ public class AugeasNodeSearch {
* @param startNode
* @return
*/
- public static List<AugeasNode> searchNode(String [] parentNodeNames,String nodeName,AugeasNode startNode){
- List<AugeasNode> nodes = new ArrayList<AugeasNode>();
- search(nodes,parentNodeNames,startNode,nodeName);
- return nodes;
+ public static List<AugeasNode> searchNode(String[] parentNodeNames, String nodeName, AugeasNode startNode) {
+ List<AugeasNode> nodes = new ArrayList<AugeasNode>();
+ search(nodes, parentNodeNames, startNode, nodeName);
+ return nodes;
}
-
- private static void search(List<AugeasNode>nodes,String [] parentNodeNames,AugeasNode node,String name){
-
+
+ private static void search(List<AugeasNode> nodes, String[] parentNodeNames, AugeasNode node, String name) {
+
nodes.addAll(node.getChildByLabel(name));
-
- for (String parentNodeName : parentNodeNames){
- List<AugeasNode> nds = node.getChildByLabel(parentNodeName);
- for (AugeasNode tempNode : nds){
- search(nodes,parentNodeNames,tempNode, name);
- }
- }
+
+ for (String parentNodeName : parentNodeNames) {
+ List<AugeasNode> nds = node.getChildByLabel(parentNodeName);
+ for (AugeasNode tempNode : nds) {
+ search(nodes, parentNodeNames, tempNode, name);
+ }
+ }
}
-
- public static List<AugeasNode> getNodeByParentParams(AugeasNode parentNode,String nodeName,List<String> nodeParams){
-
+
+ public static List<AugeasNode>
+ getNodeByParentParams(AugeasNode parentNode, String nodeName, List<String> nodeParams) {
+
List<AugeasNode> searchedNodes = AugeasNodeSearch.searchNode(NESTED_DIRECTIVES, nodeName, parentNode);
List<AugeasNode> results = new ArrayList<AugeasNode>();
-
- for (AugeasNode node : searchedNodes){
+
+ for (AugeasNode node : searchedNodes) {
AugeasNode tempNode = node;
boolean match = true;
- int i =0;
-
- while (match && i<nodeParams.size() && tempNode!=parentNode){
- List<AugeasNode> childNodes = tempNode.getChildByLabel("param");
- if (childNodes.size()>0){
- if (!nodeParams.get(i).equals(childNodes.get(0).getValue()))
- match = false;
- }else
- match = false;
- i=i+1;
- tempNode = tempNode.getParentNode();
- }
-
- if (match==true)
+ int i = 0;
+
+ while (match && i < nodeParams.size() && tempNode != parentNode) {
+ List<AugeasNode> childNodes = tempNode.getChildByLabel("param");
+ if (childNodes.size() > 0) {
+ if (!nodeParams.get(i).equals(childNodes.get(0).getValue()))
+ match = false;
+ } else
+ match = false;
+ i = i + 1;
+ tempNode = tempNode.getParentNode();
+ }
+
+ if (match == true)
results.add(node);
- }
-
+ }
+
return results;
}
-
- public static List<String> getParams(AugeasNode node,AugeasNode parentNode){
- List<String> res = new ArrayList<String>();
-
+
+ public static List<String> getParams(AugeasNode node, AugeasNode parentNode) {
+ List<String> res = new ArrayList<String>();
+
AugeasNode pNode = node;
- while (!pNode.equals(parentNode))
- {
+ while (!pNode.equals(parentNode)) {
List<AugeasNode> paramNodes = pNode.getChildByLabel("param");
- for (AugeasNode param : paramNodes){
+ for (AugeasNode param : paramNodes) {
res.add(param.getValue());
- }
+ }
pNode = pNode.getParentNode();
- }
+ }
return res;
- }
+ }
/**
* Returns all params of node as one string.
* @param nd
* @return
*/
- public static String getNodeParamString(AugeasNode nd){
+ public static String getNodeParamString(AugeasNode nd) {
List<AugeasNode> childNodes = nd.getChildByLabel("param");
StringBuilder str = new StringBuilder();
- for (AugeasNode paramNode : childNodes){
+ for (AugeasNode paramNode : childNodes) {
str.append(paramNode.getValue());
}
- return str.toString();
+ return str.toString();
}
-
+
/**
* If there is a more nodes which have the same node name and the same value of parameters than we need index
* for identification of Node.
@@ -98,13 +98,13 @@ public class AugeasNodeSearch {
* @param node
* @return
*/
- public static int getNodeIndex(AugeasNode node){
+ public static int getNodeIndex(AugeasNode node) {
List<AugeasNode> nodes = node.getParentNode().getChildByLabel(node.getLabel());
String param = getNodeParamString(node);
int index = 1;
-
- for(AugeasNode nd:nodes){
- if (getNodeParamString(nd).equals(param)){
+
+ for (AugeasNode nd : nodes) {
+ if (getNodeParamString(nd).equals(param)) {
if (node.equals(nd))
return index;
else
@@ -113,68 +113,67 @@ public class AugeasNodeSearch {
}
return index;
}
+
/**
* Returns the unique identifier of node. By this string we can identify node from parentNode's child nodes.
* @param node
* @return
*/
- public static String getNodeKeyFromParent(AugeasNode node){
-
+ public static String getNodeKeyFromParent(AugeasNode node) {
+
String param = getNodeParamString(node);
int index = getNodeIndex(node);
- return (node.getLabel()+"|"+param+"|"+String.valueOf(index)+";");
-
+ return (node.getLabel() + "|" + param + "|" + String.valueOf(index) + ";");
+
}
-
+
/**
* Returns the unique identifier of node. By this string we can identify the node in parent node's subtree.
* @param node
* @param parentNode
* @return
*/
- public static String getNodeKey(AugeasNode node,AugeasNode parentNode){
+ public static String getNodeKey(AugeasNode node, AugeasNode parentNode) {
AugeasNode pNode = node;
StringBuilder str = new StringBuilder();
- while (pNode!=null && !pNode.equals(parentNode))
- {
+ while (pNode != null && !pNode.equals(parentNode)) {
str.append(getNodeKeyFromParent(pNode));
pNode = pNode.getParentNode();
- }
+ }
return str.toString();
}
-
- public static AugeasNode findNodeById(AugeasNode parentNode,String params){
-
- AugeasNode tempNode=parentNode;
- String [] ids = params.split(";");
- for (int i=ids.length-1;i>=0;i--){
- tempNode = getNodeFromParentById(tempNode,ids[i]);
- }
+
+ public static AugeasNode findNodeById(AugeasNode parentNode, String params) {
+
+ AugeasNode tempNode = parentNode;
+ String[] ids = params.split(";");
+ for (int i = ids.length - 1; i >= 0; i--) {
+ tempNode = getNodeFromParentById(tempNode, ids[i]);
+ }
return tempNode;
}
-
- public static AugeasNode getNodeFromParentById(AugeasNode parentNode,String params){
- String nodeName;
- String parameters;
- int index=1;
-
- String [] paramsArray = params.split("\\|");
- if (paramsArray.length != 3)
- throw new RuntimeException("Node with id "+params +" was not found.");
-
- nodeName = paramsArray[0];
- parameters = paramsArray[1];
-
- index = Integer.valueOf(paramsArray[2]);
-
- for (AugeasNode nd : parentNode.getChildByLabel(nodeName)){
- String ndParam = getNodeKeyFromParent(nd);
- if (ndParam.equals(params+";")){
- return nd;
- }
- }
-
- throw new RuntimeException("Searched node with id " + params+ " was not found.");
+
+ public static AugeasNode getNodeFromParentById(AugeasNode parentNode, String params) {
+ String nodeName;
+ String parameters;
+ int index = 1;
+
+ String[] paramsArray = params.split("\\|");
+ if (paramsArray.length != 3)
+ throw new RuntimeException("Node with id " + params + " was not found.");
+
+ nodeName = paramsArray[0];
+ parameters = paramsArray[1];
+
+ index = Integer.valueOf(paramsArray[2]);
+
+ for (AugeasNode nd : parentNode.getChildByLabel(nodeName)) {
+ String ndParam = getNodeKeyFromParent(nd);
+ if (ndParam.equals(params + ";")) {
+ return nd;
+ }
+ }
+
+ throw new RuntimeException("Searched node with id " + params + " was not found.");
}
}
-
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeValueUtil.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeValueUtil.java
index 12655f8..b13c257 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeValueUtil.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/AugeasNodeValueUtil.java
@@ -31,9 +31,9 @@ package org.rhq.plugins.apache.util;
public class AugeasNodeValueUtil {
private AugeasNodeValueUtil() {
-
+
}
-
+
/**
* If the string is enclosed in double or single quotes, the
* value inside the quotes is returned with all the escaped characters
@@ -43,7 +43,8 @@ public class AugeasNodeValueUtil {
* @return
*/
public static String unescape(String value) {
- if (value == null) return value;
+ if (value == null)
+ return value;
if (value.startsWith("\"")) {
return value.substring(1, value.length() - 1).replaceAll("\\\"", "\"");
} else if (value.startsWith("'")) {
@@ -51,7 +52,7 @@ public class AugeasNodeValueUtil {
}
return value;
}
-
+
/**
* If the supplied value contains single or double quotes, the returned
* string is enclosed in quotes and the original qoutes "inside" are escaped.
@@ -65,7 +66,7 @@ public class AugeasNodeValueUtil {
} else if (value.indexOf('\'') >= 0) {
return "'" + value.replaceAll("'", "\\'") + "'";
}
-
+
return value;
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ConfigurationTimestamp.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ConfigurationTimestamp.java
index f7a8b5a..a112c47 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ConfigurationTimestamp.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/ConfigurationTimestamp.java
@@ -36,37 +36,40 @@ import java.util.Map;
public class ConfigurationTimestamp {
private Map<String, Long> lastModifiedTimes;
-
+
public ConfigurationTimestamp() {
lastModifiedTimes = new HashMap<String, Long>();
}
-
+
public ConfigurationTimestamp(List<File> files) {
this();
- for(File f : files) {
+ for (File f : files) {
lastModifiedTimes.put(f.getAbsolutePath(), f.lastModified());
}
}
-
+
@Override
public boolean equals(Object o) {
if (!(o instanceof ConfigurationTimestamp)) {
return false;
}
-
- ConfigurationTimestamp other = (ConfigurationTimestamp)o;
-
+
+ ConfigurationTimestamp other = (ConfigurationTimestamp) o;
+
Map<String, Long> oLastModified = other.lastModifiedTimes;
-
- if (lastModifiedTimes.size() != oLastModified.size()) return false;
-
- for(Map.Entry<String, Long> entry : lastModifiedTimes.entrySet()) {
+
+ if (lastModifiedTimes.size() != oLastModified.size())
+ return false;
+
+ for (Map.Entry<String, Long> entry : lastModifiedTimes.entrySet()) {
Long otherModified = oLastModified.get(entry.getKey());
- if (otherModified == null) return false;
-
- if (!entry.getValue().equals(otherModified)) return false;
+ if (otherModified == null)
+ return false;
+
+ if (!entry.getValue().equals(otherModified))
+ return false;
}
-
+
return true;
}
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdAddressUtility.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdAddressUtility.java
index 874d4e3..e37f968 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdAddressUtility.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdAddressUtility.java
@@ -41,7 +41,7 @@ import org.rhq.plugins.apache.parser.ApacheDirectiveTree;
public enum HttpdAddressUtility {
APACHE_1_3 {
-
+
public List<Address> getAllMainServerAddresses(ApacheDirectiveTree ag, boolean substituteWildcards) {
try {
List<ApacheDirective> ports = ag.search("/Port");
@@ -50,41 +50,41 @@ public enum HttpdAddressUtility {
String port = "80"; //this is the default in apache 1.3
String bindAddress = null;
-
+
List<Address> addresses = new ArrayList<Address>();
-
+
if (ports.size() > 0) {
- List<String>values = ports.get(0).getValues();
- if (values.size()>0)
- port = values.get(0);
+ List<String> values = ports.get(0).getValues();
+ if (values.size() > 0)
+ port = values.get(0);
}
-
+
if (bindAddresses.size() > 0) {
- List<String>values = bindAddresses.get(0).getValues();
- if (values.size()>0)
- bindAddress = values.get(0);
+ List<String> values = bindAddresses.get(0).getValues();
+ if (values.size() > 0)
+ bindAddress = values.get(0);
}
-
+
//listen directives take precedence over port/bindaddress combo
if (listens.size() > 0) {
- for(ApacheDirective l : listens) {
+ for (ApacheDirective l : listens) {
addresses.add(parseListen(l.getValues().get(0)));
}
} else {
addresses.add(new Address(bindAddress, Integer.parseInt(port)));
}
-
+
for (Address address : addresses) {
-
+
if (!address.isPortDefined()) {
address.port = 80;
}
-
+
if (substituteWildcards) {
substituteWildcards(ag, address);
}
}
-
+
return addresses;
} catch (Exception e) {
log.warn("Failed to obtain main server address.", e);
@@ -94,21 +94,21 @@ public enum HttpdAddressUtility {
}
},
APACHE_2_x {
-
+
public List<Address> getAllMainServerAddresses(ApacheDirectiveTree ag, boolean substituteWildcards) {
try {
List<Address> ret = new ArrayList<Address>();
-
- for(ApacheDirective n : ag.search("/Listen")) {
+
+ for (ApacheDirective n : ag.search("/Listen")) {
Address addr = parseListen(n.getValues().get(0));
-
+
if (substituteWildcards) {
substituteWildcards(ag, addr);
}
-
+
ret.add(addr);
}
-
+
return ret;
} catch (Exception e) {
log.warn("Failed to obtain main server address.", e);
@@ -122,21 +122,21 @@ public enum HttpdAddressUtility {
public static final String BOGUS_HOST_WITHOUT_FORWARD_DNS = "bogus_host_without_forward_dns";
public static final String BOGUS_HOST_WITHOUT_REVERSE_DNS = "bogus_host_without_reverse_dns";
-
+
public static HttpdAddressUtility get(String version) {
return version.startsWith("1.") ? APACHE_1_3 : APACHE_2_x;
}
-
+
public static class Address {
public String host;
public int port = -1;
public String scheme = "http";
-
+
public static final String WILDCARD = "*";
public static final String DEFAULT_HOST = "_default_";
public static final int PORT_WILDCARD_VALUE = 0;
public static final int NO_PORT_SPECIFIED_VALUE = -1;
-
+
public Address(String host, int port) {
this.host = host;
this.port = port;
@@ -146,6 +146,7 @@ public enum HttpdAddressUtility {
this(host, port);
this.scheme = scheme;
}
+
/**
* A simple parser of the provided address into host and port
* sections.
@@ -175,7 +176,7 @@ public enum HttpdAddressUtility {
scheme = address.substring(0, schemeSpecIdx);
address = address.substring(schemeSpecIdx + "://".length());
}
-
+
int lastColonIdx = address.lastIndexOf(':');
if (lastColonIdx == -1) {
return new Address(scheme, address, NO_PORT_SPECIFIED_VALUE);
@@ -184,14 +185,14 @@ public enum HttpdAddressUtility {
if (lastColonIdx > lastRightBracketPos) {
String host = address.substring(0, lastColonIdx);
String portSpec = address.substring(lastColonIdx + 1);
-
+
int port = NO_PORT_SPECIFIED_VALUE;
if (WILDCARD.equals(portSpec)) {
port = PORT_WILDCARD_VALUE;
} else {
port = Integer.parseInt(portSpec);
}
-
+
return new Address(scheme, host, port);
} else {
//this is an IP6 address without a port spec
@@ -199,23 +200,23 @@ public enum HttpdAddressUtility {
}
}
}
-
+
public boolean isPortWildcard() {
return port == PORT_WILDCARD_VALUE;
}
-
+
public boolean isPortDefined() {
return port != NO_PORT_SPECIFIED_VALUE;
}
-
+
public boolean isHostWildcard() {
return WILDCARD.equals(host);
}
-
+
public boolean isHostDefault() {
return DEFAULT_HOST.equals(host);
}
-
+
@Override
public int hashCode() {
int hash = port;
@@ -233,7 +234,7 @@ public enum HttpdAddressUtility {
return safeEquals(host, o.host) && this.port == o.port;
}
-
+
/**
* This differs from equals in the way that it considers wildcard values:
* <ul>
@@ -252,33 +253,33 @@ public enum HttpdAddressUtility {
if (matchSchemes && !safeEquals(scheme, other.scheme)) {
return false;
}
-
+
if (!WILDCARD.equals(host) && !WILDCARD.equals(other.host) && !safeEquals(host, other.host)) {
return false;
}
-
+
if (PORT_WILDCARD_VALUE != port && PORT_WILDCARD_VALUE != other.port && port != other.port) {
return false;
}
-
+
return true;
}
-
+
@Override
public String toString() {
return toString(true, true);
}
-
+
public String toString(boolean includeScheme, boolean interpretWildcardPort) {
StringBuilder bld = new StringBuilder();
-
+
if (includeScheme && scheme != null) {
bld.append(scheme).append("://");
}
if (host != null) {
bld.append(host);
-
+
if (port != NO_PORT_SPECIFIED_VALUE) {
bld.append(":");
}
@@ -291,10 +292,10 @@ public enum HttpdAddressUtility {
bld.append(port);
}
}
-
+
return bld.toString();
}
-
+
private static boolean safeEquals(Object a, Object b) {
return a == null ? b == null : a.equals(b);
}
@@ -308,7 +309,7 @@ public enum HttpdAddressUtility {
* @return the addresses or null on failure
*/
public abstract List<Address> getAllMainServerAddresses(ApacheDirectiveTree ag, boolean substituteWildcards);
-
+
/**
* This just constructs a first available address under which the server or one of its virtual hosts can be reached.
*
@@ -320,11 +321,11 @@ public enum HttpdAddressUtility {
*/
public Address getMainServerSampleAddress(ApacheDirectiveTree ag, String limitToHost, int limitToPort) {
List<Address> addressesToMatch = getAllMainServerAddresses(ag, false);
-
+
if (addressesToMatch == null) {
return null;
}
-
+
for (Address address : addressesToMatch) {
if (isAddressConforming(address, limitToHost, limitToPort, false)) {
substituteWildcards(ag, address);
@@ -334,7 +335,7 @@ public enum HttpdAddressUtility {
return address;
}
}
-
+
return null;
}
@@ -348,7 +349,8 @@ public enum HttpdAddressUtility {
* from the code generating the legacy resource keys during vhost upgrade
* @return the address on which the virtual host can be accessed or null on error
*/
- public Address getVirtualHostSampleAddress(ApacheDirectiveTree ag, String virtualHost, String serverName, boolean legacyWildcardHostHandling) {
+ public Address getVirtualHostSampleAddress(ApacheDirectiveTree ag, String virtualHost, String serverName,
+ boolean legacyWildcardHostHandling) {
try {
Address addr = Address.parse(virtualHost);
if (addr.isHostDefault() || addr.isHostWildcard()) {
@@ -362,7 +364,7 @@ public enum HttpdAddressUtility {
return null;
addr.host = serverAddr.host;
}
-
+
if (serverName != null) {
updateWithServerName(addr, serverName);
}
@@ -373,10 +375,10 @@ public enum HttpdAddressUtility {
return null;
}
}
-
+
public Address getHttpdInternalMainServerAddressRepresentation(ApacheDirectiveTree runtimeConfig) {
Address ret = null;
-
+
List<ApacheDirective> serverNames = runtimeConfig.search("/ServerName");
if (serverNames.size() == 0) {
//no servername directive in the apache config
@@ -386,7 +388,7 @@ public enum HttpdAddressUtility {
} catch (UnknownHostException e) {
ret.host = "127.0.0.1";
}
-
+
ret.port = 0;
} else {
String serverName = serverNames.get(serverNames.size() - 1).getValuesAsString();
@@ -395,35 +397,36 @@ public enum HttpdAddressUtility {
ret.port = 0;
}
}
-
+
return ret;
}
-
- public Address getHttpdInternalVirtualHostAddressRepresentation(ApacheDirectiveTree runtimeConfig, String virtualHost, String serverName) {
+
+ public Address getHttpdInternalVirtualHostAddressRepresentation(ApacheDirectiveTree runtimeConfig,
+ String virtualHost, String serverName) {
Address ret = null;
-
+
if (serverName != null) {
ret = Address.parse(serverName);
if (!ret.isPortDefined()) {
ret.port = 0;
}
-
+
//servername is taken literally and no reverse dns lookup is made
//if the servername host is an IP address. We're done here...
} else {
ret = Address.parse(virtualHost);
if (!ret.isPortDefined() || ret.isPortWildcard() || ret.isHostDefault() || ret.isHostWildcard()) {
Address mainAddress = getHttpdInternalMainServerAddressRepresentation(runtimeConfig);
-
+
if (!ret.isPortDefined() || ret.isPortWildcard()) {
ret.port = mainAddress.port;
}
-
+
if (ret.isHostDefault() || ret.isHostWildcard()) {
ret.host = mainAddress.host;
}
}
-
+
//if the vhost hostname is an IP address, a reverse dns lookup is attempted
//to get the actual hostname.
//the BOGUS* constants are what the apache actually uses to identify such
@@ -446,10 +449,10 @@ public enum HttpdAddressUtility {
ret.port = mainAddress.port;
}
}
-
+
return ret;
}
-
+
public static Address parseListen(String listenValue) {
Address ret = Address.parse(listenValue, null);
if (!ret.isPortDefined()) {
@@ -460,24 +463,24 @@ public enum HttpdAddressUtility {
}
ret.host = null;
}
-
+
return ret;
}
-
+
private static void substituteWildcards(ApacheDirectiveTree ag, Address address) {
if (address.isPortWildcard()) {
address.port = 80;
}
-
+
if (address.host == null || address.isHostDefault() || address.isHostWildcard()) {
Address localhost = getLocalhost(address.port);
address.host = localhost.host;
}
-
+
updateWithServerName(address, ag);
-
+
}
-
+
/**
* Checks that given address represents a possibly wildcarded limitingHost and limitingPort values.
*
@@ -489,21 +492,22 @@ public enum HttpdAddressUtility {
* If this flag is set to true, this method takes that into account.
* @return
*/
- public static boolean isAddressConforming(Address listen, String limitingHost, int limitingPort, boolean snmpModuleCompatibleMode) {
+ public static boolean isAddressConforming(Address listen, String limitingHost, int limitingPort,
+ boolean snmpModuleCompatibleMode) {
if (Address.DEFAULT_HOST.equals(limitingHost) || Address.WILDCARD.equals(limitingHost)) {
limitingHost = null;
}
-
+
boolean hostOk = limitingHost == null;
boolean portOk = limitingPort <= 0;
-
+
//listen.host == null means that server listens on all addresses
if (!hostOk && (listen.host == null || limitingHost.equals(listen.host))) {
hostOk = true;
}
-
+
int listenPort = listen.port;
-
+
//this stupid 80 = 0 rule is to conform with snmp module
//the problem is that snmp module represents both 80 and * port defs as 0,
//so whatever we do, we might mismatch the vhost. But there's no working around that
@@ -516,14 +520,14 @@ public enum HttpdAddressUtility {
listenPort = 0;
}
}
-
+
if (!portOk && limitingPort == listenPort) {
portOk = true;
}
-
+
return hostOk && portOk;
}
-
+
private static Address getLocalhost(int port) {
try {
return new Address(InetAddress.getLocalHost().getHostAddress(), port);
@@ -532,7 +536,7 @@ public enum HttpdAddressUtility {
return new Address("127.0.0.1", port);
}
}
-
+
private static void updateWithServerName(Address address, ApacheDirectiveTree config) {
//check if there is a ServerName directive
List<ApacheDirective> serverNameNodes = config.search("/ServerName");
@@ -545,13 +549,13 @@ public enum HttpdAddressUtility {
updateWithServerName(address, serverName);
}
}
-
+
private static void updateWithServerName(Address address, String serverName) {
//the configuration may be invalid and/or the hostname can be unresolvable.
//we try to match the address with the servername first by IP address
//but if that fails (i.e. the hostname couldn't be resolved to an IP)
//we try to simply match the hostnames themselves.
-
+
Address serverAddr = Address.parse(serverName);
String ipFromServerName = null;
String ipFromAddress = null;
@@ -568,7 +572,7 @@ public enum HttpdAddressUtility {
hostFromServerName = serverAddr.host;
lookupFailed = true;
}
-
+
try {
InetAddress addrFromAddress = InetAddress.getByName(address.host);
ipFromAddress = addrFromAddress.getHostAddress();
@@ -578,7 +582,7 @@ public enum HttpdAddressUtility {
hostFromAddress = address.host;
lookupFailed = true;
}
-
+
if (ipFromAddress.equals(ipFromServerName) || (lookupFailed && (hostFromAddress.equals(hostFromServerName)))) {
address.scheme = serverAddr.scheme;
address.host = serverAddr.host;
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdConfParser.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdConfParser.java
index 9f9bd98..37c9b2a 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdConfParser.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/HttpdConfParser.java
@@ -38,15 +38,12 @@ public class HttpdConfParser {
private final Log log = LogFactory.getLog(HttpdConfParser.class);
-
private Set<String> vhosts = new HashSet<String>();
private boolean modJkInstalled;
private String workerPropertiesFile;
private String uriWorkerLocation;
private String mainServer;
-
-
/**
* Parses the httpd.conf file located at confPath
* @param confPath The path to the httpd.conf file
@@ -60,53 +57,45 @@ public class HttpdConfParser {
return false;
}
- BufferedReader reader=null;
+ BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
String tmp;
- while ((line=reader.readLine())!=null) {
- line=line.trim();
+ while ((line = reader.readLine()) != null) {
+ line = line.trim();
tmp = getValueFrom2ndArg(line);
if (line.startsWith("LoadModule") && line.contains("jk_module")) {
- modJkInstalled=true;
- }
- else if (line.startsWith("JkWorkersFile")) {
- if (tmp!=null) {
+ modJkInstalled = true;
+ } else if (line.startsWith("JkWorkersFile")) {
+ if (tmp != null) {
workerPropertiesFile = tmp;
}
- }
- else if (line.startsWith("<VirtualHost")) {
- if (tmp!=null) {
+ } else if (line.startsWith("<VirtualHost")) {
+ if (tmp != null) {
vhosts.add(tmp);
}
- }
- else if (line.startsWith("JkMountFile")) {
- if (tmp!=null) {
+ } else if (line.startsWith("JkMountFile")) {
+ if (tmp != null) {
uriWorkerLocation = tmp;
}
- }
- else if (line.startsWith("JkMount") && !line.startsWith("JkMountFile")) {
+ } else if (line.startsWith("JkMount") && !line.startsWith("JkMountFile")) {
// TODO
- }
- else if (line.startsWith("Listen")) {
- if (tmp!=null) {
- mainServer=tmp;
+ } else if (line.startsWith("Listen")) {
+ if (tmp != null) {
+ mainServer = tmp;
}
}
}
- }
- catch (IOException ioe) {
+ } catch (IOException ioe) {
log.warn("Can't process " + confPath + " :" + ioe.getMessage());
return false;
- }
- finally {
- if (reader!=null)
+ } finally {
+ if (reader != null)
try {
reader.close();
- }
- catch (IOException e) {
+ } catch (IOException e) {
// Nothing we can do ...
}
}
@@ -123,13 +112,13 @@ public class HttpdConfParser {
@Nullable
private String getValueFrom2ndArg(String input) {
- if (input==null)
+ if (input == null)
return null;
String ret = null;
String[] tokens = input.split("\\s");
- if (tokens.length>1)
- ret=tokens[1];
+ if (tokens.length > 1)
+ ret = tokens[1];
return ret;
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/OsProcessUtility.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/OsProcessUtility.java
index cccb19d..c805b57 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/OsProcessUtility.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/OsProcessUtility.java
@@ -50,38 +50,38 @@ public abstract class OsProcessUtility {
public static File getProcExe(long pid, String name) {
SigarProxy sigar = SigarAccess.getSigar();
File argv0;
- try {
- String exe = sigar.getProcExe(pid).getName();
- // may be "" on Solaris
- if (exe.length() > 0) {
- return new File(exe);
- }
- } catch (SigarException e) {
- // most likely permission denied
+ try {
+ String exe = sigar.getProcExe(pid).getName();
+ // may be "" on Solaris
+ if (exe.length() > 0) {
+ return new File(exe);
}
+ } catch (SigarException e) {
+ // most likely permission denied
+ }
- argv0 = null;
- String[] args = getProcArgs(pid, sigar);
- if (args.length != 0) {
- // might not be an absolute path
- argv0 = new File(args[0]);
- if (argv0.exists() && argv0.isAbsolute()) {
- return argv0;
- }
+ argv0 = null;
+ String[] args = getProcArgs(pid, sigar);
+ if (args.length != 0) {
+ // might not be an absolute path
+ argv0 = new File(args[0]);
+ if (argv0.exists() && argv0.isAbsolute()) {
+ return argv0;
}
+ }
- List<String> modules = getProcModules(pid, sigar);
- if (modules.size() > 0) {
- if (name == null) {
- return new File(modules.get(0));
- }
- name = File.separator + name;
- for (String module : modules) {
- if (module.endsWith(name)) {
- return new File(module);
- }
+ List<String> modules = getProcModules(pid, sigar);
+ if (modules.size() > 0) {
+ if (name == null) {
+ return new File(modules.get(0));
+ }
+ name = File.separator + name;
+ for (String module : modules) {
+ if (module.endsWith(name)) {
+ return new File(module);
}
}
+ }
return argv0;
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/RuntimeApacheConfiguration.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/RuntimeApacheConfiguration.java
index f8a0bdb..bf81873 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/RuntimeApacheConfiguration.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/RuntimeApacheConfiguration.java
@@ -49,9 +49,11 @@ public class RuntimeApacheConfiguration {
private static final Log LOG = LogFactory.getLog(RuntimeApacheConfiguration.class);
private static final Set<String> LOGGED_UNKNOWN_MODULES = Collections.synchronizedSet(new HashSet<String>());
-
+
private enum ModuleLoadedState {
- LOADED, NOT_LOADED, UNKNOWN
+ LOADED,
+ NOT_LOADED,
+ UNKNOWN
}
private RuntimeApacheConfiguration() {
@@ -66,9 +68,9 @@ public class RuntimeApacheConfiguration {
*/
public static class NodeInspectionResult {
public boolean nodeIsConditional;
- public boolean shouldRecurseIntoConditionalNode;
+ public boolean shouldRecurseIntoConditionalNode;
}
-
+
/**
* Node inspector is used to determine how to proceed with the parsing of the configuration file.
*
@@ -77,11 +79,11 @@ public class RuntimeApacheConfiguration {
*/
public static class NodeInspector {
private TransformState state;
-
+
private NodeInspector(TransformState state) {
this.state = state;
}
-
+
/**
* Inspects a node.
*
@@ -92,7 +94,7 @@ public class RuntimeApacheConfiguration {
*/
public NodeInspectionResult inspect(String currentNodeName, List<String> allValues, String valueAsString) {
NodeInspectionResult result = new NodeInspectionResult();
-
+
result.shouldRecurseIntoConditionalNode = true;
if (currentNodeName.equalsIgnoreCase("LoadModule")) {
@@ -120,7 +122,8 @@ public class RuntimeApacheConfiguration {
LOG.debug("Encountered unknown module name in an IfModule directive: " + moduleFile);
} else {
LOG.warn("Encountered unknown module name in an IfModule directive: "
- + moduleFile + ". If you are using Apache 2.1 or later, you can try changing the module identifier from the source file to "
+ + moduleFile
+ + ". If you are using Apache 2.1 or later, you can try changing the module identifier from the source file to "
+ "the actual module name as used in the LoadModule directive to get rid of this warning.");
}
LOGGED_UNKNOWN_MODULES.add(moduleFile);
@@ -232,11 +235,11 @@ public class RuntimeApacheConfiguration {
} else {
result.nodeIsConditional = false;
}
-
+
return result;
}
}
-
+
/**
* This is a node visitor interface to be implemented by the users of the
* {@link RuntimeApacheConfiguration#walkRuntimeConfig(ApacheAugeasTree, ProcessInfo, ApacheBinaryInfo, Map)}
@@ -371,7 +374,7 @@ public class RuntimeApacheConfiguration {
public Map<String, String> moduleFiles;
public String httpdVersion;
public boolean suppressUnknownModuleWarnings;
-
+
public TransformState(ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo,
Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
defines = new HashSet<String>(httpdBinaryInfo.getCompiledInDefines());
@@ -418,16 +421,17 @@ public class RuntimeApacheConfiguration {
}
httpdVersion = httpdBinaryInfo.getVersion();
-
+
this.suppressUnknownModuleWarnings = suppressUnknownModuleWarnings;
}
}
- public static NodeInspector getNodeInspector(ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo, Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
- return new NodeInspector(new TransformState(httpdProcessInfo, httpdBinaryInfo,
- moduleNames, suppressUnknownModuleWarnings));
+ public static NodeInspector getNodeInspector(ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo,
+ Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
+ return new NodeInspector(new TransformState(httpdProcessInfo, httpdBinaryInfo, moduleNames,
+ suppressUnknownModuleWarnings));
}
-
+
/**
* Given the apache configuration and information about the parameters httpd was executed
* with this method provides the directive tree that corresponds to the actual
@@ -447,14 +451,15 @@ public class RuntimeApacheConfiguration {
public static ApacheDirectiveTree extract(ApacheDirectiveTree tree, ProcessInfo httpdProcessInfo,
ApacheBinaryInfo httpdBinaryInfo, Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
ApacheDirectiveTree ret = tree.clone();
- transform(new TransformingWalker(), ret.getRootNode(), getNodeInspector(httpdProcessInfo, httpdBinaryInfo,
- moduleNames, suppressUnknownModuleWarnings));
+ transform(new TransformingWalker(), ret.getRootNode(),
+ getNodeInspector(httpdProcessInfo, httpdBinaryInfo, moduleNames, suppressUnknownModuleWarnings));
return ret;
}
public static void walkRuntimeConfig(final NodeVisitor<ApacheDirective> visitor, ApacheDirectiveTree tree,
- ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo, Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
+ ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo, Map<String, String> moduleNames,
+ boolean suppressUnknownModuleWarnings) {
TreeWalker<ApacheDirective> walker = new TreeWalker<ApacheDirective>() {
public void visitConditionalNode(ApacheDirective node, boolean isSatisfied) {
visitor.visitConditionalNode(node, isSatisfied);
@@ -487,11 +492,13 @@ public class RuntimeApacheConfiguration {
}
};
- transform(walker, tree.getRootNode(), getNodeInspector(httpdProcessInfo, httpdBinaryInfo, moduleNames, suppressUnknownModuleWarnings));
+ transform(walker, tree.getRootNode(),
+ getNodeInspector(httpdProcessInfo, httpdBinaryInfo, moduleNames, suppressUnknownModuleWarnings));
}
public static void walkRuntimeConfig(final NodeVisitor<AugeasNode> visitor, AugeasTree tree,
- ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo, Map<String, String> moduleNames, boolean suppressUnknownModuleWarnings) {
+ ProcessInfo httpdProcessInfo, ApacheBinaryInfo httpdBinaryInfo, Map<String, String> moduleNames,
+ boolean suppressUnknownModuleWarnings) {
TreeWalker<AugeasNode> walker = new TreeWalker<AugeasNode>() {
public void visitConditionalNode(AugeasNode node, boolean isSatisfied) {
visitor.visitConditionalNode(node, isSatisfied);
@@ -534,7 +541,8 @@ public class RuntimeApacheConfiguration {
return node.getLabel();
}
};
- transform(walker, tree.getRootNode(), getNodeInspector(httpdProcessInfo, httpdBinaryInfo, moduleNames, suppressUnknownModuleWarnings));
+ transform(walker, tree.getRootNode(),
+ getNodeInspector(httpdProcessInfo, httpdBinaryInfo, moduleNames, suppressUnknownModuleWarnings));
}
private static <T> void transform(TreeWalker<T> walker, T parentNode, NodeInspector inspector) {
@@ -545,7 +553,8 @@ public class RuntimeApacheConfiguration {
walker.onBeforeChildrenScan(parentNode);
for (T node : walker.getChildren(parentNode)) {
- NodeInspectionResult result = inspector.inspect(walker.getName(node), walker.getValues(node), walker.getValue(node));
+ NodeInspectionResult result =
+ inspector.inspect(walker.getName(node), walker.getValues(node), walker.getValue(node));
if (result == null) {
continue;
}
@@ -590,8 +599,8 @@ public class RuntimeApacheConfiguration {
//the compiled in modules are being reported by apache using their source file
//and the on-demand loaded modules are identified by their
//module name - consistent, huh?
- boolean result = currentlyLoadedModules.contains(moduleIdentifier)
- || currentlyLoadedModules.contains(moduleName);
+ boolean result =
+ currentlyLoadedModules.contains(moduleIdentifier) || currentlyLoadedModules.contains(moduleName);
return result ? ModuleLoadedState.LOADED : ModuleLoadedState.NOT_LOADED;
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VHostSpec.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VHostSpec.java
index 62940c2..3ae5948 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VHostSpec.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VHostSpec.java
@@ -29,23 +29,23 @@ import org.rhq.plugins.apache.parser.ApacheDirectiveTree;
public class VHostSpec {
public String serverName;
public List<String> hosts;
-
+
public static List<VHostSpec> detect(ApacheDirectiveTree config) {
List<ApacheDirective> virtualHosts = config.search("/<VirtualHost");
-
+
List<VHostSpec> ret = new ArrayList<VHostSpec>(virtualHosts.size());
-
- for(ApacheDirective dir : virtualHosts) {
+
+ for (ApacheDirective dir : virtualHosts) {
ret.add(new VHostSpec(dir));
}
-
+
return ret;
}
-
+
public VHostSpec() {
-
+
}
-
+
public VHostSpec(ApacheDirective vhostDirective) {
hosts = new ArrayList<String>(vhostDirective.getValues());
@@ -55,40 +55,40 @@ public class VHostSpec {
serverName = serverNames.get(serverNames.size() - 1).getValuesAsString();
}
}
-
+
@Override
public String toString() {
return ApacheVirtualHostServiceDiscoveryComponent.createResourceKey(serverName, hosts);
}
-
+
@Override
public int hashCode() {
int ret = serverName != null ? serverName.hashCode() : 1;
- for(String host : hosts) {
+ for (String host : hosts) {
ret = 31 * ret * host.hashCode();
}
-
+
return ret;
}
-
+
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
-
+
if (!(o instanceof VHostSpec)) {
return false;
}
-
+
VHostSpec other = (VHostSpec) o;
-
+
boolean serverNameEqual = serverName == null ? other.serverName == null : serverName.equals(other.serverName);
-
+
if (!serverNameEqual) {
return false;
}
-
+
return hosts.equals(other.hosts);
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VirtualHostLegacyResourceKeyUtil.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VirtualHostLegacyResourceKeyUtil.java
index 3f6a15c..d5c09fc 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VirtualHostLegacyResourceKeyUtil.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/util/VirtualHostLegacyResourceKeyUtil.java
@@ -45,21 +45,23 @@ public class VirtualHostLegacyResourceKeyUtil {
private HttpdAddressUtility addressUtility;
private ApacheDirectiveTree runtimeConfig;
private ApacheServerComponent serverComponent;
-
+
public VirtualHostLegacyResourceKeyUtil(ApacheServerComponent serverComponent, ApacheDirectiveTree runtimeConfig) {
this.runtimeConfig = runtimeConfig;
this.addressUtility = serverComponent.getAddressUtility();
this.serverComponent = serverComponent;
-
+
vhosts = VHostSpec.detect(runtimeConfig);
snmpLikeReport = new ArrayList<HttpdAddressUtility.Address>();
snmpLikeReport.add(addressUtility.getHttpdInternalMainServerAddressRepresentation(runtimeConfig));
- for(VHostSpec vhost : vhosts) {
- HttpdAddressUtility.Address snmpRecord = addressUtility.getHttpdInternalVirtualHostAddressRepresentation(runtimeConfig, vhost.hosts.get(0), vhost.serverName);
+ for (VHostSpec vhost : vhosts) {
+ HttpdAddressUtility.Address snmpRecord =
+ addressUtility.getHttpdInternalVirtualHostAddressRepresentation(runtimeConfig, vhost.hosts.get(0),
+ vhost.serverName);
snmpLikeReport.add(snmpRecord);
}
}
-
+
/**
* This creates a list of possible resource keys for the main server.
* <p>
@@ -72,11 +74,11 @@ public class VirtualHostLegacyResourceKeyUtil {
*/
public Set<String> getLegacyMainServerResourceKeys() {
Set<String> ret = new HashSet<String>();
-
+
String key = getRHQ3NonSNMPLegacyMainServerResourceKey();
-
+
ret.add(key);
-
+
String snmpKey = getRHQ3SNMPLikeResourceKey(key);
if (snmpKey != null) {
@@ -84,10 +86,10 @@ public class VirtualHostLegacyResourceKeyUtil {
}
ret.add(addressUtility.getHttpdInternalMainServerAddressRepresentation(runtimeConfig).toString(false, false));
-
+
return ret;
}
-
+
/**
* A resource key for the main vhost that would be returned by the RHQ 3 codebase
* if SNMP wasn't enabled during discovery.
@@ -103,9 +105,9 @@ public class VirtualHostLegacyResourceKeyUtil {
*/
public String getRHQ3NonSNMPLegacyMainServerResourceKey() {
String mainServerUrl = serverComponent.getServerUrl();
-
+
String key = null;
-
+
if (mainServerUrl != null && !"null".equals(mainServerUrl)) {
try {
URI mainServerUri = new URI(mainServerUrl);
@@ -114,7 +116,7 @@ public class VirtualHostLegacyResourceKeyUtil {
if (port == -1) {
port = 80;
}
-
+
key = host + ":" + port;
} catch (URISyntaxException e) {
//hmm.. strange
@@ -122,10 +124,10 @@ public class VirtualHostLegacyResourceKeyUtil {
} else {
key = ApacheVirtualHostServiceComponent.MAIN_SERVER_RESOURCE_KEY;
}
-
+
return key;
}
-
+
/**
* Returns a list of possible resource keys that the RHQ 3 code could generate for the specified
* vhost.
@@ -140,20 +142,22 @@ public class VirtualHostLegacyResourceKeyUtil {
String key = getRHQ3NonSNMPLegacyVirtualHostResourceKey(vhost);
Set<String> ret = new HashSet<String>();
-
+
ret.add(key);
-
+
String snmpKey = getRHQ3SNMPLikeResourceKey(key);
if (snmpKey != null) {
ret.add(snmpKey);
}
- String snmpKeyFromRhq1 = addressUtility.getHttpdInternalVirtualHostAddressRepresentation(runtimeConfig, vhost.hosts.get(0), vhost.serverName).toString(false, false);
+ String snmpKeyFromRhq1 =
+ addressUtility.getHttpdInternalVirtualHostAddressRepresentation(runtimeConfig, vhost.hosts.get(0),
+ vhost.serverName).toString(false, false);
ret.add(snmpKeyFromRhq1);
-
+
return ret;
}
-
+
/**
* A resource key for given vhost that would be returned by RHQ 3 if SNMP wasn't enabled during
* discovery.
@@ -168,17 +172,17 @@ public class VirtualHostLegacyResourceKeyUtil {
HttpdAddressUtility.Address serverAddr = HttpdAddressUtility.Address.parse(vhost.serverName);
hostAddr.host = serverAddr.host;
}
-
+
//the SNMP module seems to resolve the IPs to hostnames.
try {
InetAddress hostName = InetAddress.getByName(hostAddr.host);
hostAddr.host = hostName.getHostName();
} catch (UnknownHostException e) {
- }
-
+ }
+
return hostAddr.host + ":" + hostAddr.port;
}
-
+
/**
* Returns an "SNMP" resource key that would have been resolved out of the non-snmp resource key
* by the RHQ 3 code-base. Note that the returned key actually isn't what SNMP module would
@@ -189,7 +193,7 @@ public class VirtualHostLegacyResourceKeyUtil {
*/
public String getRHQ3SNMPLikeResourceKey(String nonSnmpResourceKey) {
int idx = getMatchingWwwServiceIndex(nonSnmpResourceKey);
-
+
if (idx < 0) {
return null;
} else {
@@ -219,18 +223,20 @@ public class VirtualHostLegacyResourceKeyUtil {
vhostAddressStrings = resourceKey.substring(pipeIdx + 1).split(" ");
//convert the vhost addresses into fully qualified ip/port addresses
- List<HttpdAddressUtility.Address> vhostAddresses = new ArrayList<HttpdAddressUtility.Address>(
- vhostAddressStrings.length);
+ List<HttpdAddressUtility.Address> vhostAddresses =
+ new ArrayList<HttpdAddressUtility.Address>(vhostAddressStrings.length);
- if (vhostAddressStrings.length == 1 && ApacheVirtualHostServiceComponent.MAIN_SERVER_RESOURCE_KEY.equals(vhostAddressStrings[0])) {
+ if (vhostAddressStrings.length == 1
+ && ApacheVirtualHostServiceComponent.MAIN_SERVER_RESOURCE_KEY.equals(vhostAddressStrings[0])) {
HttpdAddressUtility.Address serverAddr = addressUtility.getMainServerSampleAddress(runtimeConfig, null, 0);
if (serverAddr != null) {
vhostAddresses.add(serverAddr);
}
} else {
for (int i = 0; i < vhostAddressStrings.length; ++i) {
- HttpdAddressUtility.Address vhostAddr = addressUtility.getVirtualHostSampleAddress(runtimeConfig, vhostAddressStrings[i],
- vhostServerName, true);
+ HttpdAddressUtility.Address vhostAddr =
+ addressUtility.getVirtualHostSampleAddress(runtimeConfig, vhostAddressStrings[i], vhostServerName,
+ true);
if (vhostAddr != null) {
vhostAddresses.add(vhostAddr);
} else {
@@ -251,67 +257,69 @@ public class VirtualHostLegacyResourceKeyUtil {
//vhost can actually be represented as. A vhost is represented by at most 1 hostname (i.e. ServerName)
//and possibly multiple IP addresses.
int bestMatchRate = 0;
-
+
int idx = 0;
- for(HttpdAddressUtility.Address snmpAddress : snmpLikeReport) {
-
+ for (HttpdAddressUtility.Address snmpAddress : snmpLikeReport) {
+
int matchRate = matchRate(vhostAddresses, snmpAddress);
if (matchRate > bestMatchRate) {
ret = idx;
bestMatchRate = matchRate;
}
-
+
++idx;
}
-
+
return ret;
}
-
- private static int matchRate(List<HttpdAddressUtility.Address> addresses, HttpdAddressUtility.Address addressToCheck) {
- for(HttpdAddressUtility.Address a : addresses) {
+
+ private static int
+ matchRate(List<HttpdAddressUtility.Address> addresses, HttpdAddressUtility.Address addressToCheck) {
+ for (HttpdAddressUtility.Address a : addresses) {
if (HttpdAddressUtility.isAddressConforming(addressToCheck, a.host, a.port, true)) {
return 3;
}
}
-
+
//try to get the IP of the address to check
InetAddress[] ipAddresses;
try {
ipAddresses = InetAddress.getAllByName(addressToCheck.host);
- for(InetAddress ip : ipAddresses) {
- HttpdAddressUtility.Address newCheck = new HttpdAddressUtility.Address(ip.getHostAddress(), addressToCheck.port);
-
- for(HttpdAddressUtility.Address a : addresses) {
+ for (InetAddress ip : ipAddresses) {
+ HttpdAddressUtility.Address newCheck =
+ new HttpdAddressUtility.Address(ip.getHostAddress(), addressToCheck.port);
+
+ for (HttpdAddressUtility.Address a : addresses) {
if (HttpdAddressUtility.isAddressConforming(newCheck, a.host, a.port, true)) {
return 2;
}
}
- }
+ }
} catch (UnknownHostException e) {
return 0;
}
-
+
//because of the lack of documentation on the SNMP module, we assumed
//some wrong things in the past.. this is one of them...
int addressPort = addressToCheck.port;
if (addressPort == 80) {
addressPort = 0;
}
-
+
//ok, try the hardest...
- for(HttpdAddressUtility.Address listAddress: addresses) {
+ for (HttpdAddressUtility.Address listAddress : addresses) {
int listPort = listAddress.port;
if (listPort == 80) {
listPort = 0;
}
-
+
InetAddress[] listAddresses;
try {
listAddresses = InetAddress.getAllByName(listAddress.host);
} catch (UnknownHostException e) {
return 0;
}
-
+
for (InetAddress listInetAddr : listAddresses) {
for (InetAddress ip : ipAddresses) {
if (ip.equals(listInetAddr) && addressPort == listPort) {
@@ -320,7 +328,7 @@ public class VirtualHostLegacyResourceKeyUtil {
}
}
}
-
+
return 0;
- }
+ }
}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/MIBLookupException.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/MIBLookupException.java
index 49dc575..276e388 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/MIBLookupException.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/MIBLookupException.java
@@ -26,4 +26,4 @@ public class MIBLookupException extends SNMPException {
public MIBLookupException(String msg, Throwable t) {
super(msg, t);
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPCacheObject.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPCacheObject.java
index c65f463..0d46c9c 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPCacheObject.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPCacheObject.java
@@ -22,4 +22,4 @@ class SNMPCacheObject {
int expire = SNMPSessionCache.EXPIRE_DEFAULT;
long timestamp = 0;
Object value = null;
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
index 0b04d77..79fb721 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPClient.java
@@ -43,7 +43,9 @@ public class SNMPClient {
public static final SNMPVersion DEFAULT_VERSION = SNMPVersion.V2C;
public enum SNMPVersion {
- V1, V2C, V3
+ V1,
+ V2C,
+ V3
}
public static final String[] VALID_AUTHTYPES = { "md5", "sha" };
@@ -90,8 +92,8 @@ public class SNMPClient {
ClassLoader classLoader = (contextClassLoader != null) ? contextClassLoader : this.getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream(OIDS_PROPERTIES_RESOURCE_PATH);
if (stream == null) {
- throw new IllegalStateException("Resource '" + OIDS_PROPERTIES_RESOURCE_PATH
- + "' not found by " + classLoader);
+ throw new IllegalStateException("Resource '" + OIDS_PROPERTIES_RESOURCE_PATH + "' not found by "
+ + classLoader);
}
Properties props = new Properties();
try {
@@ -291,4 +293,4 @@ public class SNMPClient {
return session;
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPConnectException.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPConnectException.java
index 8788e37..5a24b41 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPConnectException.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPConnectException.java
@@ -22,4 +22,4 @@ public class SNMPConnectException extends SNMPException {
public SNMPConnectException(String msg, SNMPSession session) {
super(msg + " SNMP agent at [" + session + "] is either not running or not reachable.");
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPException.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPException.java
index 6d4a02a..849d843 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPException.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPException.java
@@ -26,4 +26,4 @@ public class SNMPException extends Exception {
public SNMPException(String msg, Throwable t) {
super(msg, t);
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession.java
index 41f74ed..f93102a 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession.java
@@ -130,4 +130,4 @@ public interface SNMPSession {
* Closes the session and all underlying resources.
*/
void close();
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSessionCache.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSessionCache.java
index 3eacb80..0cbf569 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSessionCache.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSessionCache.java
@@ -52,8 +52,9 @@ class SNMPSessionCache implements InvocationHandler {
SNMPSession sessionCache;
try {
- sessionCache = (SNMPSession) Proxy.newProxyInstance(SNMPSession.class.getClassLoader(),
- new Class[] { SNMPSession.class }, handler);
+ sessionCache =
+ (SNMPSession) Proxy.newProxyInstance(SNMPSession.class.getClassLoader(),
+ new Class[] { SNMPSession.class }, handler);
} catch (Exception e) {
throw new SNMPException(e.getMessage());
}
@@ -90,7 +91,7 @@ class SNMPSessionCache implements InvocationHandler {
invoker.append('(');
- if (args!= null && args.length != 0) {
+ if (args != null && args.length != 0) {
String arg = args[0].toString();
invoker.append(arg);
@@ -171,4 +172,4 @@ class SNMPSessionCache implements InvocationHandler {
return retval;
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v1.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v1.java
index c9bdfaa..5da2da2 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v1.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v1.java
@@ -267,4 +267,4 @@ class SNMPSession_v1 implements SNMPSession {
return response;
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v2c.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v2c.java
index 521de6f..c43846a 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v2c.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v2c.java
@@ -33,4 +33,4 @@ class SNMPSession_v2c extends SNMPSession_v1 {
SNMPSession_v2c() {
this.version = SnmpConstants.version2c;
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v3.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v3.java
index 09c7cba..25c420d 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v3.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPSession_v3.java
@@ -40,4 +40,4 @@ class SNMPSession_v3 extends SNMPSession_v2c {
void init(String address, int port, String user, String password, int authMethod) throws SNMPException {
// TODO
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPValue.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPValue.java
index 539e08e..3368d15 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPValue.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/snmp/SNMPValue.java
@@ -31,7 +31,9 @@ public class SNMPValue {
private final Log log = LogFactory.getLog(this.getClass());
public enum Type {
- LONG, STRING, LONG_CONVERTABLE
+ LONG,
+ STRING,
+ LONG_CONVERTABLE
}
private OID oid;
@@ -178,4 +180,4 @@ public class SNMPValue {
return cal.getTimeInMillis();
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/util/WWWUtils.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/util/WWWUtils.java
index a979565..d19d28c 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/www/util/WWWUtils.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/www/util/WWWUtils.java
@@ -94,8 +94,7 @@ public abstract class WWWUtils {
// get the response code to actually trigger sending the Request.
connection.getResponseCode();
ret = connection.getHeaderField("Server");
- }
- catch (IOException e) {
+ } catch (IOException e) {
ret = null;
}
return ret;
@@ -103,21 +102,19 @@ public abstract class WWWUtils {
// This method has been added in support of https://bugzilla.redhat.com/show_bug.cgi?id=690430.
private static void disableCertificateVerification(HttpsURLConnection connection) {
- TrustManager[] trustAllCerts = new TrustManager[]{
- new X509TrustManager() {
- public X509Certificate[] getAcceptedIssuers() {
- return new X509Certificate[] {};
- }
+ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[] {};
+ }
- public void checkClientTrusted(X509Certificate[] certs, String authType) {
- return;
- }
+ public void checkClientTrusted(X509Certificate[] certs, String authType) {
+ return;
+ }
- public void checkServerTrusted(X509Certificate[] certs, String authType) {
- return;
- }
+ public void checkServerTrusted(X509Certificate[] certs, String authType) {
+ return;
}
- };
+ } };
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
@@ -134,4 +131,4 @@ public abstract class WWWUtils {
}
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasTest.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasTest.java
index cf592c1..349c846 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasTest.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasTest.java
@@ -17,121 +17,128 @@ import org.rhq.plugins.apache.util.ApacheConfigurationUtil;
import org.rhq.plugins.apache.util.AugeasNodeSearch;
public class ApacheAugeasTest {
-
- /**
- * Tests if all included configuration files were loaded.
- */
- public void testFiles(AugeasProxy augeas){
- System.out.print("Test if all included configuration files was discovered and loaded.");
- AugeasConfigurationApache config = (AugeasConfigurationApache)augeas.getConfiguration();
- List<File> configFiles = config.getAllConfigurationFiles();
-
- /*
- * There are three files one main file one which is included from main file and one which is included from
- * included file and which is declared in IfModule. All of them must be discovered.
- */
- for (File confFile : configFiles){
- boolean found = false;
- for (String fileName : ApacheTestConstants.CONFIG_FILE_NAMES){
- if (!confFile.getName().equals(fileName))
- found = true;
- }
- assert found;
- }
- System.out.println(" [success!]");
- }
- /**
- * Tests mapping of augeas tree to configuration and back.
- * @param cont
- * @throws Exception
- */
- public void testMapping(PluginContainer cont){
- ApacheAugeasUtil apacheUtil = new ApacheAugeasUtil();
- try{
- //copy all configuration files to temporary folder
- String path = apacheUtil.prepareConfigFiles();
- //loading of augeas from temporary folder
- AugeasProxy proxy = apacheUtil.initAugeas(path+File.separator+ApacheTestConstants.ROOT_CONFIG_FILE_NAME, path, path);
- AugeasTree tree = proxy.getAugeasTree(ApacheTestConstants.MODULE_NAME, true);
-
- testLoadConfig(tree, cont);
- testSaveConfig(cont);
- apacheUtil.cleanConfigFiles();
- }catch(Exception e){
- e.printStackTrace();
- apacheUtil.cleanConfigFiles();
- }
- }
- /**
- * Tests mapping of augeas tree to rhq configuration.
- * @param tree
- * @param container
- * @throws Exception
- */
- public void testLoadConfig(AugeasTree tree,PluginContainer container)throws Exception{
- System.out.print("\tTest mapping of augeas tree to rhq configuration.");
- ApacheConfigurationUtil util = new ApacheConfigurationUtil();
- for (Components component : Components.values()){
- //get nodes for each component
- List<AugeasNode> nodes = component.getAllNodes(tree);
- for (int i=0;i<nodes.size();i++){
- String key = AugeasNodeSearch.getNodeKey(nodes.get(i), tree.getRootNode());
- Configuration config = ApacheConfigurationUtil.componentToConfiguration(container, component, key, tree);
- //load configuration for related component and augeas node from tempfolder
- Configuration expectedConfig = util.loadConfiguration(ApacheTestConstants.getConfigFilesPathForLoad()+
- File.separator+component.getComponentName()+String.valueOf(i));
- assert config.equals(expectedConfig) :
- "Unexpected Resource configuration - \nExpected:\n\t"
- + expectedConfig.toString(true) + "\nActual:\n\t" + config.toString(true);
- }
- }
- System.out.println(" [success!]");
- }
-
- /**
- * Tests mapping of rhq configuration to augeas tree.
- *
- * @param container
- * @throws Exception
- */
- public void testSaveConfig(PluginContainer container)throws Exception{
- System.out.print("Test mapping of rhq configuration to augeas tree.");
- ApacheAugeasUtil apacheUtil = new ApacheAugeasUtil();
- //load augeas tree from temporary folder
- String path = ApacheTestConstants.getApacheConfigFilesPath();
- AugeasProxy proxy = apacheUtil.initAugeas(path+ApacheTestConstants.ROOT_CONFIG_FILE_NAME, path, path);
- AugeasTree tree = proxy.getAugeasTree(ApacheTestConstants.MODULE_NAME, true);
- //load augeas tree from temporary folder "updateconfig"
- String pathUpdate = ApacheTestConstants.getApacheConfigFilesPathForUpdate();
- AugeasProxy proxyUpdate = apacheUtil.initAugeas(pathUpdate+ApacheTestConstants.ROOT_CONFIG_FILE_NAME, pathUpdate, pathUpdate);
- AugeasTree treeUpdate = proxyUpdate.getAugeasTree(ApacheTestConstants.MODULE_NAME, true);
-
- for (Components component : Components.values()){
- List<AugeasNode> nodes = component.getAllNodes(tree);
- ConfigurationDefinition configDef = ApacheConfigurationUtil.getConfigurationDefinition(container, component);
- for (int i=0;i<nodes.size();i++){
- //load component from first tree - transfare that tree to configuration - and update second tree with that configuration
- String key = AugeasNodeSearch.getNodeKey(nodes.get(i), tree.getRootNode());
- Configuration config = ApacheConfigurationUtil.componentToConfiguration(container, component, key, tree);
- AugeasNode updateNode = AugeasNodeSearch.findNodeById(treeUpdate.getRootNode(), key);
-
- ApacheAugeasMapping mapping = new ApacheAugeasMapping(treeUpdate);
- mapping.updateAugeas(updateNode, config, configDef);
- }
- }
- treeUpdate.save();
- //test if the updated augeas tree can be mapped to configuration stored at files in "loadconfig" temporary directory
- testLoadConfig(treeUpdate, container);
- System.out.println(" [success!]");
- }
-
- public boolean isAugeasInstalled(){
- try {
- Augeas ag = new Augeas();
- }catch(Throwable e){
- return false;
- }
- return true;
- }
+ /**
+ * Tests if all included configuration files were loaded.
+ */
+ public void testFiles(AugeasProxy augeas) {
+ System.out.print("Test if all included configuration files was discovered and loaded.");
+ AugeasConfigurationApache config = (AugeasConfigurationApache) augeas.getConfiguration();
+ List<File> configFiles = config.getAllConfigurationFiles();
+
+ /*
+ * There are three files one main file one which is included from main file and one which is included from
+ * included file and which is declared in IfModule. All of them must be discovered.
+ */
+ for (File confFile : configFiles) {
+ boolean found = false;
+ for (String fileName : ApacheTestConstants.CONFIG_FILE_NAMES) {
+ if (!confFile.getName().equals(fileName))
+ found = true;
+ }
+ assert found;
+ }
+ System.out.println(" [success!]");
+ }
+
+ /**
+ * Tests mapping of augeas tree to configuration and back.
+ * @param cont
+ * @throws Exception
+ */
+ public void testMapping(PluginContainer cont) {
+ ApacheAugeasUtil apacheUtil = new ApacheAugeasUtil();
+ try {
+ //copy all configuration files to temporary folder
+ String path = apacheUtil.prepareConfigFiles();
+ //loading of augeas from temporary folder
+ AugeasProxy proxy =
+ apacheUtil.initAugeas(path + File.separator + ApacheTestConstants.ROOT_CONFIG_FILE_NAME, path, path);
+ AugeasTree tree = proxy.getAugeasTree(ApacheTestConstants.MODULE_NAME, true);
+
+ testLoadConfig(tree, cont);
+ testSaveConfig(cont);
+ apacheUtil.cleanConfigFiles();
+ } catch (Exception e) {
+ e.printStackTrace();
+ apacheUtil.cleanConfigFiles();
+ }
+ }
+
+ /**
+ * Tests mapping of augeas tree to rhq configuration.
+ * @param tree
+ * @param container
+ * @throws Exception
+ */
+ public void testLoadConfig(AugeasTree tree, PluginContainer container) throws Exception {
+ System.out.print("\tTest mapping of augeas tree to rhq configuration.");
+ ApacheConfigurationUtil util = new ApacheConfigurationUtil();
+ for (Components component : Components.values()) {
+ //get nodes for each component
+ List<AugeasNode> nodes = component.getAllNodes(tree);
+ for (int i = 0; i < nodes.size(); i++) {
+ String key = AugeasNodeSearch.getNodeKey(nodes.get(i), tree.getRootNode());
+ Configuration config =
+ ApacheConfigurationUtil.componentToConfiguration(container, component, key, tree);
+ //load configuration for related component and augeas node from tempfolder
+ Configuration expectedConfig =
+ util.loadConfiguration(ApacheTestConstants.getConfigFilesPathForLoad() + File.separator
+ + component.getComponentName() + String.valueOf(i));
+ assert config.equals(expectedConfig) : "Unexpected Resource configuration - \nExpected:\n\t"
+ + expectedConfig.toString(true) + "\nActual:\n\t" + config.toString(true);
+ }
+ }
+ System.out.println(" [success!]");
+ }
+
+ /**
+ * Tests mapping of rhq configuration to augeas tree.
+ *
+ * @param container
+ * @throws Exception
+ */
+ public void testSaveConfig(PluginContainer container) throws Exception {
+ System.out.print("Test mapping of rhq configuration to augeas tree.");
+ ApacheAugeasUtil apacheUtil = new ApacheAugeasUtil();
+ //load augeas tree from temporary folder
+ String path = ApacheTestConstants.getApacheConfigFilesPath();
+ AugeasProxy proxy = apacheUtil.initAugeas(path + ApacheTestConstants.ROOT_CONFIG_FILE_NAME, path, path);
+ AugeasTree tree = proxy.getAugeasTree(ApacheTestConstants.MODULE_NAME, true);
+ //load augeas tree from temporary folder "updateconfig"
+ String pathUpdate = ApacheTestConstants.getApacheConfigFilesPathForUpdate();
+ AugeasProxy proxyUpdate =
+ apacheUtil.initAugeas(pathUpdate + ApacheTestConstants.ROOT_CONFIG_FILE_NAME, pathUpdate, pathUpdate);
+ AugeasTree treeUpdate = proxyUpdate.getAugeasTree(ApacheTestConstants.MODULE_NAME, true);
+
+ for (Components component : Components.values()) {
+ List<AugeasNode> nodes = component.getAllNodes(tree);
+ ConfigurationDefinition configDef =
+ ApacheConfigurationUtil.getConfigurationDefinition(container, component);
+
+ for (int i = 0; i < nodes.size(); i++) {
+ //load component from first tree - transfare that tree to configuration - and update second tree with that configuration
+ String key = AugeasNodeSearch.getNodeKey(nodes.get(i), tree.getRootNode());
+ Configuration config =
+ ApacheConfigurationUtil.componentToConfiguration(container, component, key, tree);
+ AugeasNode updateNode = AugeasNodeSearch.findNodeById(treeUpdate.getRootNode(), key);
+
+ ApacheAugeasMapping mapping = new ApacheAugeasMapping(treeUpdate);
+ mapping.updateAugeas(updateNode, config, configDef);
+ }
+ }
+ treeUpdate.save();
+ //test if the updated augeas tree can be mapped to configuration stored at files in "loadconfig" temporary directory
+ testLoadConfig(treeUpdate, container);
+ System.out.println(" [success!]");
+ }
+
+ public boolean isAugeasInstalled() {
+ try {
+ Augeas ag = new Augeas();
+ } catch (Throwable e) {
+ return false;
+ }
+ return true;
+ }
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasUtil.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasUtil.java
index 969052d..476e716 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasUtil.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheAugeasUtil.java
@@ -25,148 +25,155 @@ public class ApacheAugeasUtil {
* @param lensPath
* @return
*/
- public AugeasProxy initAugeas(String configFilePath,String serverRootPath,String lensPath){
+ public AugeasProxy initAugeas(String configFilePath, String serverRootPath, String lensPath) {
Configuration configuration = new Configuration();
- configuration.put(new PropertySimple("configurationFilesInclusionPatterns",configFilePath));
+ configuration.put(new PropertySimple("configurationFilesInclusionPatterns", configFilePath));
configuration.put(new PropertySimple("augeasModuleName", ApacheTestConstants.MODULE_NAME));
- configuration.put(new PropertySimple(ApacheTestConstants.PLUGIN_CONFIG_PROP_SERVER_ROOT,serverRootPath));
-
- AugeasConfigurationApache conf = new AugeasConfigurationApache(lensPath,configuration);
+ configuration.put(new PropertySimple(ApacheTestConstants.PLUGIN_CONFIG_PROP_SERVER_ROOT, serverRootPath));
+
+ AugeasConfigurationApache conf = new AugeasConfigurationApache(lensPath, configuration);
AugeasTreeBuilderApache builder = new AugeasTreeBuilderApache();
- AugeasProxy augeas = new AugeasProxy(conf,builder);
-
+ AugeasProxy augeas = new AugeasProxy(conf, builder);
+
augeas.load();
-
+
return augeas;
}
-
+
/**
* This method will create a new temporary directory and copy there all configuration files.
* @return
* @throws UnitTestException
*/
- public String prepareConfigFiles() {
- String tempDirPath=null;
- try {
-
- File tempDirectory = LensHelper.createTempDir(ApacheTestConstants.TEMP_CONFIG_FILE_DIRECTORY);
- if (!tempDirectory.exists())
- tempDirectory.createNewFile();
- //copy the apache configuration files to temp folder
- tempDirPath = tempDirectory.getAbsolutePath()+File.separatorChar;
- copyFiles(ApacheTestConstants.FILES_TO_LOAD, "", tempDirectory);
-
- File updateDir = new File(tempDirectory,ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER);
- if (!updateDir.exists()){
- updateDir.mkdir();
- updateDir.createNewFile();
+ public String prepareConfigFiles() {
+ String tempDirPath = null;
+ try {
+
+ File tempDirectory = LensHelper.createTempDir(ApacheTestConstants.TEMP_CONFIG_FILE_DIRECTORY);
+ if (!tempDirectory.exists())
+ tempDirectory.createNewFile();
+ //copy the apache configuration files to temp folder
+ tempDirPath = tempDirectory.getAbsolutePath() + File.separatorChar;
+ copyFiles(ApacheTestConstants.FILES_TO_LOAD, "", tempDirectory);
+
+ File updateDir = new File(tempDirectory, ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER);
+ if (!updateDir.exists()) {
+ updateDir.mkdir();
+ updateDir.createNewFile();
+ }
+ //copy the apache configuration files to temp folder "updateconfig"
+ copyFiles(ApacheTestConstants.FILES_TO_LOAD, ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER,
+ tempDirectory);
+
+ File loadDir = new File(tempDirectory, ApacheTestConstants.TEST_FILE_CONFIG_FOLDER);
+ if (!loadDir.exists()) {
+ loadDir.mkdir();
+ loadDir.createNewFile();
+ }
+ //copy xml files with rhq configuration to loadconfig
+ for (Components component : Components.values()) {
+ copyFiles(component.getConfigurationFiles().toArray(new String[0]),
+ ApacheTestConstants.TEST_FILE_CONFIG_FOLDER, tempDirectory);
+ }
+
+ ApacheTestConstants.TEMP_FILES_PATH = tempDirectory.getAbsolutePath();
+
+ } catch (Exception e) {
+ e.printStackTrace();
}
- //copy the apache configuration files to temp folder "updateconfig"
- copyFiles(ApacheTestConstants.FILES_TO_LOAD, ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER, tempDirectory);
-
- File loadDir = new File(tempDirectory,ApacheTestConstants.TEST_FILE_CONFIG_FOLDER);
- if (!loadDir.exists()){
- loadDir.mkdir();
- loadDir.createNewFile();
+
+ return tempDirPath;
+ }
+
+ public void cleanConfigFiles() {
+ try {
+
+ File tempDirectory = new File(ApacheTestConstants.getApacheConfigFilesPath());
+ if (!tempDirectory.exists())
+ return;
+
+ deleteFiles(ApacheTestConstants.FILES_TO_LOAD, "", tempDirectory);
+
+ File updateDir = new File(tempDirectory, ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER);
+ if (updateDir.exists()) {
+ deleteFiles(ApacheTestConstants.FILES_TO_LOAD, ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER,
+ tempDirectory);
+ updateDir.delete();
+ }
+ File loadDir = new File(tempDirectory, ApacheTestConstants.TEST_FILE_CONFIG_FOLDER);
+ if (loadDir.exists()) {
+ for (Components component : Components.values()) {
+ deleteFiles(component.getConfigurationFiles().toArray(new String[0]),
+ ApacheTestConstants.TEST_FILE_CONFIG_FOLDER, tempDirectory);
+ }
+ loadDir.delete();
+ }
+
+ tempDirectory.delete();
+ } catch (Exception e) {
+ e.printStackTrace();
}
- //copy xml files with rhq configuration to loadconfig
- for(Components component : Components.values()){
- copyFiles(component.getConfigurationFiles().toArray(new String[0]), ApacheTestConstants.TEST_FILE_CONFIG_FOLDER, tempDirectory);
+ }
+
+ public void copyFiles(String[] files, String folder, File destination) throws Exception {
+ for (String fileName : files) {
+ String path = null;
+
+ if (folder.equals(""))
+ path = fileName;
+ else
+ path = folder + File.separator + fileName;
+
+ File configFile = LensHelper.cpFileFromPluginToTemp(this.getClass().getClassLoader(), destination, path);
+ if (!configFile.exists())
+ throw new UnitTestException("Creation of temporary configuration file failed.");
}
-
- ApacheTestConstants.TEMP_FILES_PATH=tempDirectory.getAbsolutePath();
-
- }catch (Exception e){
- e.printStackTrace();
- }
-
- return tempDirPath;
- }
-
- public void cleanConfigFiles(){
- try {
-
- File tempDirectory = new File(ApacheTestConstants.getApacheConfigFilesPath());
- if (!tempDirectory.exists())
- return;
-
- deleteFiles(ApacheTestConstants.FILES_TO_LOAD, "", tempDirectory);
-
- File updateDir = new File(tempDirectory,ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER);
- if (updateDir.exists()){
- deleteFiles(ApacheTestConstants.FILES_TO_LOAD, ApacheTestConstants.TEST_FILE_APACHE_CONFIG_FOLDER, tempDirectory);
- updateDir.delete();
+ }
+
+ public void deleteFiles(String[] files, String folder, File destination) throws Exception {
+ for (String fileName : files) {
+ String path = null;
+
+ if (folder.equals(""))
+ path = fileName;
+ else
+ path = folder + File.separator + fileName;
+
+ File configFile = new File(destination, path);
+ ;
+ if (configFile.exists())
+ configFile.delete();
}
- File loadDir = new File(tempDirectory,ApacheTestConstants.TEST_FILE_CONFIG_FOLDER);
- if (loadDir.exists())
- {
- for(Components component : Components.values()){
- deleteFiles(component.getConfigurationFiles().toArray(new String[0]), ApacheTestConstants.TEST_FILE_CONFIG_FOLDER, tempDirectory);
- }
- loadDir.delete();
- }
-
- tempDirectory.delete();
- }catch (Exception e){
- e.printStackTrace();
- }
- }
- public void copyFiles(String[] files,String folder,File destination) throws Exception{
- for (String fileName : files){
- String path=null;
-
- if (folder.equals(""))
- path = fileName;
- else
- path = folder+File.separator+fileName;
-
- File configFile = LensHelper.cpFileFromPluginToTemp(this.getClass().getClassLoader(),destination, path);
- if (!configFile.exists())
- throw new UnitTestException("Creation of temporary configuration file failed.");
- }
- }
-
- public void deleteFiles(String[] files,String folder,File destination) throws Exception{
- for (String fileName : files){
- String path=null;
-
- if (folder.equals(""))
- path = fileName;
- else
- path = folder+File.separator+fileName;
-
- File configFile = new File(destination,path);;
- if (configFile.exists())
- configFile.delete();
- }
- }
- /**
- * Method for searching all components in ageasTree which returns List of keys which identify the component.
- * @param parentNodeNames
- * @param componentName
- * @param tree
- * @return
- */
- public List<String> loadComponent(String[] parentNodeNames,String componentName,AugeasTree tree){
+ }
+
+ /**
+ * Method for searching all components in ageasTree which returns List of keys which identify the component.
+ * @param parentNodeNames
+ * @param componentName
+ * @param tree
+ * @return
+ */
+ public List<String> loadComponent(String[] parentNodeNames, String componentName, AugeasTree tree) {
List<String> paramsString = new ArrayList<String>();
List<AugeasNode> nodes = AugeasNodeSearch.searchNode(parentNodeNames, componentName, tree.getRootNode());
- for (AugeasNode node : nodes){
+ for (AugeasNode node : nodes) {
paramsString.add(AugeasNodeSearch.getNodeKey(node, tree.getRootNode()));
- }
- return paramsString;
+ }
+ return paramsString;
+ }
+
+ public void saveFiles(AugeasTree tree, PluginContainer container) throws Exception {
+ for (Components component : Components.values()) {
+ String name = component.getComponentName();
+ List<AugeasNode> nodes = component.getAllNodes(tree);
+ for (int i = 0; i < nodes.size(); i++) {
+ String key = AugeasNodeSearch.getNodeKey(nodes.get(i), tree.getRootNode());
+ //PATH TO THE CONFIG FILES
+ String fileName = name + String.valueOf(i);
+ Configuration config =
+ ApacheConfigurationUtil.componentToConfiguration(container, component, key, tree);
+ ApacheConfigurationUtil.saveConfiguration(config, fileName);
+ }
+ }
}
-
- public void saveFiles(AugeasTree tree,PluginContainer container) throws Exception{
- for (Components component : Components.values()){
- String name = component.getComponentName();
- List<AugeasNode> nodes = component.getAllNodes(tree);
- for (int i=0;i<nodes.size();i++){
- String key = AugeasNodeSearch.getNodeKey(nodes.get(i), tree.getRootNode());
- //PATH TO THE CONFIG FILES
- String fileName = name+String.valueOf(i);
- Configuration config = ApacheConfigurationUtil.componentToConfiguration(container, component, key, tree);
- ApacheConfigurationUtil.saveConfiguration(config, fileName);
- }
- }
- }
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApachePluginTest.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApachePluginTest.java
index 661751e..d9ef5f6 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApachePluginTest.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApachePluginTest.java
@@ -18,7 +18,6 @@
*/
package org.rhq.plugins.apache;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
@@ -63,7 +62,7 @@ public class ApachePluginTest {
pcConfig.setPluginFinder(new FileSystemPluginFinder(pluginDir));
pcConfig.setPluginDirectory(pluginDir);
pcConfig.setDataDirectory(dataDir);
-
+
pcConfig.setInsideAgent(false);
PluginContainer.getInstance().setConfiguration(pcConfig);
PluginContainer container = PluginContainer.getInstance();
@@ -71,7 +70,7 @@ public class ApachePluginTest {
container.getInventoryManager().executeServerScanImmediately();
container.getInventoryManager().executeServiceScanImmediately();
ApacheAugeasTest test = new ApacheAugeasTest();
- if (!test.isAugeasInstalled()){
+ if (!test.isAugeasInstalled()) {
System.out.println("Augeas is not installed.");
return;
}
@@ -113,8 +112,8 @@ public class ApachePluginTest {
@Test(dependsOnMethods = "testServerDiscovery")
public void testServiceDiscovery() throws Exception {
try {
- InventoryReport report = PluginContainer.getInstance().getInventoryManager()
- .executeServiceScanImmediately();
+ InventoryReport report =
+ PluginContainer.getInstance().getInventoryManager().executeServiceScanImmediately();
Resource platform = PluginContainer.getInstance().getInventoryManager().getPlatform();
System.out.println("RUNTIME SERVERS: " + platform.getChildResources().size());
for (Resource server : platform.getChildResources()) {
@@ -129,14 +128,15 @@ public class ApachePluginTest {
@Test(dependsOnMethods = "testServiceDiscovery", enabled = false)
// TODO: this is not a unit test - it requires an apache server to be running with snmp enabled
- public void testMeasurementComponent() throws Exception {
+ public
+ void testMeasurementComponent() throws Exception {
Resource platform = PluginContainer.getInstance().getInventoryManager().getPlatform();
for (Resource server : platform.getChildResources()) {
List<Resource> services = new ArrayList<Resource>(server.getChildResources());
Collections.sort(services);
for (Resource service : services) {
- ResourceComponent serviceComponent = PluginContainer.getInstance().getInventoryManager()
- .getResourceComponent(service);
+ ResourceComponent serviceComponent =
+ PluginContainer.getInstance().getInventoryManager().getResourceComponent(service);
if (serviceComponent instanceof MeasurementFacet) {
Set<MeasurementScheduleRequest> metricList = new HashSet<MeasurementScheduleRequest>();
metricList.add(new MeasurementScheduleRequest(1, "wwwSummaryInRequests", 1000, true,
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheTestConstants.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheTestConstants.java
index a23964b..63fac5b 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheTestConstants.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/ApacheTestConstants.java
@@ -4,44 +4,39 @@ import java.io.File;
public class ApacheTestConstants {
- public static final String MODULE_NAME="Httpd";
- public static final String PLUGIN_NAME="Apache";
- public static final String LENS_NAME="httpd.aug";
+ public static final String MODULE_NAME = "Httpd";
+ public static final String PLUGIN_NAME = "Apache";
+ public static final String LENS_NAME = "httpd.aug";
public static final String TEMP_CONFIG_FILE_DIRECTORY = "HttpdTest";
- public static final String CONFIG_FILE_NAMES [] = {
- "httpd.conf",
- "included.conf",
- "nested.conf"};
- public static final String FILES_TO_LOAD [] = {
- "httpd.conf",
- "included.conf",
- "nested.conf",
- "httpd.aug"};
+ public static final String CONFIG_FILE_NAMES[] = { "httpd.conf", "included.conf", "nested.conf" };
+ public static final String FILES_TO_LOAD[] = { "httpd.conf", "included.conf", "nested.conf", "httpd.aug" };
public static final String ROOT_CONFIG_FILE_NAME = "httpd.conf";
public static final String PLUGIN_CONFIG_PROP_SERVER_ROOT = "serverRoot";
- public static final String TEST_FILE_CONFIG_FOLDER="loadconfig";
- public static final String TEST_FILE_APACHE_CONFIG_FOLDER="updateconfig";
+ public static final String TEST_FILE_CONFIG_FOLDER = "loadconfig";
+ public static final String TEST_FILE_APACHE_CONFIG_FOLDER = "updateconfig";
public static String TEMP_FILES_PATH;
-
+
/**
* Path to folder containing rhq configuration in xml files.
* @return
*/
- public static String getConfigFilesPathForLoad(){
- return TEMP_FILES_PATH+File.separator+TEST_FILE_CONFIG_FOLDER+File.separator;
+ public static String getConfigFilesPathForLoad() {
+ return TEMP_FILES_PATH + File.separator + TEST_FILE_CONFIG_FOLDER + File.separator;
}
+
/**
* Path to folder containing apache configuration in "loadconfig" folder
* @return
*/
- public static String getApacheConfigFilesPathForUpdate(){
- return TEMP_FILES_PATH+File.separator+TEST_FILE_APACHE_CONFIG_FOLDER+File.separator;
+ public static String getApacheConfigFilesPathForUpdate() {
+ return TEMP_FILES_PATH + File.separator + TEST_FILE_APACHE_CONFIG_FOLDER + File.separator;
}
+
/**
* Path to temporary folder where are/will be stored all config files.
* @return
*/
- public static String getApacheConfigFilesPath(){
- return TEMP_FILES_PATH+File.separator;
+ public static String getApacheConfigFilesPath() {
+ return TEMP_FILES_PATH + File.separator;
}
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/Components.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/Components.java
index ff00796..121f629 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/Components.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/Components.java
@@ -14,112 +14,133 @@ import org.rhq.plugins.apache.util.AugeasNodeSearch;
*/
public enum Components {
- IFMODULE{
- public String getComponentName(){
- return "IfModule";
- }
- public String[] getPossParentNodeName(){
- String [] parentNames = new String[2];
- parentNames[0]="<IfModule";
- parentNames[1]="<VirtualHost";
- return parentNames;
- }
- public String getNodeName(){
- return "<IfModule";
- }
- public List<AugeasNode> getAllNodes(AugeasTree tree){
- return AugeasNodeSearch.searchNode(IFMODULE.getPossParentNodeName(), IFMODULE.getNodeName(), tree.getRootNode());
- }
- public List<String> getConfigurationFiles(){
- List<String> list = new ArrayList<String>();
+ IFMODULE {
+ public String getComponentName() {
+ return "IfModule";
+ }
+
+ public String[] getPossParentNodeName() {
+ String[] parentNames = new String[2];
+ parentNames[0] = "<IfModule";
+ parentNames[1] = "<VirtualHost";
+ return parentNames;
+ }
+
+ public String getNodeName() {
+ return "<IfModule";
+ }
+
+ public List<AugeasNode> getAllNodes(AugeasTree tree) {
+ return AugeasNodeSearch.searchNode(IFMODULE.getPossParentNodeName(), IFMODULE.getNodeName(),
+ tree.getRootNode());
+ }
+
+ public List<String> getConfigurationFiles() {
+ List<String> list = new ArrayList<String>();
list.add("IfModule0");
list.add("IfModule1");
- return list;
- }
+ return list;
+ }
},
-
- IFMODULE_DIRECTORY{
- public String getComponentName(){
- return "IfModule Parameters";
- }
- public String[] getPossParentNodeName(){
- String [] parentNames = new String[1];
- parentNames[0]="<IfModule";
+
+ IFMODULE_DIRECTORY {
+ public String getComponentName() {
+ return "IfModule Parameters";
+ }
+
+ public String[] getPossParentNodeName() {
+ String[] parentNames = new String[1];
+ parentNames[0] = "<IfModule";
return parentNames;
}
- public String getNodeName(){
+
+ public String getNodeName() {
return "<IfModule";
}
- public List<AugeasNode> getAllNodes(AugeasTree tree){
+
+ public List<AugeasNode> getAllNodes(AugeasTree tree) {
List<AugeasNode> nodes = DIRECTORY.getAllNodes(tree);
List<AugeasNode> ifModNodes = new ArrayList<AugeasNode>();
- for (AugeasNode node : nodes){
- List<AugeasNode> tempNodes = AugeasNodeSearch.searchNode(IFMODULE_DIRECTORY.getPossParentNodeName(), IFMODULE_DIRECTORY.getNodeName(), node);
- if (tempNodes != null)
- ifModNodes.addAll(tempNodes);
+ for (AugeasNode node : nodes) {
+ List<AugeasNode> tempNodes =
+ AugeasNodeSearch.searchNode(IFMODULE_DIRECTORY.getPossParentNodeName(),
+ IFMODULE_DIRECTORY.getNodeName(), node);
+ if (tempNodes != null)
+ ifModNodes.addAll(tempNodes);
}
return ifModNodes;
-
+
}
-
- public List<String> getConfigurationFiles(){
+
+ public List<String> getConfigurationFiles() {
List<String> list = new ArrayList<String>();
list.add("IfModule Parameters0");
return list;
}
- },
-
- DIRECTORY{
- public String getComponentName(){
- return "Directory";
+ },
+
+ DIRECTORY {
+ public String getComponentName() {
+ return "Directory";
}
- public String[] getPossParentNodeName(){
- String [] parentNames = new String[2];
- parentNames[0]="<IfModule";
- parentNames[1]="<VirtualHost";
- return parentNames;
+
+ public String[] getPossParentNodeName() {
+ String[] parentNames = new String[2];
+ parentNames[0] = "<IfModule";
+ parentNames[1] = "<VirtualHost";
+ return parentNames;
}
- public String getNodeName(){
+
+ public String getNodeName() {
return "<Directory";
}
- public List<AugeasNode> getAllNodes(AugeasTree tree){
- return AugeasNodeSearch.searchNode(DIRECTORY.getPossParentNodeName(), DIRECTORY.getNodeName(), tree.getRootNode());
+
+ public List<AugeasNode> getAllNodes(AugeasTree tree) {
+ return AugeasNodeSearch.searchNode(DIRECTORY.getPossParentNodeName(), DIRECTORY.getNodeName(),
+ tree.getRootNode());
}
-
- public List<String> getConfigurationFiles(){
+
+ public List<String> getConfigurationFiles() {
List<String> list = new ArrayList<String>();
list.add("Directory0");
list.add("Directory1");
list.add("Directory2");
return list;
}
- },
-
- VIRTUALHOST{
- public String getComponentName(){
+ },
+
+ VIRTUALHOST {
+ public String getComponentName() {
return "Apache Virtual Host";
}
- public String[] getPossParentNodeName(){
- String [] parentNames = new String[0];
+
+ public String[] getPossParentNodeName() {
+ String[] parentNames = new String[0];
return parentNames;
}
- public String getNodeName(){
+
+ public String getNodeName() {
return "<VirtualHost";
}
- public List<AugeasNode> getAllNodes(AugeasTree tree){
+
+ public List<AugeasNode> getAllNodes(AugeasTree tree) {
return tree.getRootNode().getChildByLabel("<VirtualHost");
}
-
- public List<String> getConfigurationFiles(){
+
+ public List<String> getConfigurationFiles() {
List<String> list = new ArrayList<String>();
list.add("Apache Virtual Host0");
return list;
}
- };
-
+ };
+
public abstract String getComponentName();
+
public abstract String[] getPossParentNodeName();
+
public abstract String getNodeName();
+
public abstract List<AugeasNode> getAllNodes(AugeasTree tree);
+
public abstract List<String> getConfigurationFiles();
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/RuntimeConfigurationTest.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/RuntimeConfigurationTest.java
index 74f4e81..43f3bf0 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/RuntimeConfigurationTest.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/RuntimeConfigurationTest.java
@@ -55,42 +55,34 @@ import org.rhq.plugins.apache.util.RuntimeApacheConfiguration;
public class RuntimeConfigurationTest {
private File tmpDir;
-
- private static final String[] CONDITIONAL_CONFIGURATION_TEST_FILES = {
- "runtime-config/conditional/httpd.conf",
- "runtime-config/conditional/ifdefine-defined.conf",
- "runtime-config/conditional/ifdefine-undefined.conf",
- "runtime-config/conditional/ifmodule-loaded.conf",
- "runtime-config/conditional/ifmodule-not-loaded.conf",
- "runtime-config/conditional/ifversion.conf",
- "runtime-config/conditional/nested-mess.conf"
- };
-
- private static final String[] INCLUSION_ORDER_CONFIGURATION_TEST_FILES = {
- "runtime-config/incl-order/a.conf",
- "runtime-config/incl-order/b.conf",
- "runtime-config/incl-order/c.conf",
- "runtime-config/incl-order/httpd.conf"
- };
-
+
+ private static final String[] CONDITIONAL_CONFIGURATION_TEST_FILES = { "runtime-config/conditional/httpd.conf",
+ "runtime-config/conditional/ifdefine-defined.conf", "runtime-config/conditional/ifdefine-undefined.conf",
+ "runtime-config/conditional/ifmodule-loaded.conf", "runtime-config/conditional/ifmodule-not-loaded.conf",
+ "runtime-config/conditional/ifversion.conf", "runtime-config/conditional/nested-mess.conf" };
+
+ private static final String[] INCLUSION_ORDER_CONFIGURATION_TEST_FILES =
+ { "runtime-config/incl-order/a.conf", "runtime-config/incl-order/b.conf", "runtime-config/incl-order/c.conf",
+ "runtime-config/incl-order/httpd.conf" };
+
@BeforeClass
public void copyConfigurationFiles() throws Exception {
tmpDir = FileUtil.createTempDirectory("apache-runtime-config-tests", null, null);
-
- for(String path : CONDITIONAL_CONFIGURATION_TEST_FILES) {
+
+ for (String path : CONDITIONAL_CONFIGURATION_TEST_FILES) {
copyResourceToFile(path, new File(tmpDir, path));
}
-
- for(String path : INCLUSION_ORDER_CONFIGURATION_TEST_FILES) {
+
+ for (String path : INCLUSION_ORDER_CONFIGURATION_TEST_FILES) {
copyResourceToFile(path, new File(tmpDir, path));
}
}
-
+
@AfterClass
public void deleteConfigurationFiles() throws IOException {
FileUtils.purge(tmpDir, true);
}
-
+
public void testConditionalInclusion() {
MockApacheBinaryInfo binfo = new MockApacheBinaryInfo();
binfo.setVersion("2.2.17");
@@ -103,23 +95,27 @@ public class RuntimeConfigurationTest {
"runtime-config/conditional/httpd.conf").getAbsolutePath(), pinfo, binfo);
List<VhostSpec> vhosts = VhostSpec.detect(tree);
-
+
List<VhostSpec> expectedVhosts = new ArrayList<VhostSpec>();
-
+
expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:100"), "ifdefine.defined"));
expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:300"), "ifmodule.loaded.source-file"));
expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:301"), "ifmodule.loaded.module-name"));
- expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:501"), "ifversion.module-loaded.implied-equals"));
+ expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:501"),
+ "ifversion.module-loaded.implied-equals"));
expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:502"), "ifversion.module-loaded.equals"));
expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:503"), "ifversion.module-loaded.not-equals"));
expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:504"), "ifversion.module-loaded.regex"));
- expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:505"), "ifversion.module-loaded.implied-regex"));
- expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:602"), "ifdefine.ifmodule.loaded.source-file"));
- expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:603"), "ifdefine.ifmodule.loaded.module-name"));
-
+ expectedVhosts.add(new VhostSpec(Collections.singleton("127.0.0.1:505"),
+ "ifversion.module-loaded.implied-regex"));
+ expectedVhosts
+ .add(new VhostSpec(Collections.singleton("127.0.0.1:602"), "ifdefine.ifmodule.loaded.source-file"));
+ expectedVhosts
+ .add(new VhostSpec(Collections.singleton("127.0.0.1:603"), "ifdefine.ifmodule.loaded.module-name"));
+
assertEquals(vhosts, expectedVhosts);
}
-
+
public void testInclusionOrder() {
MockApacheBinaryInfo binfo = new MockApacheBinaryInfo();
binfo.setVersion("2.2.17");
@@ -132,39 +128,39 @@ public class RuntimeConfigurationTest {
"runtime-config/incl-order/httpd.conf").getAbsolutePath(), pinfo, binfo);
List<ApacheDirective> listens = tree.search("/Listen");
-
+
assertEquals(listens.size(), 3, "There should be 3 listen directives");
-
+
assertEquals(listens.get(0).getValuesAsString(), "80");
assertEquals(listens.get(1).getValuesAsString(), "81");
assertEquals(listens.get(2).getValuesAsString(), "82");
}
-
- private void copyResourceToFile(String resourcePath, File destination) throws IOException {
+
+ private void copyResourceToFile(String resourcePath, File destination) throws IOException {
InputStream input = getClass().getClassLoader().getResourceAsStream(resourcePath);
-
+
if (input != null) {
destination.getParentFile().mkdirs();
destination.createNewFile();
-
+
StreamUtil.copy(input, new BufferedOutputStream(new FileOutputStream(destination)), true);
}
}
-
+
private static class VhostSpec {
public List<String> definition;
public String serverName;
-
+
public static List<VhostSpec> detect(ApacheDirectiveTree tree) {
List<VhostSpec> ret = new ArrayList<VhostSpec>();
-
- for(ApacheDirective vhost : tree.search("/<VirtualHost")) {
+
+ for (ApacheDirective vhost : tree.search("/<VirtualHost")) {
ret.add(new VhostSpec(vhost));
}
-
+
return ret;
}
-
+
public VhostSpec(ApacheDirective vhost) {
definition = vhost.getValues();
List<ApacheDirective> serverNames = vhost.getChildByName("ServerName");
@@ -172,34 +168,34 @@ public class RuntimeConfigurationTest {
serverName = serverNames.get(0).getValuesAsString();
}
}
-
+
public VhostSpec(Collection<String> definition, String serverName) {
this.definition = new ArrayList<String>(definition);
this.serverName = serverName;
}
-
+
@Override
public String toString() {
return "VhostSpec[serverName='" + serverName + "', definition=" + definition + "]";
}
-
+
@Override
public int hashCode() {
return serverName.hashCode();
}
-
+
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
-
+
if (!(other instanceof VhostSpec)) {
- return false;
+ return false;
}
-
+
VhostSpec o = (VhostSpec) other;
-
+
return serverName.equals(o.serverName) && definition.equals(o.definition);
}
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/SnmpMappingTest.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/SnmpMappingTest.java
index fd825c1..8c22cc4 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/SnmpMappingTest.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/SnmpMappingTest.java
@@ -56,18 +56,15 @@ import org.rhq.plugins.apache.util.MockProcessInfo;
public class SnmpMappingTest {
private File tmpDir;
-
- private static final String[] VHOST_NAMES_CONFIGURATION_TEST_FILES = {
- "snmp-mapping/httpd.conf",
+
+ private static final String[] VHOST_NAMES_CONFIGURATION_TEST_FILES = { "snmp-mapping/httpd.conf",
"snmp-mapping/vhost-with-servername-by-ip.conf",
"snmp-mapping/vhost-with-servername-by-unresolvable-hostname.conf",
"snmp-mapping/vhost-without-servername-resolvable-ip.conf",
"snmp-mapping/vhost-without-servername-unresolvable-hostname.conf",
- "snmp-mapping/vhost-without-servername-unresolvable-ip.conf"
- };
-
- private static final String[] EXPECTED_SNMP_NAMES = {
- "the-main-server-name:42", //httpd.conf
+ "snmp-mapping/vhost-without-servername-unresolvable-ip.conf" };
+
+ private static final String[] EXPECTED_SNMP_NAMES = { "the-main-server-name:42", //httpd.conf
"12.34.56.78:0", //vhost-with-servername-by-ip.conf
"this-will-never-resolve.weird-server.net:90", //vhost-with-servername-by-unresolvable-hostname.conf
"<<<LOCALHOST>>>:1002", //vhost-without-servernama-resolvable-ip.conf
@@ -78,25 +75,24 @@ public class SnmpMappingTest {
@BeforeClass
public void copyConfigurationFiles() throws Exception {
tmpDir = FileUtil.createTempDirectory("apache-runtime-config-tests", null, null);
-
- for(String path : VHOST_NAMES_CONFIGURATION_TEST_FILES) {
+
+ for (String path : VHOST_NAMES_CONFIGURATION_TEST_FILES) {
copyResourceToFile(path, new File(tmpDir, path));
}
}
-
+
@BeforeClass
public void initExpectedResults() throws Exception {
String localhost = InetAddress.getByName("127.0.0.1").getHostName();
- for(int i = 0; i < EXPECTED_SNMP_NAMES.length; ++i) {
+ for (int i = 0; i < EXPECTED_SNMP_NAMES.length; ++i) {
EXPECTED_SNMP_NAMES[i] = EXPECTED_SNMP_NAMES[i].replaceAll("<<<LOCALHOST>>>", localhost);
}
}
-
+
@AfterClass
public void deleteConfigurationFiles() throws IOException {
FileUtils.purge(tmpDir, true);
}
-
public void testVhostNames() {
MockApacheBinaryInfo binfo = new MockApacheBinaryInfo();
@@ -113,29 +109,29 @@ public class SnmpMappingTest {
List<ApacheDirective> vhosts = tree.search("/<VirtualHost");
List<String> snmpNames = new ArrayList<String>(vhosts.size() + 1);
snmpNames.add(addrUtil.getHttpdInternalMainServerAddressRepresentation(tree).toString(false, false));
- for(ApacheDirective vhost : vhosts) {
+ for (ApacheDirective vhost : vhosts) {
String vhostDef = vhost.getValues().get(0);
String serverName = null;
List<ApacheDirective> serverNames = vhost.getChildByName("ServerName");
if (serverNames.size() > 0) {
serverName = serverNames.get(serverNames.size() - 1).getValuesAsString();
}
-
- snmpNames.add(addrUtil.getHttpdInternalVirtualHostAddressRepresentation(tree, vhostDef, serverName).toString(false, false));
+
+ snmpNames.add(addrUtil.getHttpdInternalVirtualHostAddressRepresentation(tree, vhostDef, serverName)
+ .toString(false, false));
}
-
+
assertEquals(snmpNames, Arrays.asList(EXPECTED_SNMP_NAMES));
}
-
- private void copyResourceToFile(String resourcePath, File destination) throws IOException {
+ private void copyResourceToFile(String resourcePath, File destination) throws IOException {
InputStream input = getClass().getClassLoader().getResourceAsStream(resourcePath);
-
+
if (input != null) {
destination.getParentFile().mkdirs();
destination.createNewFile();
-
+
StreamUtil.copy(input, new BufferedOutputStream(new FileOutputStream(destination)), true);
}
- }
+ }
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/UnitTestException.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/UnitTestException.java
index 41b3ee9..fb5d02f 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/UnitTestException.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/UnitTestException.java
@@ -1,21 +1,21 @@
package org.rhq.plugins.apache;
-public class UnitTestException extends Exception{
+public class UnitTestException extends Exception {
- public UnitTestException(){
- super();
- }
+ public UnitTestException() {
+ super();
+ }
- public UnitTestException(String text){
- super(text);
- }
-
- public UnitTestException(Exception e){
- super(e);
- }
-
- public UnitTestException(String message,Throwable cause){
- super(message,cause);
- }
+ public UnitTestException(String text) {
+ super(text);
+ }
+
+ public UnitTestException(Exception e) {
+ super(e);
+ }
+
+ public UnitTestException(String message, Throwable cause) {
+ super(message, cause);
+ }
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensFilter.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensFilter.java
index f6df6d0..9fc297b 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensFilter.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensFilter.java
@@ -5,19 +5,19 @@ import java.io.FileFilter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-public class LensFilter implements FileFilter{
+public class LensFilter implements FileFilter {
private Pattern pattern;
-
- public LensFilter(String name){
- pattern = Pattern.compile(name+".*");
+
+ public LensFilter(String name) {
+ pattern = Pattern.compile(name + ".*");
}
-
+
public boolean accept(File pathname) {
String name = pathname.getName();
Matcher match = pattern.matcher(name);
if (match.matches())
- return true;
-
+ return true;
+
return false;
}
-}
\ No newline at end of file
+}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensHelper.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensHelper.java
index 329b3ca..310d1f9 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensHelper.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/helper/LensHelper.java
@@ -29,81 +29,80 @@ import java.io.InputStream;
import java.io.OutputStream;
public class LensHelper {
- public static final String TEMP_DIRECTORY = "java.io.tmpdir";
- public static final String TEMP_FILE_SUFFIX = ".aug";
-
-
- public static String getLensPath(String param) throws IOException,Exception{
- String lensPath=null;
-
- if (param.indexOf(File.separatorChar)==-1){
-
- }else
- lensPath = param;
- return lensPath;
-
- }
-
- public static void copyFile(InputStream in,File destination) throws Exception{
-
- if (!destination.canWrite())
+ public static final String TEMP_DIRECTORY = "java.io.tmpdir";
+ public static final String TEMP_FILE_SUFFIX = ".aug";
+
+ public static String getLensPath(String param) throws IOException, Exception {
+ String lensPath = null;
+
+ if (param.indexOf(File.separatorChar) == -1) {
+
+ } else
+ lensPath = param;
+ return lensPath;
+
+ }
+
+ public static void copyFile(InputStream in, File destination) throws Exception {
+
+ if (!destination.canWrite())
throw new Exception("Creating of temporary file for lens failed. Destination file "
- + destination.getAbsolutePath()+" is not accessible.");
+ + destination.getAbsolutePath() + " is not accessible.");
OutputStream out = new FileOutputStream(destination);
-
+
byte[] buf = new byte[1024];
int length;
-
+
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
-
+
in.close();
out.close();
- }
-
- public static File createTempDir(String name) throws IOException{
-
- String tempDir = (String)System.getProperties().get(TEMP_DIRECTORY);
-
- File tempDirectory = new File(tempDir);
- File [] lens = tempDirectory.listFiles(new LensFilter(name));
-
- File lensDirectory;
-
- if (lens.length==0){
- File tempFile = File.createTempFile(name, "");
- String nm = tempFile.getName();
- tempFile.delete();
- lensDirectory = new File(tempDirectory,nm);
- lensDirectory.mkdir();
- lensDirectory.deleteOnExit();
- }else{
- lensDirectory = lens[0];
- }
-
- return lensDirectory;
-
- }
-
- public static String getTempDirectoryPath(){
- return (String)System.getProperties().get(TEMP_DIRECTORY);
- }
-
- public static File cpFileFromPluginToTemp(ClassLoader loader,File tempDirectory,String fileName) throws IOException,Exception{
-
- File destinationFile = new File(tempDirectory,fileName);
- if (!destinationFile.exists())
- {
+ }
+
+ public static File createTempDir(String name) throws IOException {
+
+ String tempDir = (String) System.getProperties().get(TEMP_DIRECTORY);
+
+ File tempDirectory = new File(tempDir);
+ File[] lens = tempDirectory.listFiles(new LensFilter(name));
+
+ File lensDirectory;
+
+ if (lens.length == 0) {
+ File tempFile = File.createTempFile(name, "");
+ String nm = tempFile.getName();
+ tempFile.delete();
+ lensDirectory = new File(tempDirectory, nm);
+ lensDirectory.mkdir();
+ lensDirectory.deleteOnExit();
+ } else {
+ lensDirectory = lens[0];
+ }
+
+ return lensDirectory;
+
+ }
+
+ public static String getTempDirectoryPath() {
+ return (String) System.getProperties().get(TEMP_DIRECTORY);
+ }
+
+ public static File cpFileFromPluginToTemp(ClassLoader loader, File tempDirectory, String fileName)
+ throws IOException, Exception {
+
+ File destinationFile = new File(tempDirectory, fileName);
+ if (!destinationFile.exists()) {
destinationFile.createNewFile();
-
- InputStream input = loader.getResourceAsStream(fileName);
+
+ InputStream input = loader.getResourceAsStream(fileName);
copyFile(input, destinationFile);
- }
-
+ }
+
return destinationFile;
- }
-
-}
\ No newline at end of file
+ }
+
+}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/ApacheConfigurationUtil.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/ApacheConfigurationUtil.java
index 0014a1c..c006a7d 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/ApacheConfigurationUtil.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/ApacheConfigurationUtil.java
@@ -38,192 +38,190 @@ import org.apache.xml.serialize.XMLSerializer;
*/
public class ApacheConfigurationUtil {
-
+
public static final String SIMPLE_TAG_NAME = "simple";
public static final String LIST_TAG_NAME = "list";
public static final String MAP_TAG_NAME = "map";
public static final String ROOT_ELEMENT = "configuration";
public static final String NAME_ATTRIBUTE = "name";
-
- private Document loadXML(String file) throws UnitTestException{
- Document document= null;
- try {
- File xmlFile = new File(file);
- if (!xmlFile.exists())
- throw new UnitTestException("Configuration file not found.");
-
- DocumentBuilderFactory factory =
- DocumentBuilderFactory.newInstance();
- DocumentBuilder loader = factory.newDocumentBuilder();
-
- document = loader.parse(file);
-
- }catch(Exception e){
- throw new UnitTestException("Loading of xml file failed.",e);
- }
-
- return document;
- }
-
- public static void saveConfiguration(Configuration config,String fileName) throws UnitTestException{
- try {
- Collection<Property> properties = config.getProperties();
- DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
- Document doc = docBuilder.newDocument();
- Element element = doc.createElement(ROOT_ELEMENT);
-
- for (Property property : properties){
- element.appendChild(configurationToDom(property,doc));
- }
- doc.appendChild(element);
- saveXML(doc,fileName);
-
- }catch(Exception e){
- throw new UnitTestException(e);
- }
- }
-
-
- private static Element configurationToDom(Property prop,Document doc){
- Element element = null;
- if (prop instanceof PropertySimple){
- element = doc.createElement(SIMPLE_TAG_NAME);
- element.appendChild(doc.createTextNode(((PropertySimple) prop).getStringValue()));
- }
-
- if (prop instanceof PropertyList){
- PropertyList list = (PropertyList) prop;
- element = doc.createElement(LIST_TAG_NAME);
- List<Property> propertyList = list.getList();
- for (Property property : propertyList){
- element.appendChild(configurationToDom(property,doc));
- }
- }
-
- if (prop instanceof PropertyMap){
- PropertyMap map = (PropertyMap) prop;
- element = doc.createElement(MAP_TAG_NAME);
- Map<String,Property> propertyMap = map.getMap();
- for (Property property : propertyMap.values()){
- element.appendChild(configurationToDom(property,doc));
- }
- }
-
- fillElement(element,prop);
- return element;
- }
-
- private static void fillElement(Element element,Property prop){
- element.setAttribute(NAME_ATTRIBUTE, prop.getName());
- }
-
- public Configuration loadConfiguration(String fileName) throws UnitTestException{
- Document document = loadXML(fileName);
- NodeList nodeList = document.getElementsByTagName(ROOT_ELEMENT);
- if (nodeList.getLength()!=1)
- throw new UnitTestException("Configuration file's " + fileName+ " format is not valid.");
-
- Node rootElement = nodeList.item(0);
- Configuration configuration = new Configuration();
- NodeList childNodes = rootElement.getChildNodes();
- for (int i=0;i<childNodes.getLength();i++){
- configuration.put(domToConfiguration(childNodes.item(i)));
+
+ private Document loadXML(String file) throws UnitTestException {
+ Document document = null;
+ try {
+ File xmlFile = new File(file);
+ if (!xmlFile.exists())
+ throw new UnitTestException("Configuration file not found.");
+
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder loader = factory.newDocumentBuilder();
+
+ document = loader.parse(file);
+
+ } catch (Exception e) {
+ throw new UnitTestException("Loading of xml file failed.", e);
+ }
+
+ return document;
+ }
+
+ public static void saveConfiguration(Configuration config, String fileName) throws UnitTestException {
+ try {
+ Collection<Property> properties = config.getProperties();
+ DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
+ DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
+ Document doc = docBuilder.newDocument();
+ Element element = doc.createElement(ROOT_ELEMENT);
+
+ for (Property property : properties) {
+ element.appendChild(configurationToDom(property, doc));
+ }
+ doc.appendChild(element);
+ saveXML(doc, fileName);
+
+ } catch (Exception e) {
+ throw new UnitTestException(e);
+ }
+ }
+
+ private static Element configurationToDom(Property prop, Document doc) {
+ Element element = null;
+ if (prop instanceof PropertySimple) {
+ element = doc.createElement(SIMPLE_TAG_NAME);
+ element.appendChild(doc.createTextNode(((PropertySimple) prop).getStringValue()));
+ }
+
+ if (prop instanceof PropertyList) {
+ PropertyList list = (PropertyList) prop;
+ element = doc.createElement(LIST_TAG_NAME);
+ List<Property> propertyList = list.getList();
+ for (Property property : propertyList) {
+ element.appendChild(configurationToDom(property, doc));
+ }
+ }
+
+ if (prop instanceof PropertyMap) {
+ PropertyMap map = (PropertyMap) prop;
+ element = doc.createElement(MAP_TAG_NAME);
+ Map<String, Property> propertyMap = map.getMap();
+ for (Property property : propertyMap.values()) {
+ element.appendChild(configurationToDom(property, doc));
+ }
+ }
+
+ fillElement(element, prop);
+ return element;
+ }
+
+ private static void fillElement(Element element, Property prop) {
+ element.setAttribute(NAME_ATTRIBUTE, prop.getName());
+ }
+
+ public Configuration loadConfiguration(String fileName) throws UnitTestException {
+ Document document = loadXML(fileName);
+ NodeList nodeList = document.getElementsByTagName(ROOT_ELEMENT);
+ if (nodeList.getLength() != 1)
+ throw new UnitTestException("Configuration file's " + fileName + " format is not valid.");
+
+ Node rootElement = nodeList.item(0);
+ Configuration configuration = new Configuration();
+ NodeList childNodes = rootElement.getChildNodes();
+ for (int i = 0; i < childNodes.getLength(); i++) {
+ configuration.put(domToConfiguration(childNodes.item(i)));
+ }
+ return configuration;
+ }
+
+ private Property domToConfiguration(Node node) {
+ String nodeName = node.getNodeName();
+ NamedNodeMap attrMap = node.getAttributes();
+ Node attrNode = attrMap.getNamedItem(NAME_ATTRIBUTE);
+ String propertyName = attrNode.getNodeValue();
+
+ Property prop = null;
+
+ if (nodeName.equals(SIMPLE_TAG_NAME)) {
+ PropertySimple propertySimple = new PropertySimple(propertyName, null);
+ String value = node.getTextContent();
+ // Normalize "" to null.
+ propertySimple.setStringValue(("".equals(value)) ? null : value);
+ prop = propertySimple;
+ }
+
+ if (nodeName.equals(LIST_TAG_NAME)) {
+ PropertyList propertyList = new PropertyList(propertyName);
+ NodeList list = node.getChildNodes();
+ for (int i = 0; i < list.getLength(); i++) {
+ propertyList.add(domToConfiguration(list.item(i)));
}
- return configuration;
- }
-
- private Property domToConfiguration(Node node){
- String nodeName = node.getNodeName();
- NamedNodeMap attrMap = node.getAttributes();
- Node attrNode = attrMap.getNamedItem(NAME_ATTRIBUTE);
- String propertyName = attrNode.getNodeValue();
-
- Property prop = null;
-
- if (nodeName.equals(SIMPLE_TAG_NAME)){
- PropertySimple propertySimple = new PropertySimple(propertyName,null);
- String value = node.getTextContent();
- // Normalize "" to null.
- propertySimple.setStringValue(("".equals(value)) ? null : value);
- prop = propertySimple;
- }
-
- if (nodeName.equals(LIST_TAG_NAME)){
- PropertyList propertyList = new PropertyList(propertyName);
- NodeList list = node.getChildNodes();
- for (int i=0;i<list.getLength();i++) {
- propertyList.add(domToConfiguration(list.item(i)));
- }
- prop = propertyList;
- }
-
- if (nodeName.equals(MAP_TAG_NAME)){
- PropertyMap propertyMap = new PropertyMap(propertyName);
- NodeList list = node.getChildNodes();
- for (int i=0;i<list.getLength();i++){
- propertyMap.put(domToConfiguration(list.item(i)));
- }
- prop = propertyMap;
- }
-
- return prop;
- }
-
- private static void saveXML(Document document,String fileName) throws UnitTestException{
- try {
- File file = new File(fileName);
- if (!file.exists())
- file.createNewFile();
-
+ prop = propertyList;
+ }
+
+ if (nodeName.equals(MAP_TAG_NAME)) {
+ PropertyMap propertyMap = new PropertyMap(propertyName);
+ NodeList list = node.getChildNodes();
+ for (int i = 0; i < list.getLength(); i++) {
+ propertyMap.put(domToConfiguration(list.item(i)));
+ }
+ prop = propertyMap;
+ }
+
+ return prop;
+ }
+
+ private static void saveXML(Document document, String fileName) throws UnitTestException {
+ try {
+ File file = new File(fileName);
+ if (!file.exists())
+ file.createNewFile();
+
XMLSerializer serializer = new XMLSerializer();
- serializer.setOutputCharStream(
- new java.io.FileWriter(fileName));
+ serializer.setOutputCharStream(new java.io.FileWriter(fileName));
serializer.serialize(document);
- }catch(Exception e){
- throw new UnitTestException("Saving of xml file failed",e);
- }
- }
-
- public static void printConfiguration(Property prop){
- if (prop instanceof PropertySimple){
- System.out.println(" SimpleProperty name="+prop.getName()+" value="+((PropertySimple)prop).getStringValue());
+ } catch (Exception e) {
+ throw new UnitTestException("Saving of xml file failed", e);
}
-
- if (prop instanceof PropertyList){
+ }
+
+ public static void printConfiguration(Property prop) {
+ if (prop instanceof PropertySimple) {
+ System.out.println(" SimpleProperty name=" + prop.getName() + " value="
+ + ((PropertySimple) prop).getStringValue());
+ }
+
+ if (prop instanceof PropertyList) {
PropertyList list = (PropertyList) prop;
- System.out.println("PropertyList name="+list.getName());
- for (Property property : list.getList()){
+ System.out.println("PropertyList name=" + list.getName());
+ for (Property property : list.getList()) {
printConfiguration(property);
}
}
-
- if (prop instanceof PropertyMap){
+
+ if (prop instanceof PropertyMap) {
PropertyMap map = (PropertyMap) prop;
- System.out.println(" PropertyMap name="+map.getName());
- Map<String,Property> propertyMap = map.getMap();
- for (Property property : propertyMap.values()){
+ System.out.println(" PropertyMap name=" + map.getName());
+ Map<String, Property> propertyMap = map.getMap();
+ for (Property property : propertyMap.values()) {
printConfiguration(property);
- }
+ }
}
}
-
-
- public static ConfigurationDefinition getConfigurationDefinition(PluginContainer container,Components component){
+
+ public static ConfigurationDefinition getConfigurationDefinition(PluginContainer container, Components component) {
PluginManager pluginManager = container.getPluginManager();
PluginMetadataManager pluginMetadataManager = pluginManager.getMetadataManager();
- ResourceType type = pluginMetadataManager.getType(component.getComponentName(), ApacheTestConstants.PLUGIN_NAME);
+ ResourceType type =
+ pluginMetadataManager.getType(component.getComponentName(), ApacheTestConstants.PLUGIN_NAME);
ConfigurationDefinition configDef = type.getResourceConfigurationDefinition();
return configDef;
- }
-
-
- public static Configuration componentToConfiguration(PluginContainer container,Components component,String key,AugeasTree tree) throws UnitTestException{
- ConfigurationDefinition def = getConfigurationDefinition(container,component);
- AugeasNode node = AugeasNodeSearch.findNodeById(tree.getRootNode(), key);
- ApacheAugeasMapping map = new ApacheAugeasMapping(tree);
- Configuration config = map.updateConfiguration(node, def);
- return config;
- }
+ }
+
+ public static Configuration componentToConfiguration(PluginContainer container, Components component, String key,
+ AugeasTree tree) throws UnitTestException {
+ ConfigurationDefinition def = getConfigurationDefinition(container, component);
+ AugeasNode node = AugeasNodeSearch.findNodeById(tree.getRootNode(), key);
+ ApacheAugeasMapping map = new ApacheAugeasMapping(tree);
+ Configuration config = map.updateConfiguration(node, def);
+ return config;
+ }
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockApacheBinaryInfo.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockApacheBinaryInfo.java
index adb5ac8..5e434e5 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockApacheBinaryInfo.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockApacheBinaryInfo.java
@@ -38,70 +38,70 @@ public class MockApacheBinaryInfo extends ApacheBinaryInfo {
private String mpm;
private String root;
private String version;
-
+
public MockApacheBinaryInfo() {
super(null);
}
-
+
@Override
public String getBinaryPath() {
return binaryPath;
}
-
+
public void setBinaryPath(String path) {
this.binaryPath = path;
}
-
+
@Override
public String getBuilt() {
return built;
}
-
+
public void setBuilt(String built) {
this.built = built;
}
-
+
@Override
public Set<String> getCompiledInDefines() {
return defines;
}
-
+
public void setCompiledInDefines(Set<String> defines) {
this.defines = defines;
}
-
+
@Override
public Set<String> getCompiledInModules() {
return modules;
}
-
+
public void setCompiledInModules(Set<String> modules) {
this.modules = modules;
}
-
+
@Override
public String getCtl() {
return configFile;
}
-
+
public void setCtl(String ctl) {
this.configFile = ctl;
}
-
+
@Override
public long getLastModified() {
return lastModified;
}
-
+
public void setLastModified(long lastModified) {
this.lastModified = lastModified;
}
-
+
@Override
public String getMpm() {
return mpm;
}
-
+
public void setMpm(String mpm) {
this.mpm = mpm;
}
diff --git a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockProcessInfo.java b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockProcessInfo.java
index 2832ce2..b1aac7a 100644
--- a/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockProcessInfo.java
+++ b/modules/plugins/apache/src/test/java/org/rhq/plugins/apache/util/MockProcessInfo.java
@@ -30,7 +30,7 @@ public class MockProcessInfo extends ProcessInfo {
private long pid;
private String[] commandLine;
-
+
@Override
public long getPid() {
return pid;
@@ -39,12 +39,12 @@ public class MockProcessInfo extends ProcessInfo {
public void setPid(long pid) {
this.pid = pid;
}
-
+
@Override
public String[] getCommandLine() {
return commandLine;
}
-
+
public void setCommandLine(String[] commandLine) {
this.commandLine = commandLine;
}
commit 2007f75d4be72277f3ac62e81ee626b283c0f800
Author: Lukas Krejci <lkrejci(a)redhat.com>
Date: Tue Mar 27 14:52:59 2012 +0200
[BZ 786416 - Map configuration properties not shown in correct order]
Apache configuration mapping now uses the correct method that returns
the child property definitions in order.
diff --git a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
index fcf0689..1381861 100644
--- a/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
+++ b/modules/plugins/apache/src/main/java/org/rhq/plugins/apache/augeas/mappingImpl/MappingToAugeasParamPerMap.java
@@ -91,9 +91,9 @@ public class MappingToAugeasParamPerMap extends ConfigurationToAugeasApacheBase{
StringBuffer param= new StringBuffer();
for (List<PropertyMap> directive: map){
for (PropertyMap propMap : directive){
- for (String propDefMap : memberPropDef.getMap().keySet())
+ for (PropertyDefinition propDefMap : memberPropDef.getPropertyDefinitions())
{//for (Property propVal : propMap.getMap().values()){
- Property propVal = propMap.get(propDefMap);
+ Property propVal = propMap.get(propDefMap.getName());
if (propVal!=null)
if (!propVal.getName().equals("_index")){
param.append(" "+((PropertySimple) propVal).getStringValue());
commit 4600e41322da9478628a4c1191c235b03afee35b
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 23:32:33 2012 -0400
[BZ 807008] use server baseDir as Resource key for both standalone and host controller server Resources (https://bugzilla.redhat.com/show_bug.cgi?id=807008); extract two subclasses from BaseProcessDiscovery - StandaloneASDiscovery and HostControllerDiscovery - the former discovers standalone instances and the latter discovers host controller instances; add two new plugin config props - homeDir and configDir (the previously existing baseDir prop is now set to the baseDir, rather than the homeDir)
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7Mode.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7Mode.java
index a98e13c..75ccf30 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7Mode.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7Mode.java
@@ -61,4 +61,5 @@ public enum AS7Mode {
public String getConfigPropertyName() {
return configPropertyName;
}
+
}
\ No newline at end of file
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index 0bf4961..8206c61 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -34,6 +34,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
+import org.rhq.core.pluginapi.util.FileUtils;
import org.rhq.core.system.ProcessInfo;
/**
@@ -42,8 +43,10 @@ import org.rhq.core.system.ProcessInfo;
* @author Heiko W. Rupp
*/
public class AbstractBaseDiscovery {
- static final String DORG_JBOSS_BOOT_LOG_FILE = "-Dorg.jboss.boot.log.file=";
- private static final String DJBOSS_SERVER_HOME_DIR = "-Djboss.home.dir";
+
+ static final String BOOT_LOG_FILE_SYSPROP = "org.jboss.boot.log.file";
+ private static final String HOME_DIR_SYSPROP = "jboss.home.dir";
+
static final int DEFAULT_MGMT_PORT = 9990;
private static final String JBOSS_AS_PREFIX = "jboss-as-";
static final String CALL_READ_STANDALONE_OR_HOST_XML_FIRST = "hostXml is null. You need to call 'readStandaloneOrHostXml' first.";
@@ -62,18 +65,6 @@ public class AbstractBaseDiscovery {
}
}
- /**
- * Read the host.xml or standalone.xml file depending on isDomainMode. If isDomainMode is true,
- * host.xml is read, otherwise standalone.xml.
- * The xml file content is stored in the variable hostXml for future use.
- * @param processInfo Process info to determine the base file location
- * @param isDomainMode Indicates if host.xml should be read (true) or standalone.xml (false)
- */
- protected void readStandaloneOrHostXml(ProcessInfo processInfo, boolean isDomainMode) {
- String hostXmlFile = getHostXmlFileLocation(processInfo, isDomainMode);
- readStandaloneOrHostXmlFromFile(hostXmlFile);
- }
-
protected void readStandaloneOrHostXmlFromFile(String hostXmlFile) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
@@ -90,36 +81,20 @@ public class AbstractBaseDiscovery {
}
/**
- * Determine the server home (=base) directory by parsing the passed command line
- * @param commandLine command line arguments of the process
- * @return The home dir if found or empty string otherwise
- */
- String getHomeDirFromCommandLine(String[] commandLine) {
- for (String line : commandLine) {
- if (line.startsWith(DJBOSS_SERVER_HOME_DIR))
- return line.substring(DJBOSS_SERVER_HOME_DIR.length() + 1);
- }
- return "";
- }
-
- /**
* Determine the location of the boot log file of the server by parsing the command line
* @param commandLine command line arguments of the process
* @return The log file location or empty string otherwise
*/
+ //-Dorg.jboss.boot.log.file=/devel/jbas7/jboss-as/build/target/jboss-7.0.0.Alpha2/domain/log/server-manager/boot.log
+ //-Dlogging.configuration=file:/devel/jbas7/jboss-as/build/target/jboss-7.0.0.Alpha2/domain/configuration/logging.properties
String getLogFileFromCommandLine(String[] commandLine) {
-
- for (String line : commandLine) {
- if (line.startsWith(DORG_JBOSS_BOOT_LOG_FILE))
- return line.substring(DORG_JBOSS_BOOT_LOG_FILE.length());
- }
- return "";
+ return getSystemPropertyFromCommandLine(commandLine, BOOT_LOG_FILE_SYSPROP, "");
}
/**
* Try to obtain the management IP and port from the already parsed host.xml or standalone.xml
* @return an Object containing host and port
- * @see #readStandaloneOrHostXml(org.rhq.core.system.ProcessInfo, boolean) on how to obtain the parsed xml
+ * @see #readStandaloneOrHostXmlFromFile(String) for how to obtain the parsed xml
* @param commandLine Command line arguments of the process to
*/
protected HostPort getManagementPortFromHostXml(String[] commandLine) {
@@ -260,7 +235,7 @@ public class AbstractBaseDiscovery {
* Try to obtain the domain controller's location from looking at host.xml
* @return host and port of the domain controller
*/
- protected HostPort getDomainControllerFromHostXml() {
+ protected HostPort getHostPortFromHostXml() {
if (hostXml == null)
throw new IllegalArgumentException(CALL_READ_STANDALONE_OR_HOST_XML_FIRST);
@@ -317,30 +292,10 @@ public class AbstractBaseDiscovery {
return fullName;
}
- /**
- * Get the location of the host definition file (host.xml in domain mode, standalone.xml
- * in standalone mode.
- * @param processInfo ProcessInfo structure containing the ENV variables
- * @param isDomain Are we looking for host.xml (=isDomain) or not
- * @return The path to the definition file.
- */
- protected String getHostXmlFileLocation(ProcessInfo processInfo, boolean isDomain) {
-
- String home = processInfo.getEnvironmentVariable("jboss.home.dir");
- if (home == null)
- home = getHomeDirFromCommandLine(processInfo.getCommandLine());
- StringBuilder builder = new StringBuilder(home);
- if (isDomain)
- builder.append(File.separator).append(AS7Mode.DOMAIN.getBaseDir());
- else
- builder.append(File.separator).append(AS7Mode.STANDALONE.getBaseDir());
- builder.append(File.separator).append("configuration");
- if (isDomain)
- builder.append(File.separator).append(AS7Mode.HOST.getDefaultXmlFile());
- else
- builder.append(File.separator).append(AS7Mode.STANDALONE.getDefaultXmlFile());
- return builder.toString();
-
+ protected File getHomeDir(ProcessInfo processInfo) {
+ String home = getSystemPropertyFromCommandLine(processInfo.getCommandLine(), HOME_DIR_SYSPROP,
+ processInfo.getEnvironmentVariable("JBOSS_HOME"));
+ return new File(FileUtils.getCanonicalPath(home));
}
protected String determineServerVersionFromHomeDir(String homeDir) {
@@ -382,6 +337,24 @@ public class AbstractBaseDiscovery {
}
}
+ protected static String getSystemPropertyFromCommandLine(String[] commandLine, String systemPropertyName) {
+ return getSystemPropertyFromCommandLine(commandLine, systemPropertyName, null);
+ }
+
+ protected static String getSystemPropertyFromCommandLine(String[] commandLine, String systemPropertyName,
+ String defaultValue) {
+ for (String arg : commandLine) {
+ String prefix = "-D" + systemPropertyName;
+ String prefixWithEqualsSign = prefix + "=";
+ if (arg.startsWith(prefixWithEqualsSign)) {
+ return arg.substring(prefixWithEqualsSign.length());
+ } else if (arg.equals(prefix)) {
+ return "";
+ }
+ }
+ return defaultValue;
+ }
+
/**
* Helper class that holds information about the host,port tuple
*/
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 6b73ad3..c382a28 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
- * Copyright (C) 2005-2011 Red Hat, Inc.
+ * Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -46,204 +46,169 @@ import org.rhq.core.pluginapi.inventory.ManualAddFacet;
import org.rhq.core.pluginapi.inventory.ProcessScanResult;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryComponent;
import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.core.pluginapi.util.FileUtils;
import org.rhq.core.system.ProcessInfo;
import org.rhq.modules.plugins.jbossas7.json.Operation;
import org.rhq.modules.plugins.jbossas7.json.ReadAttribute;
import org.rhq.modules.plugins.jbossas7.json.Result;
/**
- * Discovery class
+ * Abstract base discovery component for the two server types - "JBossAS7 Host Controller" and
+ * "JBossAS7 Standalone Server".
*/
-public class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent, ManualAddFacet
-
-{
- static final String DORG_JBOSS_BOOT_LOG_FILE = "-Dorg.jboss.boot.log.file=";
- private static final String JBOSS_EAP_6 = "JBoss Enterprise Application Platform 6";
- private static final String JBOSS_EDG_6 = "JBoss Enterprise Data Grid 6";
- private static final String JBOSS_EPP_6 = "JBoss Enterprise Portal Platform 6";
- private static final String JBOSS_SOA_6 = "JBoss Service Oriented Architecture Platform 6";
- private static final String AS7 = "AS7";
+public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery implements ResourceDiscoveryComponent, ManualAddFacet {
+
+ protected static final String JBOSS_EAP_6 = "JBoss Enterprise Application Platform 6";
+ protected static final String JBOSS_EDG_6 = "JBoss Enterprise Data Grid 6";
+ protected static final String JBOSS_EPP_6 = "JBoss Enterprise Portal Platform 6";
+ protected static final String JBOSS_SOA_6 = "JBoss Service Oriented Architecture Platform 6";
+ protected static final String AS7 = "AS7";
+
+ private static final String SOCKET_BINDING_PORT_OFFSET_SYSPROP = "jboss.socket.binding.port-offset";
+
private final Log log = LogFactory.getLog(this.getClass());
- /**
- * Run the auto-discovery
- */
+ // Auto-discover running AS7 instances.
public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext discoveryContext) throws Exception {
Set<DiscoveredResourceDetails> discoveredResources = new HashSet<DiscoveredResourceDetails>();
List<ProcessScanResult> scans = discoveryContext.getAutoDiscoveredProcesses();
-
for (ProcessScanResult psr : scans) {
-
try {
- Configuration config = discoveryContext.getDefaultPluginConfiguration();
- // IF SE, then look at domain/configuration/host.xml <management interface="default" port="9990
- // for management port
- String[] commandLine = psr.getProcessInfo().getCommandLine();
- String serverNameFull;
- String serverName;
- String psName = psr.getProcessScan().getName();
- String description;
- String homeDir = getHomeDirFromCommandLine(commandLine);
- String version = determineServerVersionFromHomeDir(homeDir);
- boolean isEAP = false;
- boolean isJDG = false;
-
- //retrieve specific boot log file. Override for Standalone as server.log is more appropriate
- String bootLogFile = getLogFileFromCommandLine(commandLine);
- String logFile = bootLogFile;
-
- if (homeDir.contains("eap")) {
- isEAP = true;
- }
- if (homeDir.contains("edg")) {
- isJDG = true;
- }
+ DiscoveredResourceDetails details = buildResourceDetails(discoveryContext, psr);
+ discoveredResources.add(details);
+ log.info("Discovered new " + discoveryContext.getResourceType().getName() + " Resource with key ["
+ + details.getResourceKey() + "].");
+ } catch (Exception e) {
+ log.warn("Discovery for a " + discoveryContext.getResourceType().getName()
+ + " Resource failed for process " + psr + ": " + e);
+ }
+ }
- if (psName.equals("HostController")) {
-
- readStandaloneOrHostXml(psr.getProcessInfo(), true);
- HostPort hp = getDomainControllerFromHostXml();
- if (hp.isLocal) {
- serverName = "DomainController"; // TODO make more unique
- serverNameFull = "DomainController";
- if (isEAP)
- description = "Domain controller for a " + JBOSS_EAP_6 + " domain";
- else
- description = "Domain controller for an " + AS7 + " domain";
- } else {
- serverName = "HostController"; // TODO make more unique
- serverNameFull = "HostController";
- if (isEAP)
- description = "Host controller for a " + JBOSS_EAP_6 + " host";
- else
- description = "Host controller for an " + AS7 + " host";
-
- }
-
- config.put(new PropertySimple("baseDir", homeDir));
- config.put(new PropertySimple("startScript", AS7Mode.DOMAIN.getStartScript()));
- String host = findHost(psr.getProcessInfo(), true);
- config.put(new PropertySimple("domainHost", host));
-
- fillUserPassFromFile(config, AS7Mode.DOMAIN, homeDir);
-
- // provide running config
- String domainConfig = getServerConfigFromCommandLine(commandLine, AS7Mode.DOMAIN);
- String hostConfig = getServerConfigFromCommandLine(commandLine, AS7Mode.HOST);
- config.put(new PropertySimple("domainConfig", domainConfig));
- config.put(new PropertySimple("hostConfig", hostConfig));
-
- } else { // Standalone server
- serverNameFull = homeDir;
-
- if (isEAP)
- description = "Standalone " + JBOSS_EAP_6 + " server";
- else if (isJDG)
- description = "Standalone " + JBOSS_EDG_6 + " server";
- else
- description = "Standalone " + AS7 + " server";
-
- readStandaloneOrHostXml(psr.getProcessInfo(), false);
- if (serverNameFull.isEmpty()) {
- // Try to obtain the server name
- // -Dorg.jboss.boot.log.file=domain/servers/server-one/log/boot.log
- // This is a hack until I know a better way to do so.
- //XXX hardcoded separators?
- String tmp = getLogFileFromCommandLine(commandLine);
- int i = tmp.indexOf("servers" + File.separator);
- tmp = tmp.substring(i + 8);
- tmp = tmp.substring(0, tmp.indexOf(File.separator));
- serverNameFull = tmp;
-
- }
- String host = findHost(psr.getProcessInfo(), false);
- config.put(new PropertySimple("domainHost", host));
-
- config.put(new PropertySimple("baseDir", serverNameFull));
-
- serverName = findHostName();
- if (serverName.isEmpty())
- serverName = serverNameFull;
-
- String serverConfig = getServerConfigFromCommandLine(commandLine, AS7Mode.STANDALONE);
- config.put(new PropertySimple("config", serverConfig));
- config.put(new PropertySimple("startScript", AS7Mode.STANDALONE.getStartScript()));
-
- fillUserPassFromFile(config, AS7Mode.STANDALONE, serverNameFull);
-
- //preload server.log file for event log monitoring
- logFile = bootLogFile.substring(0, bootLogFile.lastIndexOf(File.separator)) + File.separator
- + "server.log";
- }
+ return discoveredResources;
+ }
- if (isEAP) {
- serverName = EAP_PREFIX + serverName;
- version = EAP_PREFIX + version;
- } else if (isJDG) {
- serverName = JDG_PREFIX + serverName;
- version = JDG_PREFIX + version;
+ protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext, ProcessScanResult psr) {
+ Configuration pluginConfig = discoveryContext.getDefaultPluginConfiguration();
+ // IF SE, then look at domain/configuration/host.xml <management interface="default" port="9990
+ // for management port
+ ProcessInfo process = psr.getProcessInfo();
+ String[] commandLine = process.getCommandLine();
+ String homeDir = getHomeDir(process).getPath();
+ String version = determineServerVersionFromHomeDir(homeDir);
+
+ File baseDir = getBaseDir(process);
+ String configName = baseDir.getName();
+ String key = baseDir.getPath();
+ readStandaloneOrHostXmlFromFile(getHostXmlFile(process).getPath()); // this sets this.hostXml
+ HostPort hostPort = getHostPortFromHostXml();
+
+ // TODO: Move this stuff to a ProductType enum.
+ String productTypeName;
+ String productTypePrefix;
+ if (homeDir.contains("eap")) {
+ productTypeName = JBOSS_EAP_6;
+ productTypePrefix = EAP;
+ } else if (homeDir.contains("edg")) {
+ productTypeName = JBOSS_EDG_6;
+ productTypePrefix = JDG;
+ } else {
+ productTypeName = AS7;
+ productTypePrefix = null;
+ }
- }
+ String name = buildDefaultResourceName(hostPort, configName, productTypeName);
+ String description = buildDefaultResourceDescription(hostPort, productTypeName);
+ if (productTypePrefix != null) {
+ name = productTypePrefix + " " + name;
+ version = productTypePrefix + " " + version;
+ }
- initLogEventSourcesConfigProp(logFile, config);
+ pluginConfig.put(new PropertySimple("homeDir", homeDir));
+ pluginConfig.put(new PropertySimple("baseDir", baseDir));
+ pluginConfig.put(new PropertySimple("configDir", getConfigDir(process)));
+ pluginConfig.put(new PropertySimple("startScript", getMode().getStartScript()));
+ pluginConfig.put(new PropertySimple("domainHost", findHost(getHostXmlFile(process))));
+ fillUserPassFromFile(pluginConfig, getMode(), homeDir);
+ String logFile = getLogFile(process).getAbsolutePath();
+ initLogEventSourcesConfigProp(logFile, pluginConfig);
+ HostPort managementHostPort = getManagementPortFromHostXml(commandLine);
+ pluginConfig.put(new PropertySimple("hostname", managementHostPort.host));
+ pluginConfig.put(new PropertySimple("port", managementHostPort.port));
+ pluginConfig.put(new PropertySimple("realm", getManagementSecurityRealmFromHostXml()));
+
+ ProductInfo productInfo = new ProductInfo(managementHostPort.host, pluginConfig.getSimpleValue("user", null),
+ pluginConfig.getSimpleValue("password", null), managementHostPort.port);
+ productInfo = productInfo.getFromRemote();
+ if (productInfo.fromRemote) {
+ version = productInfo.productName + " " + productInfo.productVersion;
+ name = productInfo.productName + " " + productInfo.serverName;
+ String tmp = getServerDescr(productInfo.getProductName());
+ description = "Standalone " + tmp + " server";
+ }
- HostPort managementPort = getManagementPortFromHostXml(commandLine);
- if (!psName.equals("HostController")) { // standalone
- managementPort = checkForSocketBindingOffset(managementPort, commandLine);
- }
- config.put(new PropertySimple("hostname", managementPort.host));
- config.put(new PropertySimple("port", managementPort.port));
- config.put(new PropertySimple("realm", getManagementSecurityRealmFromHostXml()));
-
- ProductInfo productInfo = new ProductInfo(managementPort.host, config.getSimpleValue("user", null),
- config.getSimpleValue("password", null), managementPort.port);
- productInfo = productInfo.getFromRemote();
- if (productInfo.fromRemote) {
- version = productInfo.productName + " " + productInfo.productVersion;
- serverName = productInfo.productName + " " + productInfo.serverName;
- String tmp = getServerDescr(productInfo.getProductName());
- description = "Standalone " + tmp + " server";
- }
+ // String javaClazz = psr.getProcessInfo().getName();
+
+ /*
+* We'll connect to the discovered VM on the local host, so set the jmx connection
+* properties accordingly. This may only work on JDK6+, but then JDK5 is deprecated
+* anyway.
+*/
+ // config.put(new PropertySimple(JMXDiscoveryComponent.COMMAND_LINE_CONFIG_PROPERTY,
+ // javaClazz));
+ // config.put(new PropertySimple(JMXDiscoveryComponent.CONNECTION_TYPE,
+ // LocalVMTypeDescriptor.class.getName()));
+ //
+ // // TODO vmid will change when the detected server is bounced - how do we follow this?
+ // config.put(new PropertySimple(JMXDiscoveryComponent.VMID_CONFIG_PROPERTY,psr.getProcessInfo().getPid()));
+
+ return new DiscoveredResourceDetails(discoveryContext.getResourceType(), key, name, version, description,
+ pluginConfig, process);
+ }
- // String javaClazz = psr.getProcessInfo().getName();
-
- /*
- * We'll connect to the discovered VM on the local host, so set the jmx connection
- * properties accordingly. This may only work on JDK6+, but then JDK5 is deprecated
- * anyway.
- */
- // config.put(new PropertySimple(JMXDiscoveryComponent.COMMAND_LINE_CONFIG_PROPERTY,
- // javaClazz));
- // config.put(new PropertySimple(JMXDiscoveryComponent.CONNECTION_TYPE,
- // LocalVMTypeDescriptor.class.getName()));
- //
- // // TODO vmid will change when the detected server is bounced - how do we follow this?
- // config.put(new PropertySimple(JMXDiscoveryComponent.VMID_CONFIG_PROPERTY,psr.getProcessInfo().getPid()));
-
- DiscoveredResourceDetails detail = new DiscoveredResourceDetails(discoveryContext.getResourceType(), // ResourceType
- serverNameFull, // key TODO distinguish per domain?
- serverName, // Name
- version, description, // Description
- config, psr.getProcessInfo());
-
- // Add to return values
- discoveredResources.add(detail);
- log.info("Discovered new ... " + discoveryContext.getResourceType() + ", " + serverNameFull);
- } catch (Exception e) {
- log.warn("Discovery for a " + discoveryContext.getResourceType() + " failed for process " + psr + " :"
- + e.getMessage());
- }
- }
+ protected File getBaseDir(ProcessInfo process) {
+ String baseDirString = getSystemPropertyFromCommandLine(process.getCommandLine(),
+ getBaseDirSystemPropertyName());
+ File baseDir = (baseDirString != null) ? new File(FileUtils.getCanonicalPath(baseDirString)) :
+ new File(getHomeDir(process), getDefaultBaseDirName());
+ return baseDir;
+ }
- return discoveredResources;
+ protected File getConfigDir(ProcessInfo process) {
+ String configDirString = getSystemPropertyFromCommandLine(process.getCommandLine(),
+ getConfigDirSystemPropertyName());
+ File configDir = (configDirString != null) ? new File(FileUtils.getCanonicalPath(configDirString)) :
+ new File(getBaseDir(process), getDefaultConfigDirName());
+ return configDir;
+ }
+ protected File getHostXmlFile(ProcessInfo process) {
+ return new File(getConfigDir(process), getHostXmlFileName());
}
- private HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
+ protected String getDefaultConfigDirName() {
+ return "configuration";
+ }
+
+ protected abstract AS7Mode getMode();
+
+ protected abstract File getLogFile(ProcessInfo process);
+ protected abstract String getBaseDirSystemPropertyName();
+
+ protected abstract String getConfigDirSystemPropertyName();
+
+ protected abstract String getDefaultBaseDirName();
+
+ protected abstract String getHostXmlFileName();
+
+ protected abstract String buildDefaultResourceName(HostPort hostPort, String configName, String productTypeName);
+
+ protected abstract String buildDefaultResourceDescription(HostPort hostPort, String productTypeName);
+
+ protected HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
for (String line : commandLine) {
- if (line.contains("jboss.socket.binding.port-offset")) {
+ if (line.contains(SOCKET_BINDING_PORT_OFFSET_SYSPROP)) {
String tmp = line.substring(line.indexOf('=')+1);
Integer offset = Integer.valueOf(tmp);
managementPort.port+=offset;
@@ -254,6 +219,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
return managementPort;
}
+ // TODO: Move this to a ProductType enum.
private String getServerDescr(String productName) {
if (productName.equals("EAP"))
return JBOSS_EAP_6;
@@ -266,14 +232,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
return AS7;
}
- /**
- * Allow to manually add a (remote) AS7
- * @param pluginConfiguration the plugin configuration that describes how to discover the Resource being manually
- * added
- * @param context
- * @return
- * @throws InvalidPluginConfigurationException
- */
+ // Manually add a (remote) AS7 instance.
@Override
public DiscoveredResourceDetails discoverResource(Configuration pluginConfiguration,
ResourceDiscoveryContext context) throws InvalidPluginConfigurationException {
@@ -293,6 +252,8 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
String productVersion = productInfo.getProductVersion();
String resourceKey = hostname + ":" + portS + ":" + productName;
+
+ // TODO: Move this stuff to a ProductType enum.
String description;
if (productName.contains("EAP")) {
description = "Standalone JBoss Enterprise Application Platform server";
@@ -346,10 +307,10 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
continue;
// found a candidate
String user = line.substring(0, line.indexOf("="));
- String pass = line.substring(line.indexOf("=") + 1);
- config.put(new PropertySimple("user", user));
- // config.put(new PropertySimple("password", pass)); // this is now hashed, so no point in supplying it
+ config.put(new PropertySimple("user", user));
+ // String pass = line.substring(line.indexOf("=") + 1);
+ // config.put(new PropertySimple("password", pass)); // this is now hashed, so no point in supplying it
}
} catch (IOException e) {
log.error(e.getMessage());
@@ -361,11 +322,9 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
// empty
}
}
-
}
- private String findHost(ProcessInfo processInfo, boolean isDomain) {
- String hostXmlFile = getHostXmlFileLocation(processInfo, isDomain);
+ private String findHost(File hostXmlFile) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String hostName = null;
try {
@@ -391,7 +350,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
* @param mode mode and thus command line switch to look for
* @return the config or the default for the mode if no config was passed on the command line.
*/
- private String getServerConfigFromCommandLine(String[] commandLine, AS7Mode mode) {
+ protected String getServerConfigFromCommandLine(String[] commandLine, AS7Mode mode) {
String configArg = mode.getConfigArg();
for (int index = 0; index < commandLine.length; index++) {
@@ -407,20 +366,7 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
return mode.getDefaultXmlFile();
}
- //-Dorg.jboss.boot.log.file=/devel/jbas7/jboss-as/build/target/jboss-7.0.0.Alpha2/domain/log/server-manager/boot.log
- //-Dlogging.configuration=file:/devel/jbas7/jboss-as/build/target/jboss-7.0.0.Alpha2/domain/configuration/logging.properties
-
- String getLogFileFromCommandLine(String[] commandLine) {
-
- for (String line : commandLine) {
- if (line.startsWith(DORG_JBOSS_BOOT_LOG_FILE))
- return line.substring(DORG_JBOSS_BOOT_LOG_FILE.length());
- }
- return "";
- }
-
private void initLogEventSourcesConfigProp(String fileName, Configuration pluginConfiguration) {
-
PropertyList logEventSources = pluginConfiguration
.getList(LogFileEventResourceComponentHelper.LOG_EVENT_SOURCES_CONFIG_PROP);
@@ -495,4 +441,5 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
+ '}';
}
}
+
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
index 68044ae..8644b71 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
@@ -257,8 +257,8 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
}
protected OperationResult installManagementUser(Configuration parameters, Configuration pluginConfig, AS7Mode mode) {
- String user = parameters.getSimpleValue("user","");
- String password = parameters.getSimpleValue("password","");
+ String user = parameters.getSimpleValue("user", "");
+ String password = parameters.getSimpleValue("password", "");
OperationResult result = new OperationResult();
@@ -273,21 +273,30 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
return result;
}
- String baseDir = pluginConfig.getSimpleValue("baseDir","");
- if (baseDir.isEmpty()) {
- result.setErrorMessage("No baseDir found, can not continue");
+ String homeDir = pluginConfig.getSimpleValue("homeDir", "");
+ if (homeDir.isEmpty()) {
+ result.setErrorMessage("No homeDir found, can not continue");
return result;
}
- String standaloneXmlFile = pluginConfig.getSimpleValue("config",mode.getDefaultXmlFile());
-
- String standaloneXml = baseDir + File.separator + mode.getBaseDir() + File.separator + "configuration" + File.separator + standaloneXmlFile;
- AbstractBaseDiscovery abd = new AbstractBaseDiscovery();
- abd.readStandaloneOrHostXmlFromFile(standaloneXml);
-
- String realm = pluginConfig.getSimpleValue("realm","ManagementRealm");
- String propertiesFilePath = abd.getSecurityPropertyFileFromHostXml(baseDir,mode, realm);
+ String configFile;
+ BaseProcessDiscovery processDiscovery;
+ switch (mode) {
+ case STANDALONE:
+ processDiscovery = new StandaloneASDiscovery();
+ configFile = pluginConfig.getSimpleValue("config", null);
+ break;
+ case HOST:
+ processDiscovery = new HostControllerDiscovery();
+ configFile = pluginConfig.getSimpleValue("hostConfig", null);
+ break;
+ default:
+ throw new IllegalArgumentException("Unsupported mode: " + mode);
+ }
+ processDiscovery.readStandaloneOrHostXmlFromFile(configFile);
+ String realm = pluginConfig.getSimpleValue("realm", "ManagementRealm");
+ String propertiesFilePath = processDiscovery.getSecurityPropertyFileFromHostXml(homeDir, mode, realm);
Properties p = new Properties();
try {
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
new file mode 100644
index 0000000..c3acc94
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
@@ -0,0 +1,95 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.modules.plugins.jbossas7;
+
+import java.io.File;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
+import org.rhq.core.pluginapi.inventory.ProcessScanResult;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.core.system.ProcessInfo;
+
+/**
+ * Discovery component for "JBossAS7 Host Controller" Resources.
+ *
+ * @author Ian Springer
+ */
+public class HostControllerDiscovery extends BaseProcessDiscovery {
+
+ private static final String DOMAIN_BASE_DIR_SYSPROP = "jboss.domain.base.dir";
+ private static final String DOMAIN_CONFIG_DIR_SYSPROP = "jboss.domain.config.dir";
+
+ @Override
+ protected AS7Mode getMode() {
+ return AS7Mode.DOMAIN;
+ }
+
+ @Override
+ protected String getBaseDirSystemPropertyName() {
+ return DOMAIN_BASE_DIR_SYSPROP;
+ }
+
+ @Override
+ protected String getConfigDirSystemPropertyName() {
+ return DOMAIN_CONFIG_DIR_SYSPROP;
+ }
+
+ @Override
+ protected String getDefaultBaseDirName() {
+ return "domain";
+ }
+
+ @Override
+ protected String getHostXmlFileName() {
+ return "host.xml";
+ }
+
+ @Override
+ protected String buildDefaultResourceName(HostPort hostPort, String configName, String productTypeName) {
+ String suffix = (hostPort.isLocal) ? "Domain Controller" : "Host Controller";
+ return configName + " " + productTypeName + " " + suffix;
+ }
+
+ @Override
+ protected String buildDefaultResourceDescription(HostPort hostPort, String productTypeName) {
+ String prefix = (hostPort.isLocal) ? "Domain controller" : "Host controller";
+ String suffix = (hostPort.isLocal) ? "domain" : "host";
+ return prefix + " for a " + productTypeName + " " + suffix;
+ }
+
+ @Override
+ protected File getLogFile(ProcessInfo process) {
+ String bootLogFile = getLogFileFromCommandLine(process.getCommandLine());
+ return new File(bootLogFile);
+ }
+
+ @Override
+ protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
+ ProcessScanResult psr) {
+ DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
+ Configuration pluginConfig = details.getPluginConfiguration();
+ String domainConfig = getServerConfigFromCommandLine(psr.getProcessInfo().getCommandLine(), getMode());
+ pluginConfig.put(new PropertySimple("domainConfig", domainConfig));
+ pluginConfig.put(new PropertySimple("hostConfig", getHostXmlFile(psr.getProcessInfo())));
+ return details;
+ }
+
+}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
new file mode 100644
index 0000000..8c4f9e7
--- /dev/null
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
@@ -0,0 +1,98 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2012 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.modules.plugins.jbossas7;
+
+import java.io.File;
+
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.configuration.PropertySimple;
+import org.rhq.core.pluginapi.inventory.DiscoveredResourceDetails;
+import org.rhq.core.pluginapi.inventory.ProcessScanResult;
+import org.rhq.core.pluginapi.inventory.ResourceDiscoveryContext;
+import org.rhq.core.system.ProcessInfo;
+
+/**
+ * Discovery component for "JBossAS7 Standalone Server" Resources.
+ *
+ * @author Ian Springer
+ */
+public class StandaloneASDiscovery extends BaseProcessDiscovery {
+
+ private static final String SERVER_BASE_DIR_SYSPROP = "jboss.server.base.dir";
+ private static final String SERVER_CONFIG_DIR_SYSPROP = "jboss.server.config.dir";
+
+ @Override
+ protected AS7Mode getMode() {
+ return AS7Mode.STANDALONE;
+ }
+
+ @Override
+ protected String getBaseDirSystemPropertyName() {
+ return SERVER_BASE_DIR_SYSPROP;
+ }
+
+ @Override
+ protected String getConfigDirSystemPropertyName() {
+ return SERVER_CONFIG_DIR_SYSPROP;
+ }
+
+ @Override
+ protected String getDefaultBaseDirName() {
+ return "standalone";
+ }
+
+ @Override
+ protected String getHostXmlFileName() {
+ return "standalone.xml";
+ }
+
+ @Override
+ protected String buildDefaultResourceName(HostPort hostPort, String configName, String productTypeName) {
+ String hostName = findHostName();
+ return (hostName == null || hostName.isEmpty()) ? configName : configName + " (" + hostName + ")";
+ }
+
+ @Override
+ protected String buildDefaultResourceDescription(HostPort hostPort, String productTypeName) {
+ return "Standalone " + productTypeName + " server";
+ }
+
+ @Override
+ protected File getLogFile(ProcessInfo process) {
+ String bootLogFile = getLogFileFromCommandLine(process.getCommandLine());
+ File logDir = new File(bootLogFile).getParentFile();
+ return new File(logDir, "server.log");
+ }
+
+ @Override
+ protected HostPort getManagementPortFromHostXml(String[] commandLine) {
+ HostPort managementPort = super.getManagementPortFromHostXml(commandLine);
+ return checkForSocketBindingOffset(managementPort, commandLine);
+ }
+
+ @Override
+ protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
+ ProcessScanResult psr) {
+ DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
+ Configuration pluginConfig = details.getPluginConfiguration();
+ pluginConfig.put(new PropertySimple("config", getHostXmlFile(psr.getProcessInfo())));
+ return details;
+ }
+
+}
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 0a3ed99..ca285ef 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
@@ -62,7 +62,7 @@
-->
<server name="JBossAS7 Host Controller"
- discovery="BaseProcessDiscovery"
+ discovery="HostControllerDiscovery"
class="HostControllerComponent"
description="Domain controller (delegate) for this host"
>
@@ -74,12 +74,14 @@
<c:simple-property name="password" type="password" default="rhqadmin" description="Password for the management user" required="false"/>
<c:simple-property name="domainConfig" type="string" default="domain.xml" description="Running configuration (domain part)" displayName="Domain Configuration"/>
<c:simple-property name="hostConfig" type="string" default="host.xml" description="Running configuration (host part)" displayName="Host Configuration"/>
- <c:simple-property name="baseDir" type="file" description="Base directory of the server installation" displayName="Base directory" readOnly="true" required="false"/>
+ <c:simple-property name="homeDir" type="file" description="Root directory of the server installation" displayName="Home Directory" readOnly="true" required="true"/>
+ <c:simple-property name="baseDir" type="file" description="Base directory for server content" displayName="Base Directory" readOnly="true" required="false"/>
+ <c:simple-property name="configDir" type="file" description="Base configuration directory" displayName="Configuration Directory" readOnly="true" required="false"/>
<c:simple-property name="startScript" type="file" default="bin/domain.sh" description="Script used to start the server. If the path is not absolute, it is relative to the base directory"/>
<c:simple-property name="javaHomePath" type="file" displayName="JAVA_HOME Path" required="false"
description="The absolute path to a JRE or JDK installation directory containing
- the JVM that should be used to start and shutdown the HostController instance;
- defaults to the home directory of the RHQ agent JRE."/>
+ the JVM that should be used to start and shutdown the HostController instance;
+ defaults to the home directory of the RHQ Agent JRE."/>
<c:simple-property name="domainHost" type="string" readOnly="true" required="false" description="Host name within the AS7 domain"/>
&logSources;
@@ -358,7 +360,7 @@
</server>
<server name="JBossAS7 Standalone Server"
- discovery="BaseProcessDiscovery"
+ discovery="StandaloneASDiscovery"
class="StandaloneASComponent"
description="Standalone AS7 server"
supportsManualAdd="true"
@@ -370,12 +372,14 @@
<c:simple-property name="user" default="rhqadmin" type="string" description="Management user for a secured AS" required="false"/>
<c:simple-property name="password" default="rhqadmin" type="password" description="Password for the management user" required="false"/>
<c:simple-property name="config" type="string" default="standalone.xml" description="Running configuration" displayName="Configuration"/>
- <c:simple-property name="baseDir" type="file" description="Base directory of the server installation" displayName="Base directory" readOnly="true" required="false"/>
+ <c:simple-property name="homeDir" type="file" description="Root directory of the server installation" displayName="Home Directory" readOnly="true" required="true"/>
+ <c:simple-property name="baseDir" type="file" description="Base directory for server content" displayName="Base Directory" readOnly="true" required="false"/>
+ <c:simple-property name="configDir" type="file" description="Base configuration directory" displayName="Configuration Directory" readOnly="true" required="false"/>
<c:simple-property name="startScript" type="file" default="bin/standalone.sh" description="Script used to start the server. If the path is not absolute, it is relative to the base directory"/>
<c:simple-property name="javaHomePath" type="file" displayName="JAVA_HOME Path" required="false"
description="The absolute path to a JRE or JDK installation directory containing
- the JVM that should be used to start and shutdown the JBossAS instance;
- defaults to the home directory of the RHQ agent JRE."/>
+ the JVM that should be used to start and shutdown the JBossAS instance;
+ defaults to the home directory of the RHQ Agent JRE."/>
&logSources;
</plugin-configuration>
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java
index 2fdcdb1..85ae619 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/XmlFileReadingTest.java
@@ -13,7 +13,7 @@ public class XmlFileReadingTest {
public void hostPort70() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new StandaloneASDiscovery();
URL url = getClass().getClassLoader().getResource("standalone70.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
@@ -25,7 +25,7 @@ public class XmlFileReadingTest {
public void hostPort71() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new StandaloneASDiscovery();
URL url = getClass().getClassLoader().getResource("standalone71.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
@@ -38,22 +38,22 @@ public class XmlFileReadingTest {
public void domainController1() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new HostControllerDiscovery();
URL url = getClass().getClassLoader().getResource("host1.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
- AbstractBaseDiscovery.HostPort hp = bd.getDomainControllerFromHostXml();
+ AbstractBaseDiscovery.HostPort hp = bd.getHostPortFromHostXml();
assert hp.isLocal : "DC is not local as expected: " + hp;
}
public void domainController2() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new HostControllerDiscovery();
URL url = getClass().getClassLoader().getResource("host2.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
- AbstractBaseDiscovery.HostPort hp = bd.getDomainControllerFromHostXml();
+ AbstractBaseDiscovery.HostPort hp = bd.getHostPortFromHostXml();
assert "192.168.100.1".equals(hp.host) : "DC is at " + hp.host;
assert hp.port == 9559 : "DC port is at " + hp.port;
}
@@ -62,7 +62,7 @@ public class XmlFileReadingTest {
public void testXpath70() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new StandaloneASDiscovery();
URL url = getClass().getClassLoader().getResource("standalone70.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
@@ -88,7 +88,7 @@ public class XmlFileReadingTest {
public void testXpath71() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new StandaloneASDiscovery();
URL url = getClass().getClassLoader().getResource("standalone71.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
@@ -114,7 +114,7 @@ public class XmlFileReadingTest {
public void testGetRealm() throws Exception {
- BaseProcessDiscovery bd = new BaseProcessDiscovery();
+ BaseProcessDiscovery bd = new StandaloneASDiscovery();
URL url = getClass().getClassLoader().getResource("standalone71.xml");
bd.readStandaloneOrHostXmlFromFile(url.getFile());
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
index d816bab..8a90c8f 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
@@ -59,7 +59,9 @@ public abstract class AbstractServerComponentTest extends AbstractJBossAS7Plugin
getServerResourceKey());
assertNotNull(resource,
- getServerResourceType() + " Resource with key [" + getServerResourceKey() + "] not found in inventory.");
+ getServerResourceType().getName() + " Resource with key [" + getServerResourceKey()
+ + "] not found in inventory - platform child Resources that were discovered: "
+ + inventoryManager.getPlatform().getChildResources());
return resource;
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
index 76330b3..d532225 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
@@ -22,6 +22,7 @@ import org.testng.annotations.Test;
import org.rhq.core.domain.resource.ResourceCategory;
import org.rhq.core.domain.resource.ResourceType;
+import org.rhq.core.pluginapi.util.FileUtils;
import org.rhq.modules.plugins.jbossas7.itest.AbstractServerComponentTest;
import org.rhq.test.arquillian.RunDiscovery;
@@ -34,7 +35,7 @@ import org.rhq.test.arquillian.RunDiscovery;
public class DomainServerComponentTest extends AbstractServerComponentTest {
public static final ResourceType RESOURCE_TYPE = new ResourceType("JBossAS7 Host Controller", PLUGIN_NAME, ResourceCategory.SERVER, null);
- public static final String RESOURCE_KEY = "DomainController";
+ public static final String RESOURCE_KEY = FileUtils.getCanonicalPath(System.getProperty("jboss7.home") + "/domain");
@Override
protected ResourceType getServerResourceType() {
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
index 11ba4b0..a221a27 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
@@ -39,7 +39,7 @@ public class StandaloneServerComponentTest extends AbstractServerComponentTest {
public static final ResourceType RESOURCE_TYPE = new ResourceType("JBossAS7 Standalone Server", PLUGIN_NAME, ResourceCategory.SERVER, null);
// The key of an AS7 Standalone Server Resource is its JBOSS_HOME dir.
- public static final String RESOURCE_KEY = FileUtils.getCanonicalPath(System.getProperty("jboss7.home"));
+ public static final String RESOURCE_KEY = FileUtils.getCanonicalPath(System.getProperty("jboss7.home") + "/standalone");
private static final String RELOAD_OPERATION_NAME = "reload";
private static final String RESTART_OPERATION_NAME = "restart";
commit b645766a8be727d50f01dc8eb861f75c63caf4cc
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 22:58:26 2012 -0400
minor: fix some typos
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HornetQComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HornetQComponent.java
index 7cc2639..c578607 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HornetQComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HornetQComponent.java
@@ -33,11 +33,11 @@ public class HornetQComponent extends BaseComponent {
Configuration rc = report.getResourceConfiguration();
Address targetAddress = new Address(getPath());
- CreationType targeType = CreationType.getForName(targetTypeName);
- if (targeType==null)
+ CreationType targetType = CreationType.getForName(targetTypeName);
+ if (targetType==null)
throw new IllegalArgumentException("Type " + targetTypeName + " not yet supported");
- targetAddress.add(targeType.as7name,resourceName);
+ targetAddress.add(targetType.as7name,resourceName);
List<String> entries;
Operation op;
@@ -55,7 +55,7 @@ public class HornetQComponent extends BaseComponent {
}
op = new Operation("add",targetAddress);
- switch (targeType) {
+ switch (targetType) {
case JMS_QUEUE:
entries = getEntriesPropertyFromConfig(rc);
op.addAdditionalProperty("entries",entries);
@@ -233,18 +233,16 @@ public class HornetQComponent extends BaseComponent {
OBJECT(false,"-object-"),
LIST(false,"-list-"),
DOUBLE(true,"long")
-
;
private boolean numeric;
private String rhqName;
private DataType(boolean numeric, String rhqName) {
- this.numeric=numeric;
+ this.numeric = numeric;
this.rhqName = rhqName;
}
-
public boolean isNumeric() {
return numeric;
}
commit 2afba16576fc92fd4db835e1272efc53f845d6ea
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 22:55:50 2012 -0400
'discovery' command now discovers types in order, by plugin name then by type name, rather than in random order
diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java
index bd6ceed..ad8d8f5 100644
--- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java
+++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/promptcmd/DiscoveryPromptCommand.java
@@ -24,11 +24,13 @@ import gnu.getopt.LongOpt;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
+import java.util.TreeSet;
import mazz.i18n.Msg;
@@ -247,7 +249,7 @@ public class DiscoveryPromptCommand implements AgentPromptCommand {
throws Exception {
PluginContainer pc = PluginContainer.getInstance();
PluginMetadataManager metadataManager = pc.getPluginManager().getMetadataManager();
- Set<ResourceType> typesToDiscover = new HashSet<ResourceType>();
+ Set<ResourceType> typesToDiscover = new TreeSet<ResourceType>(new PluginPrimaryResourceTypeComparator());
// make sure the plugin exists first (if one was specified)
Set<String> allPlugins = metadataManager.getPluginNames();
@@ -427,4 +429,22 @@ public class DiscoveryPromptCommand implements AgentPromptCommand {
out.println();
return;
}
+
+ private class PluginPrimaryResourceTypeComparator implements Comparator<ResourceType> {
+ @Override
+ public int compare(ResourceType type1, ResourceType type2) {
+ if (type1.getPlugin() == null) {
+ return (type2.getPlugin() == null) ? 0 : -1;
+ }
+ int result = (type2.getPlugin() == null) ? 1 : type1.getPlugin().compareTo(type2.getPlugin());
+ if (result != 0) {
+ return result;
+ }
+ if (type1.getName() == null) {
+ return (type2.getName() == null) ? 0 : -1;
+ }
+ return (type2.getName() == null) ? 1 : type1.getName().compareTo(type2.getName());
+ }
+ }
+
}
\ No newline at end of file
commit 6e7fe0381b816992efdebc6963ca7c6db4cd4af5
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Mon Mar 26 22:29:57 2012 -0500
Commit for matching service end tag.
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 3f19522..0a3ed99 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
@@ -1013,7 +1013,7 @@
<c:simple-property name="enable-statistics" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether statistics should be enabled."/>
</resource-configuration>
- </server>
+ </service>
<server name="Datasources"
discovery="SubsystemDiscovery"
commit 3625be03fd566e76b4c71fbb14552333e6a02078
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Mon Mar 26 22:00:41 2012 -0400
[Bug 806009 - Trait history could not be displayed]
Bring the datasource in line with others and migrate from
DataSourceFields to ListGridFields. This fixes the issue and
allows the use of standard timestamp formatting and ancestry
handlers (for the group trait view).
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java
index 0afcc20..325a542 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitDataSource.java
@@ -18,6 +18,7 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.common;
+import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
@@ -28,16 +29,17 @@ import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
-import com.smartgwt.client.data.fields.DataSourceDateTimeField;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
+import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.criteria.MeasurementDataTraitCriteria;
import org.rhq.core.domain.measurement.MeasurementDataTrait;
import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
+import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter;
import org.rhq.enterprise.gui.coregui.client.gwt.GWTServiceLookup;
import org.rhq.enterprise.gui.coregui.client.gwt.MeasurementDataGWTServiceAsync;
import org.rhq.enterprise.gui.coregui.client.util.Log;
@@ -72,18 +74,35 @@ public abstract class AbstractMeasurementDataTraitDataSource extends
idField.setHidden(true);
fields.add(idField);
- DataSourceTextField nameField = new DataSourceTextField(MeasurementDataTraitCriteria.SORT_FIELD_DISPLAY_NAME,
+ return fields;
+ }
+
+ /**
+ * The view that contains the list grid which will display this datasource's data will call this
+ * method to get the field information which is used to control the display of the data.
+ *
+ * @return list grid fields used to display the datasource data
+ */
+ public ArrayList<ListGridField> getListGridFields() {
+ ArrayList<ListGridField> fields = new ArrayList<ListGridField>(3);
+
+ ListGridField nameField = new ListGridField(MeasurementDataTraitCriteria.SORT_FIELD_DISPLAY_NAME,
MSG.dataSource_traits_field_trait());
fields.add(nameField);
// TODO: Include description from metric def?
- DataSourceTextField valueField = new DataSourceTextField(MeasurementDataTraitCriteria.SORT_FIELD_VALUE,
+ ListGridField valueField = new ListGridField(MeasurementDataTraitCriteria.SORT_FIELD_VALUE,
MSG.common_title_value());
fields.add(valueField);
- DataSourceDateTimeField timestampField = new DataSourceDateTimeField(
- MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP, MSG.dataSource_traits_field_lastChanged());
+ ListGridField timestampField = new ListGridField(MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP,
+ MSG.dataSource_traits_field_lastChanged());
+ timestampField.setCellFormatter(new TimestampCellFormatter());
+ timestampField.setShowHover(true);
+ timestampField.setHoverCustomizer(TimestampCellFormatter
+ .getHoverCustomizer(MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP));
+ timestampField.setWidth("20%");
fields.add(timestampField);
return fields;
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListDetailView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListDetailView.java
index b410a80..60cb4d3 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListDetailView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListDetailView.java
@@ -18,6 +18,8 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.common;
+import java.util.ArrayList;
+
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.SortSpecifier;
import com.smartgwt.client.types.SelectionStyle;
@@ -29,7 +31,6 @@ import com.smartgwt.client.widgets.grid.events.DataArrivedHandler;
import org.rhq.core.domain.criteria.MeasurementDataTraitCriteria;
import org.rhq.enterprise.gui.coregui.client.components.table.Table;
-import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter;
/**
* A view that displays a non-paginated table of {@link org.rhq.core.domain.measurement.MeasurementDataTrait trait}s,
@@ -56,14 +57,13 @@ public abstract class AbstractMeasurementDataTraitListDetailView extends Table {
}
@Override
- protected void configureTable() {
+ protected void configureTable() {
ListGrid listGrid = getListGrid();
- listGrid.setSelectionType(SelectionStyle.NONE);
- // Set widths and cell formatters on the fields.
- ListGridField timestampField = listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP);
- timestampField.setWidth("20%");
- timestampField.setCellFormatter(new TimestampCellFormatter());
+ ArrayList<ListGridField> dataSourceFields = getDataSource().getListGridFields();
+ listGrid.setFields(dataSourceFields.toArray(new ListGridField[dataSourceFields.size()]));
+
+ listGrid.setSelectionType(SelectionStyle.NONE);
listGrid.addDataArrivedHandler(new DataArrivedHandler() {
public void onDataArrived(DataArrivedEvent dataArrivedEvent) {
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java
index 27a766c..2f842a8 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/common/AbstractMeasurementDataTraitListView.java
@@ -18,6 +18,8 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.common;
+import java.util.ArrayList;
+
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.data.SortSpecifier;
import com.smartgwt.client.types.SelectionStyle;
@@ -27,7 +29,6 @@ import com.smartgwt.client.widgets.grid.ListGridField;
import org.rhq.core.domain.criteria.MeasurementDataTraitCriteria;
import org.rhq.enterprise.gui.coregui.client.components.table.TableSection;
-import org.rhq.enterprise.gui.coregui.client.components.table.TimestampCellFormatter;
/**
* A view that displays a non-paginated table of {@link org.rhq.core.domain.measurement.MeasurementDataTrait trait}s,
@@ -60,19 +61,15 @@ public abstract class AbstractMeasurementDataTraitListView extends TableSection
super.configureTable();
ListGrid listGrid = getListGrid();
+
+ ArrayList<ListGridField> dataSourceFields = getDataSource().getListGridFields();
+ listGrid.setFields(dataSourceFields.toArray(new ListGridField[dataSourceFields.size()]));
+
listGrid.setSelectionType(SelectionStyle.SINGLE);
// Set widths and cell formatters on the fields.
ListGridField displayNameField = listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_DISPLAY_NAME);
- if (displayNameField != null) {
- displayNameField.setWidth("20%");
- }
-
- ListGridField timestampField = listGrid.getField(MeasurementDataTraitCriteria.SORT_FIELD_TIMESTAMP);
- if (timestampField != null) {
- timestampField.setWidth("20%");
- timestampField.setCellFormatter(new TimestampCellFormatter());
- }
+ displayNameField.setWidth("20%");
}
@Override
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsDataSource.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsDataSource.java
index 152852e..64b857b 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsDataSource.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsDataSource.java
@@ -18,6 +18,7 @@
*/
package org.rhq.enterprise.gui.coregui.client.inventory.groups.detail.monitoring.traits;
+import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -27,7 +28,9 @@ import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.fields.DataSourceIntegerField;
-import com.smartgwt.client.data.fields.DataSourceTextField;
+import com.smartgwt.client.widgets.grid.CellFormatter;
+import com.smartgwt.client.widgets.grid.HoverCustomizer;
+import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.criteria.MeasurementDataTraitCriteria;
@@ -35,10 +38,12 @@ import org.rhq.core.domain.measurement.MeasurementDataTrait;
import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.domain.util.PageList;
+import org.rhq.enterprise.gui.coregui.client.LinkManager;
import org.rhq.enterprise.gui.coregui.client.inventory.common.AbstractMeasurementDataTraitDataSource;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.AncestryUtil;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository;
import org.rhq.enterprise.gui.coregui.client.inventory.resource.type.ResourceTypeRepository.TypesLoadedCallback;
+import org.rhq.enterprise.gui.coregui.client.util.selenium.SeleniumUtility;
/**
* A DataSource for reading traits for the current group.
@@ -61,13 +66,36 @@ public class TraitsDataSource extends AbstractMeasurementDataTraitDataSource {
groupIdField.setHidden(true);
fields.add(0, groupIdField);
- DataSourceTextField resourceNameField = new DataSourceTextField(
- MeasurementDataTraitCriteria.SORT_FIELD_RESOURCE_NAME, MSG.common_title_resource());
- fields.add(0, resourceNameField);
+ return fields;
+ }
+
+ /**
+ * The view that contains the list grid which will display this datasource's data will call this
+ * method to get the field information which is used to control the display of the data.
+ *
+ * @return list grid fields used to display the datasource data
+ */
+ public ArrayList<ListGridField> getListGridFields() {
+ ArrayList<ListGridField> fields = super.getListGridFields();
+
+ ListGridField resourceNameField = new ListGridField(AncestryUtil.RESOURCE_NAME, MSG.common_title_resource());
+ resourceNameField.setCellFormatter(new CellFormatter() {
+ public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
+ String url = LinkManager.getResourceLink(record.getAttributeAsInt(AncestryUtil.RESOURCE_ID));
+ return SeleniumUtility.getLocatableHref(url, value.toString(), null);
+ }
+ });
+ resourceNameField.setShowHover(true);
+ resourceNameField.setHoverCustomizer(new HoverCustomizer() {
+
+ public String hoverHTML(Object value, ListGridRecord listGridRecord, int rowNum, int colNum) {
+ return AncestryUtil.getResourceHoverHTML(listGridRecord, 0);
+ }
+ });
+ fields.add(resourceNameField);
- DataSourceTextField ancestryField = new DataSourceTextField(AncestryUtil.RESOURCE_ANCESTRY, MSG
- .common_title_ancestry());
- fields.add(1, ancestryField);
+ ListGridField ancestryField = AncestryUtil.setupAncestryListGridField();
+ fields.add(ancestryField);
return fields;
}
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsView.java
index c56638d..ed91c6a 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/groups/detail/monitoring/traits/TraitsView.java
@@ -47,6 +47,8 @@ public class TraitsView extends AbstractMeasurementDataTraitListView {
@Override
protected void configureTable() {
+ super.configureTable();
+
ListGrid listGrid = getListGrid();
listGrid.setShowAllRecords(true);
commit ce4f367472d2d47b4a5c252504fef34bbbca02bc
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Mon Mar 26 17:07:02 2012 -0500
Move the transactions subsystem from server to service.
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 75264cc..3f19522 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
@@ -957,7 +957,7 @@
</server>
- <server name="Transactions Subsystem"
+ <service name="Transactions Subsystem"
discovery="SubsystemDiscovery"
class="BaseComponent"
singleton="true"
commit 0758ea14be87ea0ebe4783c2c52366fcfb68f774
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Mon Mar 26 16:58:35 2012 -0500
Add support for JPA subsystem.
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 9d97b8c..75264cc 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
@@ -2670,4 +2670,25 @@ working area for individual server instances</li></ul>"/>
</service>
+ <service name="JPA"
+ class="BaseComponent"
+ discovery="SubsystemDiscovery"
+ description="The configuration of the JPA subsystem."
+ singleton="true">
+
+ <runs-inside>
+ <parent-resource-type name="Profile" plugin="jboss-as-7"/>
+ <parent-resource-type name="JBossAS7 Standalone Server" plugin="jboss-as-7"/>
+ </runs-inside>
+
+ <plugin-configuration>
+ <c:simple-property name="path" default="subsystem=jpa" readOnly="true"/>
+ </plugin-configuration>
+
+ <resource-configuration>
+ <c:simple-property name="default-datasource" required="false" type="string" readOnly="false" description="The name of the default global datasource."/>
+ </resource-configuration>
+
+ </service>
+
</plugin>
commit e89136fb236ac7480ed34141fc0c3d049096240a
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Mon Mar 26 16:38:16 2012 -0500
Add support for JAXR subsystem.
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 5916ed9..9d97b8c 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
@@ -2647,4 +2647,27 @@ working area for individual server instances</li></ul>"/>
</service>
+ <service name="JAXR"
+ class="BaseComponent"
+ discovery="SubsystemDiscovery"
+ description="The configuration of the JAXR subsystem."
+ singleton="true">
+
+ <runs-inside>
+ <parent-resource-type name="Profile" plugin="jboss-as-7"/>
+ <parent-resource-type name="JBossAS7 Standalone Server" plugin="jboss-as-7"/>
+ </runs-inside>
+
+ <plugin-configuration>
+ <c:simple-property name="path" default="subsystem=jaxr" readOnly="true"/>
+ </plugin-configuration>
+
+ <resource-configuration>
+ <c:simple-property name="connection-factory" required="false" type="string" readOnly="false" description="The JNDI name for the ConnectionFactory"/>
+ <c:simple-property name="publish-url" required="false" type="string" readOnly="false" description="The jUDDI server publish URL"/>
+ <c:simple-property name="query-url" required="false" type="string" readOnly="false" description="The jUDDI server query URL"/>
+ </resource-configuration>
+
+ </service>
+
</plugin>
commit 5caa6ec075c1f08ff1f1ef6df061c0e33efc4dae
Author: Stefan Negrea <snegrea(a)redhat.com>
Date: Mon Mar 26 16:25:05 2012 -0500
Move singleton JCA subsystems as group configuration to simplify structure. Add subsystems for workmanager as resource configuration since they are singletons too.
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 5ae84bc..5916ed9 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
@@ -2575,37 +2575,21 @@ working area for individual server instances</li></ul>"/>
<c:simple-property name="path" default="subsystem=jca" readOnly="true"/>
</plugin-configuration>
- <service name="ArchiveValidation"
- class="BaseComponent"
- discovery="SubsystemDiscovery"
- description="Archive validation for resource adapters."
- singleton="true">
-
- <plugin-configuration>
- <c:simple-property name="path" readOnly="true" default="archive-validation"/>
- </plugin-configuration>
-
- <resource-configuration>
+ <resource-configuration>
+ <c:group name="child:bean-validation=bean-validation" displayName="Bean validation (JSR-303) for resource adapters.">
+ <c:simple-property name="enabled" required="false" type="boolean" readOnly="false" defaultValue="true" description="Specify whether bean validation is enabled. The default value is true."/>
+ </c:group>
+ <c:group name="child:archive-validation=archive-validation" displayName="Archive validation for resource adapters.">
<c:simple-property name="enabled" required="false" type="boolean" readOnly="false" defaultValue="true" description="Specify whether archive validation is enabled. The default value is true."/>
<c:simple-property name="fail-on-error" required="false" type="boolean" readOnly="false" defaultValue="true" description="Should an archive validation error report fail the deployment. The default value is true."/>
<c:simple-property name="fail-on-warn" required="false" type="boolean" readOnly="false" defaultValue="false" description="Should an archive validation warning report fail the deployment. The default value is false."/>
- </resource-configuration>
- </service>
-
- <service name="BeanValidation"
- class="BaseComponent"
- discovery="SubsystemDiscovery"
- description="Bean validation (JSR-303) for resource adapters."
- singleton="true">
-
- <plugin-configuration>
- <c:simple-property name="path" readOnly="true" default="bean-validation"/>
- </plugin-configuration>
-
- <resource-configuration>
- <c:simple-property name="enabled" required="false" type="boolean" readOnly="false" defaultValue="true" description="Specify whether bean validation is enabled. The default value is true."/>
- </resource-configuration>
- </service>
+ </c:group>
+ <c:group name="child:cached-connection-manager=cached-connection-manager" displayName="Cached connection manager for resource adapters.">
+ <c:simple-property name="debug" required="false" type="boolean" readOnly="false" defaultValue="false" description="Enable/disable debug information logging. The default value is false."/>
+ <c:simple-property name="error" required="false" type="boolean" readOnly="false" defaultValue="false" description="Enable/disable error information logging. The default value is false."/>
+ <c:simple-property name="install" required="false" type="boolean" readOnly="false" defaultValue="false" description="Enable/disable the cached connection manager valve and interceptor. The default value is false."/>
+ </c:group>
+ </resource-configuration>
<service name="BootstrapContext"
class="BaseComponent"
@@ -2633,25 +2617,34 @@ working area for individual server instances</li></ul>"/>
<resource-configuration>
<c:simple-property name="name" required="false" type="string" readOnly="false" description="The name of the WorkManager"/>
+
+ <c:group name="child:long-running-threads=default-long-running-threads" displayName="Long running thread pool executor with a bounded queue where threads submittings tasks may block.">
+ <c:simple-property name="allow-core-timeout" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether core threads may time out. The default value is false."/>
+ <c:simple-property name="core-threads:expr" required="false" type="string" readOnly="false" description="The core thread pool size which is smaller than the maximum pool size. If undefined, the core thread pool size is the same as the maximum thread pool size."/>
+ <c:map-property name="keepalive-time" description="Used to specify the amount of time that pool threads should be kept running when idle; if not specified, threads will run until the executor is shut down." >
+ <c:simple-property name="time" required="true" type="long" readOnly="true" description="The time"/>
+ <c:simple-property name="unit" required="true" type="string" readOnly="true" description="The time unit"/>
+ </c:map-property>
+ <c:simple-property name="max-threads:expr" required="false" type="string" readOnly="false" description="The maximum thread pool size."/>
+ <c:simple-property name="name" required="false" type="string" readOnly="true" description="The name of the thread pool."/>
+ <c:simple-property name="queue-length:expr" required="false" type="string" readOnly="false" description="The queue length."/>
+ <c:simple-property name="thread-factory" required="false" type="string" readOnly="false" description="Specifies the name of a specific thread factory to use to create worker threads. If not defined an appropriate default thread factory will be used."/>
+ </c:group>
+ <c:group name="child:short-running-threads=default-short-running-threads" displayName="Short running thread pool executor with a bounded queue where threads submittings tasks may block.">
+ <c:simple-property name="allow-core-timeout" required="false" type="boolean" readOnly="false" defaultValue="false" description="Whether core threads may time out. The default value is false."/>
+ <c:simple-property name="core-threads:expr" required="false" type="string" readOnly="false" description="The core thread pool size which is smaller than the maximum pool size. If undefined, the core thread pool size is the same as the maximum thread pool size."/>
+ <c:map-property name="keepalive-time" description="Used to specify the amount of time that pool threads should be kept running when idle; if not specified, threads will run until the executor is shut down." >
+ <c:simple-property name="time" required="true" type="long" readOnly="true" description="The time"/>
+ <c:simple-property name="unit" required="true" type="string" readOnly="true" description="The time unit"/>
+ </c:map-property>
+ <c:simple-property name="max-threads:expr" required="false" type="string" readOnly="false" description="The maximum thread pool size."/>
+ <c:simple-property name="name" required="false" type="string" readOnly="true" description="The name of the thread pool."/>
+ <c:simple-property name="queue-length:expr" required="false" type="string" readOnly="false" description="The queue length."/>
+ <c:simple-property name="thread-factory" required="false" type="string" readOnly="false" description="Specifies the name of a specific thread factory to use to create worker threads. If not defined an appropriate default thread factory will be used."/>
+ </c:group>
</resource-configuration>
</service>
-
- <service name="CachedConnectionManager"
- class="BaseComponent"
- discovery="SubsystemDiscovery"
- description="Cached connection manager for resource adapters."
- singleton="true">
-
- <plugin-configuration>
- <c:simple-property name="path" readOnly="true" default="cached-connection-manager"/>
- </plugin-configuration>
- <resource-configuration>
- <c:simple-property name="debug" required="false" type="boolean" readOnly="false" defaultValue="false" description="Enable/disable debug information logging. The default value is false."/>
- <c:simple-property name="error" required="false" type="boolean" readOnly="false" defaultValue="false" description="Enable/disable error information logging. The default value is false."/>
- <c:simple-property name="install" required="false" type="boolean" readOnly="false" defaultValue="false" description="Enable/disable the cached connection manager valve and interceptor. The default value is false."/>
- </resource-configuration>
- </service>
</service>
</plugin>
commit 3e93e33b82b96cc3cf73c54f5907ac8f9d97bbe6
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Mon Mar 26 16:33:08 2012 -0400
[BZ 801432] but make sure we keep the same collection that we already have, even if the children is supposed to be empty
I don't think this fixes anything, but it at least maintains our expectations.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
index 4e974a8..74b5c17 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/resource/Resource.java
@@ -1387,7 +1387,15 @@ public class Resource implements Comparable<Resource>, Serializable {
public void setChildResources(Set<Resource> children) {
// Never allow this.childResources to become null, so we can guarantee getChildResources() will always return a
// non-null value.
- this.childResources = (children != null) ? children : new HashSet<Resource>();
+ if (children != null) {
+ this.childResources = children;
+ } else {
+ if (this.childResources != null) {
+ this.childResources.clear();
+ } else {
+ this.childResources = new HashSet<Resource>();
+ }
+ }
}
@Nullable
commit c52f86c0ec27f224ff5fa854b667d3f0e43b8b67
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Mon Mar 26 21:39:11 2012 +0200
Tell the VM to prefer IPv4
diff --git a/modules/plugins/jboss-as-7/src/test/resources/itest/jbossas7-arquillian.xml b/modules/plugins/jboss-as-7/src/test/resources/itest/jbossas7-arquillian.xml
index b0899ad..fab895c 100644
--- a/modules/plugins/jboss-as-7/src/test/resources/itest/jbossas7-arquillian.xml
+++ b/modules/plugins/jboss-as-7/src/test/resources/itest/jbossas7-arquillian.xml
@@ -10,7 +10,7 @@
overridden via the mvn command line. -->
<configuration>
<property name="jbossHome">${jboss7.home}</property>
- <property name="javaVmArguments">-Xmx512M -XX:MaxPermSize=128M -Djboss.bind.address.management=${jboss.standalone.bindAddress} -Djboss.bind.address=${jboss.standalone.bindAddress} -Djboss.bind.address.unsecure=${jboss.standalone.bindAddress} -Djboss.socket.binding.port-offset=${jboss.standalone.portOffset}</property>
+ <property name="javaVmArguments">-Djava.net.preferIPv4Stack=true -Xmx512M -XX:MaxPermSize=128M -Djboss.bind.address.management=${jboss.standalone.bindAddress} -Djboss.bind.address=${jboss.standalone.bindAddress} -Djboss.bind.address.unsecure=${jboss.standalone.bindAddress} -Djboss.socket.binding.port-offset=${jboss.standalone.portOffset}</property>
<property name="managementAddress">${jboss.standalone.bindAddress}</property>
<property name="managementPort">${jboss.standalone.nativeManagementPort}</property>
</configuration>
commit 95fc8dd5273b973633b1907d654a468e883afcb6
Author: Jay Shaughnessy <jshaughn(a)redhat.com>
Date: Mon Mar 26 14:10:53 2012 -0400
When presenting a PropertyMapListGridRecord in the ConfigurationEditor
make it sort numerically for Long properties. Although Long support
is not well-documented in SmartGWT, I think declaring the type
field as a Integer and then ensuring we set the attribute value
to the Long Object will be ok.
It seems to work.
See http://forums.smartclient.com/showthread.php?t=17431&highlight=listgridfi...
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
index 1dc1ace..f3a1704 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/ConfigurationEditor.java
@@ -931,8 +931,7 @@ public class ConfigurationEditor extends LocatableVLayout {
summaryTable.setRecordEnabledProperty(null);
List<ListGridField> fieldsList = new ArrayList<ListGridField>();
- final List<PropertyDefinition> propertyDefinitions = memberPropertyDefinitionMap
- .getPropertyDefinitions();
+ final List<PropertyDefinition> propertyDefinitions = memberPropertyDefinitionMap.getPropertyDefinitions();
List<PropertyDefinition> summaryPropertyDefinitions = new ArrayList<PropertyDefinition>();
for (PropertyDefinition subDef : propertyDefinitions) {
@@ -1046,6 +1045,7 @@ public class ConfigurationEditor extends LocatableVLayout {
field.setType(ListGridFieldType.BOOLEAN);
break;
case INTEGER:
+ case LONG: // according to what i see in smartgwt forums, INTEGER supports LONG
field.setType(ListGridFieldType.INTEGER);
break;
case FLOAT:
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyMapListGridRecord.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyMapListGridRecord.java
index 5a840c2..f912c1f 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyMapListGridRecord.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/configuration/PropertyMapListGridRecord.java
@@ -1,13 +1,14 @@
package org.rhq.enterprise.gui.coregui.client.components.configuration;
+import java.util.List;
+
import com.smartgwt.client.widgets.grid.ListGridRecord;
+
import org.rhq.core.domain.configuration.AbstractPropertyMap;
import org.rhq.core.domain.configuration.PropertySimple;
import org.rhq.core.domain.configuration.definition.PropertyDefinition;
import org.rhq.core.domain.configuration.definition.PropertyDefinitionSimple;
-import java.util.List;
-
/**
* A ListGridRecord representation of an RHQ PropertyMap.
*
@@ -20,7 +21,7 @@ public class PropertyMapListGridRecord extends ListGridRecord {
private List<PropertyDefinition> memberPropertyDefinitions;
public PropertyMapListGridRecord(AbstractPropertyMap propertyMap, int index,
- List<PropertyDefinition> memberPropertyDefinitions) {
+ List<PropertyDefinition> memberPropertyDefinitions) {
this.propertyMap = propertyMap;
this.index = index;
this.memberPropertyDefinitions = memberPropertyDefinitions;
@@ -45,21 +46,24 @@ public class PropertyMapListGridRecord extends ListGridRecord {
if ((propertySimple != null) && (propertySimple.getStringValue() != null)) {
try {
switch (((PropertyDefinitionSimple) subDef).getType()) {
- case BOOLEAN:
- setAttribute(propertyName, propertySimple.getBooleanValue());
- break;
- case INTEGER:
- setAttribute(propertyName, propertySimple.getIntegerValue());
- break;
- case FLOAT:
- setAttribute(propertyName, propertySimple.getFloatValue());
- break;
- case DOUBLE:
- setAttribute(propertyName, propertySimple.getDoubleValue());
- break;
- default:
- setAttribute(propertyName, propertySimple.getStringValue());
- break;
+ case BOOLEAN:
+ setAttribute(propertyName, propertySimple.getBooleanValue());
+ break;
+ case INTEGER:
+ setAttribute(propertyName, propertySimple.getIntegerValue());
+ break;
+ case LONG:
+ setAttribute(propertyName, propertySimple.getLongValue());
+ break;
+ case FLOAT:
+ setAttribute(propertyName, propertySimple.getFloatValue());
+ break;
+ case DOUBLE:
+ setAttribute(propertyName, propertySimple.getDoubleValue());
+ break;
+ default:
+ setAttribute(propertyName, propertySimple.getStringValue());
+ break;
}
} catch (Exception e) {
// value is not valid according to the type specified by the prop def; validation code in
commit 31f1104d88bf5fd18fe5267d258d70f0df7c6e4d
Author: John Mazzitelli <mazz(a)redhat.com>
Date: Mon Mar 26 13:57:23 2012 -0400
fix the agent log messages
diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java
index 8536de2..f4d7a1c 100644
--- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java
+++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/AgentMain.java
@@ -3657,7 +3657,7 @@ public class AgentMain {
// An unlikely state, but if we're not sending, not polling and not performing autoDiscovery
// (multicast), then start polling to we eventually get out of this state.
if (!(m_clientSender.isServerPolling() || isAutoDiscoveryEnabled())) {
- LOG.info("Starting polling to determine sender status");
+ LOG.info(AgentI18NResourceKeys.PING_EXECUTOR_STARTING_POLLING);
m_clientSender.startServerPolling();
}
@@ -3666,7 +3666,7 @@ public class AgentMain {
// we are in sending mode, so make sure the poller is off
if (m_clientSender.isServerPolling()) {
- LOG.info("Stopping polling and resuming pinging");
+ LOG.info(AgentI18NResourceKeys.PING_EXECUTOR_STOPPING_POLLING_RESUME_PING);
m_clientSender.stopServerPolling();
}
@@ -3684,10 +3684,11 @@ public class AgentMain {
// If the ping fails, typically do to a CannotConnectException, and we're not using autodiscovery,
// then start the poller to have sending mode re-established when the connection resumes.
if (!(m_clientSender.isServerPolling() || isAutoDiscoveryEnabled())) {
- LOG.info("Starting polling to determine sender status", t);
+ LOG.info(AgentI18NResourceKeys.PING_EXECUTOR_STARTING_POLLING_AFTER_EXCEPTION,
+ ThrowableUtil.getAllMessages(t));
m_clientSender.startServerPolling();
} else {
- LOG.warn("Server Ping failed", t);
+ LOG.warn(AgentI18NResourceKeys.PING_EXECUTOR_SERVER_PING_FAILED, t);
}
}
}
diff --git a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java
index 60c048c..93f8b8f 100644
--- a/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java
+++ b/modules/enterprise/agent/src/main/java/org/rhq/enterprise/agent/i18n/AgentI18NResourceKeys.java
@@ -540,7 +540,7 @@ public interface AgentI18NResourceKeys {
@I18NMessage("The agent has been configured with server auto-detection enabled; however, the multicast detector communications service has been disabled. Auto-detection needs that multicast detector in order to work. Auto-detection will, therefore, be disabled.")
String WEIRD_AUTO_DETECT_CONFIG = "AgentMain.weird-auto-detect-config";
- @I18NMessage("Neither server auto-detection nor polling is enabled - the client will be allowed to start sending commands immediately, but when the server is offline, be prepared for alot of errors to be logged")
+ @I18NMessage("Server auto-detection is not enabled - starting the poller immediately")
String NO_AUTO_DETECT = "AgentMain.no-auto-detect";
@I18NMessage("Native system info is enabled, but the system info API is not accessible on this platform "
@@ -2116,4 +2116,16 @@ public interface AgentI18NResourceKeys {
@I18NMessage("The config file already has a security token defined. The original security token will be thrown away.")
String NOT_RESTORING_SECURITY_TOKEN = "AgentMain.not-restoring-security-token";
-}
\ No newline at end of file
+
+ @I18NMessage("Starting polling to determine sender status")
+ String PING_EXECUTOR_STARTING_POLLING = "AgentMain.ping-executor.starting-polling";
+
+ @I18NMessage("Stopping polling and resuming pinging")
+ String PING_EXECUTOR_STOPPING_POLLING_RESUME_PING = "AgentMain.ping-executor.stop-polling-resume-ping";
+
+ @I18NMessage("Starting polling to determine sender status (server ping failed)")
+ String PING_EXECUTOR_STARTING_POLLING_AFTER_EXCEPTION = "AgentMain.ping-executor.start-polling-after-exception";
+
+ @I18NMessage("Server ping failed")
+ String PING_EXECUTOR_SERVER_PING_FAILED = "AgentMain.ping-executor.server-ping-failed";
+}
commit 08632a0ada1954345afae6fadced16f67db5f62c
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 12:57:14 2012 -0400
re-enable testReloadOperation(), since "reload" is working now
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
index 12a441f..11ba4b0 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
@@ -84,8 +84,7 @@ public class StandaloneServerComponentTest extends AbstractServerComponentTest {
}
// ******************************* OPERATIONS ******************************* //
- // TODO: Re-enable once fixed.
- @Test(priority = 12, enabled = false)
+ @Test(priority = 12)
public void testReloadOperation() throws Exception {
invokeOperationAndAssertSuccess(getServerResource(), RELOAD_OPERATION_NAME, null);
}
commit 372fcea81d8dc8927571156e095eb6d207c1b57f
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 12:34:16 2012 -0400
add assertions to testAutoDiscovery() that verify the 'hostname' and 'port' plugin config props got set correctly by the discovery component
diff --git a/modules/plugins/jboss-as-7/pom.xml b/modules/plugins/jboss-as-7/pom.xml
index 6eb5e3c..2c6a98e 100644
--- a/modules/plugins/jboss-as-7/pom.xml
+++ b/modules/plugins/jboss-as-7/pom.xml
@@ -452,7 +452,10 @@
<arquillian.xml>${project.build.testSourceDirectory}/../resources/itest/arquillian.xml</arquillian.xml>
<jboss7.home>${jboss7.home}</jboss7.home>
<as7.version>${as7.version}</as7.version>
+ <jboss.standalone.bindAddress>${jboss.standalone.bindAddress}</jboss.standalone.bindAddress>
+ <jboss.standalone.portOffset>${jboss.standalone.portOffset}</jboss.standalone.portOffset>
<jboss.domain.bindAddress>${jboss.domain.bindAddress}</jboss.domain.bindAddress>
+ <jboss.domain.portOffset>${jboss.domain.portOffset}</jboss.domain.portOffset>
<jboss.domain.httpManagementPort>${jboss.domain.httpManagementPort}</jboss.domain.httpManagementPort>
<settings.localRepository>${settings.localRepository}</settings.localRepository>
</systemPropertyVariables>
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
index d4edff1..d816bab 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
@@ -21,6 +21,7 @@ package org.rhq.modules.plugins.jbossas7.itest;
import java.util.HashMap;
import java.util.Map;
+import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
@@ -71,9 +72,28 @@ public abstract class AbstractServerComponentTest extends AbstractJBossAS7Plugin
assertNotNull(getServerResource(),
getServerResourceType() + " Resource with key [" + getServerResourceKey() + "] was not discovered.");
System.out.println("===== Discovered: " + getServerResource());
- System.out.println("---------- " + getServerResource().getPluginConfiguration().toString(true));
+ Configuration pluginConfig = getServerResource().getPluginConfiguration();
+ System.out.println("---------- " + pluginConfig.toString(true));
+ validatePluginConfiguration(pluginConfig);
}
+ private void validatePluginConfiguration(Configuration pluginConfig) {
+ String hostname = pluginConfig.getSimpleValue("hostname", null);
+ String expectedHostname = System.getProperty(getBindAddressSystemPropertyName());
+ assertEquals(hostname, expectedHostname, "Plugin config prop [hostname].");
+
+ String portString = pluginConfig.getSimpleValue("port", null);
+ Integer port = (portString != null) ? Integer.valueOf(portString) : null;
+ String portOffsetString = System.getProperty(getPortOffsetSystemPropertyName());
+ int portOffset = (portOffsetString != null) ? Integer.valueOf(portOffsetString) : 0;
+ Integer expectedPort = portOffset + 9990;
+ assertEquals(port, expectedPort, "Plugin config prop [port].");
+ }
+
+ protected abstract String getBindAddressSystemPropertyName();
+
+ protected abstract String getPortOffsetSystemPropertyName();
+
public void testMetricsHaveNonNullValues() throws Exception {
assertAllNumericMetricsAndTraitsHaveNonNullValues(getServerResource());
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
index ba6ee2d..76330b3 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java
@@ -46,6 +46,16 @@ public class DomainServerComponentTest extends AbstractServerComponentTest {
return RESOURCE_KEY;
}
+ @Override
+ protected String getBindAddressSystemPropertyName() {
+ return "jboss.domain.bindAddress";
+ }
+
+ @Override
+ protected String getPortOffsetSystemPropertyName() {
+ return "jboss.domain.portOffset";
+ }
+
@RunDiscovery
@Test(priority = 20, groups = "discovery")
public void testDomainServerDiscovery() throws Exception {
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
index 1823490..12a441f 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
@@ -54,6 +54,16 @@ public class StandaloneServerComponentTest extends AbstractServerComponentTest {
return RESOURCE_KEY;
}
+ @Override
+ protected String getBindAddressSystemPropertyName() {
+ return "jboss.standalone.bindAddress";
+ }
+
+ @Override
+ protected String getPortOffsetSystemPropertyName() {
+ return "jboss.standalone.portOffset";
+ }
+
@Test(priority = 10, groups = "discovery")
@RunDiscovery
public void testStandaloneServerDiscovery() throws Exception {
commit ef0c9d966422ecbdd876d1230e8935ec9fae0a8c
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Mon Mar 26 18:19:30 2012 +0200
Also take a port-offset from the command line into account.
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index 0dfc54c..6b73ad3 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -189,6 +189,9 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
initLogEventSourcesConfigProp(logFile, config);
HostPort managementPort = getManagementPortFromHostXml(commandLine);
+ if (!psName.equals("HostController")) { // standalone
+ managementPort = checkForSocketBindingOffset(managementPort, commandLine);
+ }
config.put(new PropertySimple("hostname", managementPort.host));
config.put(new PropertySimple("port", managementPort.port));
config.put(new PropertySimple("realm", getManagementSecurityRealmFromHostXml()));
@@ -237,6 +240,20 @@ public class BaseProcessDiscovery extends AbstractBaseDiscovery implements Resou
}
+ private HostPort checkForSocketBindingOffset(HostPort managementPort, String[] commandLine) {
+
+ for (String line : commandLine) {
+ if (line.contains("jboss.socket.binding.port-offset")) {
+ String tmp = line.substring(line.indexOf('=')+1);
+ Integer offset = Integer.valueOf(tmp);
+ managementPort.port+=offset;
+ break;
+ }
+ }
+
+ return managementPort;
+ }
+
private String getServerDescr(String productName) {
if (productName.equals("EAP"))
return JBOSS_EAP_6;
commit 75d1f5851f1c00df75f44671fa317e972d4e1ef1
Author: Heiko W. Rupp <hwr(a)redhat.com>
Date: Mon Mar 26 17:40:26 2012 +0200
Fix typo
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
index 91e5317..4dbaa71 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
@@ -15,13 +15,13 @@
<description>Server side plugin providing MongoDB Backend for drift management</description>
<properties>
- <!--
+ <!--
skipping mongodb tests by default for dev builds since a MongoDB
server install is not a prerequisite for development environment.
MongoDB is however is installed on jenkins and MongoDB tests will
run in jenkins builds.
-->
- <skip.mongodb.tests>true</skip.mongodb.tests</skip.mongodb.tests>
+ <skip.mongodb.tests>true</skip.mongodb.tests>
</properties>
<dependencies>
commit ed1abe17c811ddfdc121a697701647891869d692
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 11:18:38 2012 -0400
use static import for org.testng.Assert.*
diff --git a/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java b/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java
index 96dc32f..5f658f4 100644
--- a/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java
+++ b/modules/core/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java
@@ -29,7 +29,6 @@ import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mockito.Mockito;
-import org.testng.Assert;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.test.api.ArquillianResource;
@@ -70,6 +69,8 @@ import org.rhq.test.arquillian.FakeServerInventory;
import org.rhq.test.arquillian.MockingServerServices;
import org.rhq.test.shrinkwrap.RhqAgentPluginArchive;
+import static org.testng.Assert.*;
+
/**
* The base class for an Agent plugin integration test class.
*
@@ -177,7 +178,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
ResourceType resourceType = resource.getResourceType();
OperationDefinition operationDefinition = ResourceTypeUtility.getOperationDefinition(resourceType,
operationName);
- Assert.assertNotNull(operationDefinition, "No operation named [" + operationName
+ assertNotNull(operationDefinition, "No operation named [" + operationName
+ "] is defined for ResourceType {" + resourceType.getPlugin() + "}" + resourceType.getName() + ".");
long timeout = getDefaultTimeout(resource.getResourceType(), operationName);
@@ -235,7 +236,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
metricsWithNullValues.add(metricDef.getName());
}
}
- Assert.assertEquals(metricsWithNullValues.size(), 0, "Null values were collected for the following metrics: "
+ assertTrue(metricsWithNullValues.isEmpty(), "Null values were collected for the following metrics: "
+ metricsWithNullValues);
}
@@ -246,7 +247,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
if (report.getNumericData().isEmpty()) {
return null;
}
- Assert.assertEquals(report.getNumericData().size(), 1,
+ assertEquals(report.getNumericData().size(), 1,
"Requested a single metric but plugin returned more than one datum: " + report.getNumericData());
MeasurementDataNumeric datum = report.getNumericData().iterator().next();
// Normalize NaN or infinite to null, as the PC does.
@@ -263,7 +264,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
if (report.getTraitData().isEmpty()) {
return null;
}
- Assert.assertEquals(report.getTraitData().size(), 1,
+ assertEquals(report.getTraitData().size(), 1,
"Requested a single trait but plugin returned more than one datum: " + report.getTraitData());
MeasurementDataTrait datum = report.getTraitData().iterator().next();
String value = datum.getValue();
@@ -286,7 +287,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
ResourceType resourceType = resource.getResourceType();
MeasurementDefinition measurementDefinition = ResourceTypeUtility.getMeasurementDefinition(resourceType,
metricName);
- Assert.assertNotNull(measurementDefinition, "No metric named [" + metricName
+ assertNotNull(measurementDefinition, "No metric named [" + metricName
+ "] is defined for ResourceType {" + resourceType.getPlugin() + "}" + resourceType.getName() + ".");
ResourceContainer resourceContainer = this.pluginContainer.getInventoryManager().getResourceContainer(resource);
@@ -334,7 +335,7 @@ public abstract class AbstractAgentPluginTest extends Arquillian {
protected void assertOperationSucceeded(String operationName, Configuration params, OperationResult result) {
String paramsString = (params != null) ? params.toString(true) : String.valueOf(params);
- Assert.assertNull(result.getErrorMessage(), "Operation [" + operationName + "] with parameters "
+ assertNull(result.getErrorMessage(), "Operation [" + operationName + "] with parameters "
+ paramsString + " returned an error: " + result.getErrorMessage());
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java
index f2ffb3e..5e22925 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java
@@ -30,7 +30,6 @@ import org.rhq.core.pluginapi.operation.OperationResult;
import org.rhq.modules.plugins.jbossas7.itest.domain.DomainServerComponentTest;
import org.rhq.modules.plugins.jbossas7.itest.standalone.StandaloneServerComponentTest;
import org.rhq.test.arquillian.AfterDiscovery;
-import org.rhq.test.arquillian.RunDiscovery;
/**
* The base class for all jboss-as-7 plugin integration tests.
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
index e8fc852..d4edff1 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java
@@ -21,8 +21,6 @@ package org.rhq.modules.plugins.jbossas7.itest;
import java.util.HashMap;
import java.util.Map;
-import org.testng.Assert;
-
import org.rhq.core.domain.measurement.AvailabilityType;
import org.rhq.core.domain.resource.InventoryStatus;
import org.rhq.core.domain.resource.Resource;
@@ -30,6 +28,8 @@ import org.rhq.core.domain.resource.ResourceType;
import org.rhq.core.domain.util.ResourceUtility;
import org.rhq.core.pc.inventory.InventoryManager;
+import static org.testng.Assert.*;
+
/**
* The base class for the integration tests for the two AS7 server types.
*
@@ -57,7 +57,7 @@ public abstract class AbstractServerComponentTest extends AbstractJBossAS7Plugin
getServerResourceType(),
getServerResourceKey());
- Assert.assertNotNull(resource,
+ assertNotNull(resource,
getServerResourceType() + " Resource with key [" + getServerResourceKey() + "] not found in inventory.");
return resource;
@@ -65,10 +65,10 @@ public abstract class AbstractServerComponentTest extends AbstractJBossAS7Plugin
public void testAutoDiscovery() throws Exception {
Resource platform = this.pluginContainer.getInventoryManager().getPlatform();
- Assert.assertNotNull(platform);
- Assert.assertEquals(platform.getInventoryStatus(), InventoryStatus.COMMITTED);
+ assertNotNull(platform);
+ assertEquals(platform.getInventoryStatus(), InventoryStatus.COMMITTED);
- Assert.assertNotNull(getServerResource(),
+ assertNotNull(getServerResource(),
getServerResourceType() + " Resource with key [" + getServerResourceKey() + "] was not discovered.");
System.out.println("===== Discovered: " + getServerResource());
System.out.println("---------- " + getServerResource().getPluginConfiguration().toString(true));
@@ -92,20 +92,20 @@ public abstract class AbstractServerComponentTest extends AbstractJBossAS7Plugin
// AS7
expectedReleaseVersion = as7Version;
}
- Assert.assertEquals(releaseVersion, expectedReleaseVersion,
+ assertEquals(releaseVersion, expectedReleaseVersion,
"Unexpected value for trait [" + RELEASE_VERSION_TRAIT_NAME + "].");
}
public void testShutdownAndStartOperations() throws Exception {
AvailabilityType avail = getAvailability(getServerResource());
- Assert.assertEquals(avail, AvailabilityType.UP);
+ assertEquals(avail, AvailabilityType.UP);
invokeOperationAndAssertSuccess(getServerResource(), SHUTDOWN_OPERATION_NAME, null);
avail = getAvailability(getServerResource());
- Assert.assertEquals(avail, AvailabilityType.DOWN);
+ assertEquals(avail, AvailabilityType.DOWN);
// Restart the server, so the rest of the tests don't fail.
invokeOperationAndAssertSuccess(getServerResource(), START_OPERATION_NAME, null);
avail = getAvailability(getServerResource());
- Assert.assertEquals(avail, AvailabilityType.UP);
+ assertEquals(avail, AvailabilityType.UP);
}
}
diff --git a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
index e8474e7..1823490 100644
--- a/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
+++ b/modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/standalone/StandaloneServerComponentTest.java
@@ -18,7 +18,6 @@
*/
package org.rhq.modules.plugins.jbossas7.itest.standalone;
-import org.testng.Assert;
import org.testng.annotations.Test;
import org.rhq.core.domain.measurement.AvailabilityType;
@@ -28,6 +27,8 @@ import org.rhq.core.pluginapi.util.FileUtils;
import org.rhq.modules.plugins.jbossas7.itest.AbstractServerComponentTest;
import org.rhq.test.arquillian.RunDiscovery;
+import static org.testng.Assert.*;
+
/**
* Test discovery and facets of the "JBossAS7 Standalone Server" Resource type.
*
@@ -89,10 +90,10 @@ public class StandaloneServerComponentTest extends AbstractServerComponentTest {
@Test(priority = 13, dependsOnMethods = "testStandaloneServerShutdownAndStartOperations", enabled = false)
public void testRestartOperation() throws Exception {
AvailabilityType avail = getAvailability(getServerResource());
- Assert.assertEquals(avail, AvailabilityType.UP);
+ assertEquals(avail, AvailabilityType.UP);
invokeOperationAndAssertSuccess(getServerResource(), RESTART_OPERATION_NAME, null);
avail = getAvailability(getServerResource());
- Assert.assertEquals(avail, AvailabilityType.UP);
+ assertEquals(avail, AvailabilityType.UP);
}
}
commit f62fb10d7210146a95ae284c073c48134268f4ac
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 11:18:02 2012 -0400
if as7.itest is set, always run the itests, even if skipTests or skipITs sysprop is set
diff --git a/modules/plugins/jboss-as-7/pom.xml b/modules/plugins/jboss-as-7/pom.xml
index 8397f44..6eb5e3c 100644
--- a/modules/plugins/jboss-as-7/pom.xml
+++ b/modules/plugins/jboss-as-7/pom.xml
@@ -436,6 +436,8 @@
- can still shut down the servers fired up.
-->
<configuration>
+ <skipTests>false</skipTests>
+ <skipITs>false</skipITs>
<includes>
<!-- only include integration tests; normal unit tests are handled above by surefire plugin -->
<include>org/rhq/modules/plugins/jbossas7/itest/**/*Test.java</include>
commit 84c80504d01d2f346693d25826c2f90ca0452b98
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 11:16:39 2012 -0400
remove invalid parent relativePath
diff --git a/modules/core/plugin-test-util/pom.xml b/modules/core/plugin-test-util/pom.xml
index fcd0336..9f9338f 100644
--- a/modules/core/plugin-test-util/pom.xml
+++ b/modules/core/plugin-test-util/pom.xml
@@ -10,7 +10,6 @@
<groupId>org.rhq</groupId>
<artifactId>rhq-core-parent</artifactId>
<version>4.4.0-SNAPSHOT</version>
- <relativePath>../../../pom.xml</relativePath>
</parent>
<groupId>org.rhq</groupId>
commit 8eb7a120a2d2f90d63f2a628781b8f66d530311f
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 10:06:24 2012 -0400
improve logging when an exception occurs while attempting to collect file system usage info
diff --git a/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java b/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java
index 2bde8ee..6d5ada6 100644
--- a/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java
+++ b/modules/core/native-system/src/main/java/org/rhq/core/system/FileSystemInfo.java
@@ -1,6 +1,6 @@
/*
* RHQ Management Platform
-* Copyright (C) 2005-2008 Red Hat, Inc.
+* Copyright (C) 2005-2012 Red Hat, Inc.
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
@@ -26,6 +26,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
+import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.SigarProxy;
/**
@@ -61,11 +62,19 @@ public class FileSystemInfo {
try {
// this is the usage data and therefore should be refreshed
this.fsUsage = sigar.getMountedFileSystemUsage(this.mountPoint);
- } catch (Exception e) {
- // this happens when the file system is not available (like if its a CD-ROM without a CD loaded in it)
- // we can ignore this and set the usage data to null
+ } catch (SigarException e) {
+ // this happens when the file system is not available (e.g. if it's a CD-ROM without a CD loaded in it) or
+ // if we don't have permission to access the filesystem. we can ignore it and set the usage data to null.
+ this.fsUsage = null;
+ if (log.isTraceEnabled()) {
+ log.trace("Cannot refresh the usage data for file system mounted at [" + this.mountPoint + "].", e);
+ } else {
+ log.debug("Cannot refresh the usage data for file system mounted at [" + this.mountPoint + "]: " + e);
+ }
+ } catch (RuntimeException e) {
this.fsUsage = null;
- log.debug("Cannot refresh the usage data for file system mounted at [" + this.mountPoint + "]", e);
+ log.error("An error occurred while refreshing the usage data for file system mounted at [" + this.mountPoint
+ + "].", e);
}
}
@@ -84,7 +93,8 @@ public class FileSystemInfo {
/**
* This returns the usage information on the file system. This may return <code>null</code> if the file system is
- * not available (e.g when a "device not ready" error for CD-ROM drives occurs).
+ * not available (e.g when a "device not ready" error for CD-ROM drives occurs) or not accessible due to lack of
+ * permission.
*
* @return file system usage data
*/
commit e7575cd30fe9d8f284850a6b898e0df109db852f
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Mon Mar 26 10:05:46 2012 -0400
set project.reporting.outputEncoding=ISO-8859-1 to prevent the failsafe:verify goal from logging an annoying warning about no default encoding being set
diff --git a/pom.xml b/pom.xml
index 654968d..2705417 100644
--- a/pom.xml
+++ b/pom.xml
@@ -33,6 +33,7 @@
<properties>
<!-- explicitly specify a default encoding to avoid relying on the LANG env var being set correctly -->
<project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>ISO-8859-1</project.reporting.outputEncoding>
<rhq.groupId>org.rhq</rhq.groupId>
<rhq.product.name>RHQ</rhq.product.name>
@@ -536,7 +537,7 @@
<build>
- <defaultGoal>install</defaultGoal>
+ <defaultGoal>install</defaultGoal>
<pluginManagement>
<plugins>
commit e37e0c4f208d5256eb598eb299f333af4aef4e3c
Author: John Sanda <jsanda(a)redhat.com>
Date: Mon Mar 26 09:56:30 2012 -0400
Disable plugin by default upon discover and disable tests by default
I am disabling the plugin (upon discovery by server) and tests by
default since a MongoDB install is not a prerequisite for developer
environments.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
index 42b4d5b..91e5317 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
@@ -15,12 +15,13 @@
<description>Server side plugin providing MongoDB Backend for drift management</description>
<properties>
- <!--
- Tests are temporarily disabled until a MongoDB server is set up for use with
- hudson builds. They can however be run locally provided you have MongoDB installed.
- - jsanda
- <skipTests>true</skipTests>
- -->
+ <!--
+ skipping mongodb tests by default for dev builds since a MongoDB
+ server install is not a prerequisite for development environment.
+ MongoDB is however is installed on jenkins and MongoDB tests will
+ run in jenkins builds.
+ -->
+ <skip.mongodb.tests>true</skip.mongodb.tests</skip.mongodb.tests>
</properties>
<dependencies>
@@ -84,6 +85,7 @@
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
+ <skipTests>${skip.mongodb.tests}</skipTests>
<excludedGroups>${rhq.testng.excludedGroups}</excludedGroups>
<!--
<argLine>-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=y</argLine>
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml
index 6826efb..c6a8bff 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<drift-plugin
+<drift-plugin disabledOnDiscovery="true"
version="1.0"
apiVersion="1.0"
description="The Drift Management MongoDB Persistence Store"
commit 7665ec9bc63803b6d2a6d45a9e2525cae12e5a8d
Merge: 5e8e056 0882753
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Mar 25 21:38:13 2012 -0400
Merge branch 'master' into jsanda/drift-mongodb
commit 5e8e0566263ba0c972c63a6978c600943d1d0de5
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Mar 18 14:06:48 2012 -0400
Adding some source level docs
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 060cef5..9d25a30 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -19,6 +19,10 @@
package org.rhq.enterprise.server.plugins.drift.mongodb;
+import static org.rhq.enterprise.server.util.LookupUtil.getAgentManager;
+import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager;
+import static org.rhq.enterprise.server.util.LookupUtil.getSubjectManager;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
@@ -38,6 +42,7 @@ import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.WriteConcern;
import com.mongodb.gridfs.GridFSDBFile;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;
@@ -81,10 +86,6 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import org.rhq.enterprise.server.resource.ResourceManagerLocal;
import org.rhq.enterprise.server.util.LookupUtil;
-import static org.rhq.enterprise.server.util.LookupUtil.getAgentManager;
-import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager;
-import static org.rhq.enterprise.server.util.LookupUtil.getSubjectManager;
-
public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
private Log log = LogFactory.getLog(MongoDBDriftServer.class);
@@ -147,6 +148,15 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
changeSetDAO = new ChangeSetDAO(morphia, connection, "rhq");
fileDAO = new FileDAO(ds.getDB());
+ // Note that a write concern of SAFE does not cause the write operation
+ // to wait for the server to flush to disk which occurrs every one
+ // minute by default. With journaled enabled however (which is the
+ // default), we get the ability to recover from errors such as failure
+ // to flush to disk. If we absolutely need to wait and ensure that the
+ // write is successfully written to disk, we could use a write concern
+ // of FSYNC_SAFE; however, this should be used very judiciously as it
+ // will introduce a significant performance overhead on the server as
+ // it forces a flush to disk on every write (from this connect).
ds.setDefaultWriteConcern(WriteConcern.SAFE);
}
commit d7981933fa8095fdd15dae99880601be20d1aef3
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Mar 18 13:58:17 2012 -0400
Use default write concern of SAFE so that exceptions are raised on writes
Note that SAFE does not caue the write operation to wait for the server
to flush to disk which occurrs every one minute by default. With
journaled enabled (which is the default), we get the ability to recover
from errors such as failure to flush to disk.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 3bad055..060cef5 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -36,6 +36,7 @@ import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
+import com.mongodb.WriteConcern;
import com.mongodb.gridfs.GridFSDBFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -145,6 +146,8 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
ds = morphia.createDatastore(connection, "rhq");
changeSetDAO = new ChangeSetDAO(morphia, connection, "rhq");
fileDAO = new FileDAO(ds.getDB());
+
+ ds.setDefaultWriteConcern(WriteConcern.SAFE);
}
@Override
commit 226ccc025858a2c3763d911db5d1f8133485fae2
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Mar 16 14:42:15 2012 -0400
Adding drift-mongodb server plugin back to build
MongoDB is now installed on jenkins build slaves so we can run MongoDB
tests in jenkins builds, and MongoDB packages are in brew as well.
diff --git a/modules/enterprise/server/plugins/pom.xml b/modules/enterprise/server/plugins/pom.xml
index 5283b98..d7475f3 100644
--- a/modules/enterprise/server/plugins/pom.xml
+++ b/modules/enterprise/server/plugins/pom.xml
@@ -74,11 +74,7 @@
<module>alert-log4j</module>
<module>cobbler</module>
<module>drift-rhq</module>
- <!-- spinder,jsanda 8/26/11: Disabled from list of server plugins as
- i)not ready for release
- ii)causes plugin dependency issues with brew.
<module>drift-mongodb</module>
- -->
<module>filetemplate-bundle</module>
<module>ant-bundle</module>
<module>validate-all-serverplugins</module>
commit c2bac4df90cc4ebc6e1f33ee128781c1c7568b65
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Mar 11 22:32:26 2012 -0400
Exposing purgeOrphanedContent as plugin operation that can be invoked from UI.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml b/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml
index eb32c51..6826efb 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/resources/META-INF/rhq-serverplugin.xml
@@ -9,13 +9,17 @@
package="org.rhq.enterprise.server.plugins.drift.mongodb"
xmlns="urn:xmlns:rhq-serverplugin.drift"
xmlns:serverplugin="urn:xmlns:rhq-serverplugin"
+ xmlns:c="urn:xmlns:rhq-configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<serverplugin:help><![CDATA[
Provides back-end store and retrieve for drift files.
]]></serverplugin:help>
- <serverplugin:plugin-component class="MongoDBDriftServer"/>
+ <serverplugin:plugin-component class="MongoDBDriftServer">
+ <serverplugin:control name="purgeOrphanedContent" description="Purges drift file content no longer referenced
+ by any change sets."/>
+ </serverplugin:plugin-component>
<drift diff-support="false" />
commit 9a127aa21815bf6ce14974f42aa2adaef2cb1846
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Mar 11 22:10:43 2012 -0400
Adding method to purge orphaned drift file content
This commit adds the method purgeOrphanedContent to MongoDBDriftServer.
This method is not part of the drift server plugin API, but
purgeOrphanedDriftFiles is. I am not (yet) implementing the latter
because there are some race conditions that have to be dealt with, and I
am pushing that off for now. The plan is to expose purgeOrphanedContent
as a plugin operation to provide a manual way of purging content.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index ce06678..3bad055 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -33,6 +33,8 @@ import java.util.zip.ZipInputStream;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
+import com.google.code.morphia.query.Query;
+import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFSDBFile;
import org.apache.commons.logging.Log;
@@ -360,6 +362,19 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return 0;
}
+ public void purgeOrphanedContent() {
+ for (DBObject object : fileDAO.getFileListCursor()) {
+ String id = (String) object.get("_id");
+ Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class);
+ query.or(query.criteria("files.newFileHash").equal(id),
+ query.criteria("files.oldFileHash").equal(id));
+ query.limit(1);
+ if (query.get() == null) {
+ fileDAO.delete(id);
+ }
+ }
+ }
+
@Override
public String getDriftFileBits(Subject subject, String hash) {
GridFSDBFile file = fileDAO.findById(hash);
@@ -433,6 +448,8 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return changeSet.getResourceId() == 0 && changeSet.getDriftDefinitionId() == 0;
}
+
+
@Override
public String copyChangeSet(Subject subject, String changeSetId, int driftDefId, int resourceId) {
// TODO Pass definition name in as an argument
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java
index 874fdf6..559e153 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java
@@ -27,6 +27,7 @@ import java.io.InputStream;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
+import com.mongodb.DBCursor;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
@@ -59,5 +60,13 @@ public class FileDAO {
inputFile.put("_id", file.getName());
inputFile.save();
}
+
+ public void delete(String id) {
+ gridFS.remove(new BasicDBObject("_id", id));
+ }
+
+ public DBCursor getFileListCursor() {
+ return gridFS.getFileList();
+ }
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index 0f4efe1..e467b35 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -388,6 +388,34 @@ public class MongoDBDriftServerTest extends MongoDBTest {
}
@Test
+ public void purgeOrphanedContent() throws Exception {
+ int size = 1024;
+ File file1 = createRandomFile(getBaseDir(), size);
+ File file2 = createRandomFile(getBaseDir(), size);
+
+ driftServer.saveChangeSetFiles(null, createChangeSetContentZipFile(file1, file2));
+
+ MongoDBChangeSet changeSet = new MongoDBChangeSet();
+ changeSet.setDriftDefinitionId(1);
+ changeSet.setResourceId(1);
+ changeSet.setDriftDefinitionName("testdef");
+ changeSet.setCategory(COVERAGE);
+ changeSet.setVersion(0);
+
+ MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("./1.bin", FILE_ADDED);
+ entry.setNewFileHash(file1.getName());
+ changeSet.add(entry);
+
+ changeSetDAO.save(changeSet);
+
+ driftServer.purgeOrphanedContent();
+
+ FileDAO fileDAO = new FileDAO(ds.getDB());
+ assertNull(fileDAO.findById(file2.getName()), "Expected unreferenced file to be deleted");
+ assertNotNull(fileDAO.findById(file1.getName()), "Referenced file should not be deleted");
+ }
+
+ @Test
public void findChangeSetsByCriteriaAndDoNotFetchDrifts() throws Exception {
String driftDefName = "testdef";
int driftDefId = 1;
commit 19e8320f10f1349e1c4dbdca5b67374804719eef
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Mar 11 08:26:53 2012 -0400
Bumping up project version to 4.4.0-SNAPSHOT
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
index e93d680..42b4d5b 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
@@ -5,12 +5,11 @@
<parent>
<groupId>org.rhq</groupId>
<artifactId>rhq-enterprise-server-plugins-parent</artifactId>
- <version>4.3.0-SNAPSHOT</version>
+ <version>4.4.0-SNAPSHOT</version>
</parent>
<groupId>org.rhq</groupId>
<artifactId>drift-mongodb-serverplugin</artifactId>
- <packaging>jar</packaging>
<name>Drift Server MongoDB Plugin</name>
<description>Server side plugin providing MongoDB Backend for drift management</description>
commit 5c696f7049b68e3e2ea64ed66b13a5e50ec161f9
Merge: e3675c9 ccd5b1f
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Mar 10 22:24:08 2012 -0500
Merge branch 'master' into jsanda/drift-mongodb
commit e3675c94aa594b178df0ef9a07c3cce56c9f8d7f
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Mar 10 21:54:01 2012 -0500
Adding support for filtering by change set version with drift criteria queries
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index 35d4584..f88f368 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -175,6 +175,11 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
boolean entriesFiltered = false;
ChangeSetEntryFilters filters = new ChangeSetEntryFilters();
+
+ if (criteria.getFilterChangeSetId() != null) {
+ query.field("id").equal(new ObjectId(criteria.getFilterChangeSetId()));
+ changeSetsFiltered = true;
+ }
if (criteria.getFilterResourceIds().length > 0) {
query.field("resourceId").in(asList(criteria.getFilterResourceIds()));
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index b74d3e0..635f0d9 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -759,6 +759,25 @@ public class ChangeSetDAOTest extends MongoDBTest {
}
@Test(enabled = ENABLED)
+ public void findEntriesWithChangeSetIdFilter() throws Exception {
+ MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1);
+ MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
+ c1.add(e1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = createChangeSet(COVERAGE, 1, 2, 1);
+ MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED);
+ c2.add(e2);
+ dao.save(c2);
+
+ GenericDriftCriteria criteria = new GenericDriftCriteria();
+ criteria.addFilterChangeSetId(c2.getId());
+
+ List<MongoDBChangeSetEntry> entries = dao.findEntries(criteria);
+ assertEntriesMatch("Failed to find change set entries with change set id filter", asList(e2), entries);
+ }
+
+ @Test(enabled = ENABLED)
public void findEntriesWithResourceIdFilters() throws Exception {
MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1);
MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
@@ -866,6 +885,58 @@ public class ChangeSetDAOTest extends MongoDBTest {
}
@Test(enabled = ENABLED)
+ public void findEntriesWithChangeSetStartVersionFilter() throws Exception {
+ MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1);
+ MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
+ c1.add(e1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = createChangeSet(COVERAGE, 2, 1, 1);
+ MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED);
+ c2.add(e2);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = createChangeSet(DRIFT, 3, 1, 1);
+ MongoDBChangeSetEntry e3 = new MongoDBChangeSetEntry("c1-1.txt", FILE_CHANGED);
+ c3.add(e3);
+ dao.save(c3);
+
+ GenericDriftCriteria criteria = new GenericDriftCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterChangeSetStartVersion(2);
+
+ List<MongoDBChangeSetEntry> entries = dao.findEntries(criteria);
+ assertEntriesMatch("Failed to find change set entries with change set start version filter", asList(e2, e3),
+ entries);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findEntriesWithChangeSetEndVersionFilter() throws Exception {
+ MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1);
+ MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
+ c1.add(e1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = createChangeSet(COVERAGE, 2, 1, 1);
+ MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED);
+ c2.add(e2);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = createChangeSet(DRIFT, 3, 1, 1);
+ MongoDBChangeSetEntry e3 = new MongoDBChangeSetEntry("c1-1.txt", FILE_CHANGED);
+ c3.add(e3);
+ dao.save(c3);
+
+ GenericDriftCriteria criteria = new GenericDriftCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterChangeSetEndVersion(2);
+
+ List<MongoDBChangeSetEntry> entries = dao.findEntries(criteria);
+ assertEntriesMatch("Failed to find change set entries with change set end version filter", asList(e1, e2),
+ entries);
+ }
+
+ @Test(enabled = ENABLED)
public void findEntriesWithPathFilter() throws Exception {
MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1);
MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
commit ab8ae07ae8f11a2481b32162b61c28a704558c4d
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Mar 10 09:48:24 2012 -0500
Adding support for change set start/end version filters in drift criteria queries
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index 07792db..35d4584 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -162,6 +162,8 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
}
public List<MongoDBChangeSetEntry> findEntries(DriftCriteria criteria) {
+ // TODO Add support for driftHandlingModes filter
+
if (criteria.getFilterId() != null) {
String[] ids = criteria.getFilterId().split(":");
ObjectId changeSetId = new ObjectId(ids[0]);
@@ -178,6 +180,21 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
query.field("resourceId").in(asList(criteria.getFilterResourceIds()));
changeSetsFiltered = true;
}
+
+ if (criteria.getFilterDriftDefinitionId() != null) {
+ query.field("driftDefId").equal(criteria.getFilterDriftDefinitionId());
+ changeSetsFiltered = true;
+ }
+
+ if (criteria.getFilterChangeSetStartVersion() != null) {
+ query.field("version").greaterThanOrEq(criteria.getFilterChangeSetStartVersion());
+ changeSetsFiltered = true;
+ }
+
+ if (criteria.getFilterChangeSetEndVersion() != null) {
+ query.field("version").lessThanOrEq(criteria.getFilterChangeSetEndVersion());
+ changeSetsFiltered = true;
+ }
if (criteria.getFilterCategories().length > 0) {
query.field("files.category").in(asList(criteria.getFilterCategories()));
@@ -202,6 +219,12 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
entriesFiltered = true;
filters.add(new PathFilter(criteria.getFilterPath()));
}
+
+ if (criteria.getFilterDirectory() != null) {
+ query.field("files.directory").equal(criteria.getFilterDirectory());
+ entriesFiltered = true;
+ filters.add(new DirectoryFilter(criteria.getFilterDirectory()));
+ }
List<MongoDBChangeSetEntry> entries = new ArrayList<MongoDBChangeSetEntry>();
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/DirectoryFilter.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/DirectoryFilter.java
new file mode 100644
index 0000000..6781a9b
--- /dev/null
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/DirectoryFilter.java
@@ -0,0 +1,17 @@
+package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
+
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
+
+class DirectoryFilter implements ChangeSetEntryFilter {
+
+ private String dir;
+
+ public DirectoryFilter(String dir) {
+ this.dir = dir;
+ }
+
+ @Override
+ public boolean matches(MongoDBChangeSetEntry entry) {
+ return entry.getDirectory().equals(dir);
+ }
+}
commit 9c2767be7247b1c1de47a8acb385a3d2352088a2
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Mar 6 09:10:47 2012 -0500
Adding tests for change set and drift criteria queries
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index 44300d9..0f4efe1 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -42,12 +42,15 @@ import org.rhq.core.clientapi.agent.drift.DriftAgentService;
import org.rhq.core.domain.auth.Subject;
import org.rhq.core.domain.configuration.Configuration;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
+import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.Drift;
+import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
import org.rhq.core.domain.drift.dto.DriftDTO;
import org.rhq.core.domain.drift.dto.DriftFileDTO;
+import org.rhq.core.domain.util.PageList;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.ZipUtil;
import org.rhq.core.util.file.FileUtil;
@@ -74,6 +77,8 @@ import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandli
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertNull;
+import static org.testng.Assert.assertTrue;
public class MongoDBDriftServerTest extends MongoDBTest {
@@ -383,6 +388,290 @@ public class MongoDBDriftServerTest extends MongoDBTest {
}
@Test
+ public void findChangeSetsByCriteriaAndDoNotFetchDrifts() throws Exception {
+ String driftDefName = "testdef";
+ int driftDefId = 1;
+ int resourceId1 = 1;
+ int resourceId2 = 2;
+
+ MongoDBChangeSet changeSet1 = new MongoDBChangeSet();
+ changeSet1.setDriftDefinitionId(driftDefId);
+ changeSet1.setDriftDefinitionName(driftDefName);
+ changeSet1.setResourceId(resourceId1);
+ changeSet1.setCategory(COVERAGE);
+ changeSet1.setVersion(0);
+
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("./1.bin", FILE_ADDED);
+ entry1.setNewFileHash("./1.bin");
+ changeSet1.add(entry1);
+
+ changeSetDAO.save(changeSet1);
+
+ MongoDBChangeSet changeSet2 = new MongoDBChangeSet();
+ changeSet2.setDriftDefinitionId(driftDefId);
+ changeSet2.setDriftDefinitionName(driftDefName);
+ changeSet2.setResourceId(resourceId1);
+ changeSet2.setCategory(DRIFT);
+ changeSet2.setVersion(1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("./1.bin", FILE_CHANGED);
+ entry2.setNewFileHash(sha256("./1.bin.new"));
+ entry2.setOldFileHash(sha256("./1.bin"));
+ changeSet2.add(entry2);
+
+ MongoDBChangeSetEntry entry3 = new MongoDBChangeSetEntry("./2.bin", FILE_ADDED);
+ entry3.setNewFileHash("./2.bin");
+ changeSet2.add(entry3);
+
+ changeSetDAO.save(changeSet2);
+
+
+ MongoDBChangeSet changeSet3 = new MongoDBChangeSet();
+ changeSet3.setDriftDefinitionId(driftDefId);
+ changeSet3.setDriftDefinitionName(driftDefName);
+ changeSet3.setResourceId(resourceId2);
+ changeSet3.setCategory(COVERAGE);
+ changeSet3.setVersion(0);
+
+ MongoDBChangeSetEntry entry4 = new MongoDBChangeSetEntry("./3.bin", FILE_ADDED);
+ entry4.setNewFileHash(sha256("./3.bin"));
+ changeSet3.add(entry4);
+ changeSetDAO.save(changeSet3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(driftDefId);
+ criteria.addFilterResourceId(resourceId1);
+ criteria.addFilterVersion("1");
+
+ Mapper mapper = new Mapper();
+ DriftChangeSetDTO expected = mapper.toDTO(changeSet2);
+
+ PageList<? extends DriftChangeSet<?>> actualChangeSets = driftServer.findDriftChangeSetsByCriteria(null,
+ criteria);
+
+ assertEquals(actualChangeSets.size(), 1, "Expected to get back one change set.");
+ DriftChangeSetDTO actual = (DriftChangeSetDTO) actualChangeSets.get(0);
+
+ assertChangeSetMatches("Failed to return change set DTO", expected, actual);
+ assertTrue(actual.getDrifts().isEmpty(), "Drifts should not have been returned since criteria did not " +
+ "specify to fetch drifts");
+ }
+
+ @Test
+ public void findChangeSetsByCriteriaAndFetchDrifts() throws Exception {
+ String driftDefName = "testdef";
+ int driftDefId = 1;
+ int resourceId1 = 1;
+ int resourceId2 = 2;
+
+ MongoDBChangeSet changeSet1 = new MongoDBChangeSet();
+ changeSet1.setDriftDefinitionId(driftDefId);
+ changeSet1.setDriftDefinitionName(driftDefName);
+ changeSet1.setResourceId(resourceId1);
+ changeSet1.setCategory(COVERAGE);
+ changeSet1.setVersion(0);
+
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("./1.bin", FILE_ADDED);
+ entry1.setNewFileHash("./1.bin");
+ changeSet1.add(entry1);
+
+ changeSetDAO.save(changeSet1);
+
+ MongoDBChangeSet changeSet2 = new MongoDBChangeSet();
+ changeSet2.setDriftDefinitionId(driftDefId);
+ changeSet2.setDriftDefinitionName(driftDefName);
+ changeSet2.setResourceId(resourceId1);
+ changeSet2.setCategory(DRIFT);
+ changeSet2.setVersion(1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("./1.bin", FILE_CHANGED);
+ entry2.setNewFileHash(sha256("./1.bin.new"));
+ entry2.setOldFileHash(sha256("./1.bin"));
+ changeSet2.add(entry2);
+
+ MongoDBChangeSetEntry entry3 = new MongoDBChangeSetEntry("./2.bin", FILE_ADDED);
+ entry3.setNewFileHash("./2.bin");
+ changeSet2.add(entry3);
+
+ changeSetDAO.save(changeSet2);
+
+
+ MongoDBChangeSet changeSet3 = new MongoDBChangeSet();
+ changeSet3.setDriftDefinitionId(driftDefId);
+ changeSet3.setDriftDefinitionName(driftDefName);
+ changeSet3.setResourceId(resourceId2);
+ changeSet3.setCategory(COVERAGE);
+ changeSet3.setVersion(0);
+
+ MongoDBChangeSetEntry entry4 = new MongoDBChangeSetEntry("./3.bin", FILE_ADDED);
+ entry4.setNewFileHash(sha256("./3.bin"));
+ changeSet3.add(entry4);
+ changeSetDAO.save(changeSet3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(driftDefId);
+ criteria.addFilterResourceId(resourceId1);
+ criteria.addFilterVersion("1");
+ criteria.fetchDrifts(true);
+
+ Mapper mapper = new Mapper();
+ DriftChangeSetDTO expected = mapper.toDTO(changeSet2);
+
+
+ PageList<? extends DriftChangeSet<?>> actualChangeSets = driftServer.findDriftChangeSetsByCriteria(null,
+ criteria);
+
+ assertEquals(actualChangeSets.size(), 1, "Expected to get back one change set.");
+ DriftChangeSetDTO actual = (DriftChangeSetDTO) actualChangeSets.get(0);
+
+ assertChangeSetMatches("Failed to return change set DTO", expected, actual);
+ assertEquals(actual.getDrifts().size(), 2, "Expected change set to contain two drifts");
+
+ assertDriftMatches("The drift should have been included in the change set", mapper.toDTO(entry2),
+ find(actual.getDrifts(), "./1.bin"));
+ assertDriftMatches("The drift should have been included in the change set", mapper.toDTO(entry3),
+ find(actual.getDrifts(), "./2.bin"));
+ }
+
+ @Test
+ public void findDriftsByCriteriaAndDoNotFetchChangeSets() {
+ String driftDefName = "testdef";
+ int driftDefId = 1;
+ int resourceId1 = 1;
+ int resourceId2 = 2;
+
+ MongoDBChangeSet changeSet1 = new MongoDBChangeSet();
+ changeSet1.setDriftDefinitionId(driftDefId);
+ changeSet1.setDriftDefinitionName(driftDefName);
+ changeSet1.setResourceId(resourceId1);
+ changeSet1.setCategory(COVERAGE);
+ changeSet1.setVersion(0);
+
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("./1.bin", FILE_ADDED);
+ entry1.setNewFileHash("./1.bin");
+ changeSet1.add(entry1);
+
+ changeSetDAO.save(changeSet1);
+
+ MongoDBChangeSet changeSet2 = new MongoDBChangeSet();
+ changeSet2.setDriftDefinitionId(driftDefId);
+ changeSet2.setDriftDefinitionName(driftDefName);
+ changeSet2.setResourceId(resourceId1);
+ changeSet2.setCategory(DRIFT);
+ changeSet2.setVersion(1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("./1.bin", FILE_CHANGED);
+ entry2.setNewFileHash(sha256("./1.bin.new"));
+ entry2.setOldFileHash(sha256("./1.bin"));
+ changeSet2.add(entry2);
+
+ MongoDBChangeSetEntry entry3 = new MongoDBChangeSetEntry("./2.bin", FILE_ADDED);
+ entry3.setNewFileHash("./2.bin");
+ changeSet2.add(entry3);
+
+ changeSetDAO.save(changeSet2);
+
+
+ MongoDBChangeSet changeSet3 = new MongoDBChangeSet();
+ changeSet3.setDriftDefinitionId(driftDefId);
+ changeSet3.setDriftDefinitionName(driftDefName);
+ changeSet3.setResourceId(resourceId2);
+ changeSet3.setCategory(COVERAGE);
+ changeSet3.setVersion(0);
+
+ MongoDBChangeSetEntry entry4 = new MongoDBChangeSetEntry("./3.bin", FILE_ADDED);
+ entry4.setNewFileHash(sha256("./3.bin"));
+ changeSet3.add(entry4);
+ changeSetDAO.save(changeSet3);
+
+ GenericDriftCriteria criteria = new GenericDriftCriteria();
+ criteria.addFilterResourceIds(resourceId1);
+ criteria.addFilterDriftDefinitionId(driftDefId);
+ criteria.addFilterCategories(FILE_CHANGED);
+ criteria.addFilterChangeSetStartVersion(1);
+
+ PageList<? extends Drift<?, ?>> actualDrifts = driftServer.findDriftsByCriteria(null, criteria);
+ assertEquals(actualDrifts.size(), 1, "Expected to get back one drift");
+ DriftDTO actual = (DriftDTO) actualDrifts.get(0);
+
+ Mapper mapper = new Mapper();
+ DriftDTO expected = mapper.toDTO(entry2);
+
+ assertDriftMatches("Failed to return drift DTO", expected, actual);
+ assertNull(actual.getChangeSet(), "The change set should not have been included with the returned drift");
+ }
+
+ @Test
+ public void findDriftsByCriteriaAndFetchChangeSets() {
+ String driftDefName = "testdef";
+ int driftDefId = 1;
+ int resourceId1 = 1;
+ int resourceId2 = 2;
+
+ MongoDBChangeSet changeSet1 = new MongoDBChangeSet();
+ changeSet1.setDriftDefinitionId(driftDefId);
+ changeSet1.setDriftDefinitionName(driftDefName);
+ changeSet1.setResourceId(resourceId1);
+ changeSet1.setCategory(COVERAGE);
+ changeSet1.setVersion(0);
+
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("./1.bin", FILE_ADDED);
+ entry1.setNewFileHash("./1.bin");
+ changeSet1.add(entry1);
+
+ changeSetDAO.save(changeSet1);
+
+ MongoDBChangeSet changeSet2 = new MongoDBChangeSet();
+ changeSet2.setDriftDefinitionId(driftDefId);
+ changeSet2.setDriftDefinitionName(driftDefName);
+ changeSet2.setResourceId(resourceId1);
+ changeSet2.setCategory(DRIFT);
+ changeSet2.setVersion(1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("./1.bin", FILE_CHANGED);
+ entry2.setNewFileHash(sha256("./1.bin.new"));
+ entry2.setOldFileHash(sha256("./1.bin"));
+ changeSet2.add(entry2);
+
+ MongoDBChangeSetEntry entry3 = new MongoDBChangeSetEntry("./2.bin", FILE_ADDED);
+ entry3.setNewFileHash("./2.bin");
+ changeSet2.add(entry3);
+
+ changeSetDAO.save(changeSet2);
+
+
+ MongoDBChangeSet changeSet3 = new MongoDBChangeSet();
+ changeSet3.setDriftDefinitionId(driftDefId);
+ changeSet3.setDriftDefinitionName(driftDefName);
+ changeSet3.setResourceId(resourceId2);
+ changeSet3.setCategory(COVERAGE);
+ changeSet3.setVersion(0);
+
+ MongoDBChangeSetEntry entry4 = new MongoDBChangeSetEntry("./3.bin", FILE_ADDED);
+ entry4.setNewFileHash(sha256("./3.bin"));
+ changeSet3.add(entry4);
+ changeSetDAO.save(changeSet3);
+
+ GenericDriftCriteria criteria = new GenericDriftCriteria();
+ criteria.addFilterResourceIds(resourceId1);
+ criteria.addFilterDriftDefinitionId(driftDefId);
+ criteria.addFilterCategories(FILE_CHANGED);
+ criteria.addFilterChangeSetStartVersion(1);
+ criteria.fetchChangeSet(true);
+
+ PageList<? extends Drift<?, ?>> actualDrifts = driftServer.findDriftsByCriteria(null, criteria);
+ assertEquals(actualDrifts.size(), 1, "Expected to get back one drift");
+ DriftDTO actual = (DriftDTO) actualDrifts.get(0);
+
+ Mapper mapper = new Mapper();
+ DriftDTO expected = mapper.toDTO(entry2);
+
+ assertDriftMatches("Failed to return drift DTO", expected, actual);
+ assertChangeSetMatches("The change set should have been fetched", mapper.toDTO(changeSet2),
+ actual.getChangeSet());
+ }
+
+ @Test
public void persistNewInitialChangeSetForPinnedDriftDef() throws Exception {
DriftDefinition driftDef = new DriftDefinition(new Configuration());
driftDef.setId(1);
@@ -510,6 +799,8 @@ public class MongoDBDriftServerTest extends MongoDBTest {
find(actualDrifts, "./2.bin").getNewDriftFile());
}
+
+
/**
* Performs a property-wise comparison of the change set DTOs. The id, ctime, and drift
* properties are excluded from comparison.
commit c4898d2f84c9a65cde929303ee2182c4b2f5c894
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Mar 6 07:57:12 2012 -0500
Adding tests for MongoDBDriftServer.persistChangeSet
persistChangeSet is called when pinning a snapshot to a template or to a
definition.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 05d8275..ce06678 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -32,15 +32,13 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.google.code.morphia.Datastore;
-import com.google.code.morphia.Key;
import com.google.code.morphia.Morphia;
-import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import com.mongodb.gridfs.GridFSDBFile;
-
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;
+
import org.rhq.common.drift.ChangeSetReader;
import org.rhq.common.drift.ChangeSetReaderImpl;
import org.rhq.common.drift.FileEntry;
@@ -463,7 +461,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return StreamUtil.slurp(file.getInputStream());
}
- private DriftDefinition getDriftDef(Subject subject, int id) {
+ protected DriftDefinition getDriftDef(Subject subject, int id) {
DriftManagerLocal driftMgr = LookupUtil.getDriftManager();
return driftMgr.getDriftDefinition(subject, id);
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index c5eff1a..44300d9 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -18,13 +18,35 @@
*/
package org.rhq.enterprise.server.plugins.drift.mongodb;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilenameFilter;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Random;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
import org.jmock.Expectations;
import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.ChangeSetWriterImpl;
import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.clientapi.agent.drift.DriftAgentService;
+import org.rhq.core.domain.auth.Subject;
+import org.rhq.core.domain.configuration.Configuration;
+import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
+import org.rhq.core.domain.drift.Drift;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
+import org.rhq.core.domain.drift.dto.DriftDTO;
import org.rhq.core.domain.drift.dto.DriftFileDTO;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.ZipUtil;
@@ -40,12 +62,6 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import java.io.*;
-import java.util.List;
-import java.util.Random;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
import static java.util.Arrays.asList;
import static org.apache.commons.io.IOUtils.write;
import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
@@ -54,6 +70,7 @@ import static org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
+import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.plannedChanges;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
@@ -66,6 +83,8 @@ public class MongoDBDriftServerTest extends MongoDBTest {
private TestMongoDBDriftServer driftServer;
+ private ChangeSetDAO changeSetDAO;
+
@BeforeClass
public void initClass() throws Exception {
digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
@@ -96,11 +115,13 @@ public class MongoDBDriftServerTest extends MongoDBTest {
FileUtil.purge(basedir, true);
getBaseDir().mkdirs();
+ changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
+
driftServer = new TestMongoDBDriftServer();
driftServer.setConnection(connection);
driftServer.setMorphia(morphia);
driftServer.setDatastore(ds);
- driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, "rhqtest"));
+ driftServer.setChangeSetDAO(changeSetDAO);
driftServer.setFileDAO(new FileDAO(ds.getDB()));
}
@@ -141,8 +162,7 @@ public class MongoDBDriftServerTest extends MongoDBTest {
// use the subject argument.
DriftChangeSetSummary actualSummary = driftServer.saveChangeSet(null, resourceId, changeSetZip);
- // verify that the change set was persisted
- ChangeSetDAO changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
+ // verify that the change set was persisted
List<MongoDBChangeSet> changeSets = changeSetDAO.find().asList();
assertEquals(changeSets.size(), 1, "Expected to find one change set in the database.");
@@ -349,24 +369,211 @@ public class MongoDBDriftServerTest extends MongoDBTest {
driftServer.saveChangeSetFiles(null, createChangeSetContentZipFile(file1, file2));
- assertFileContentPersisted(file1, file2);
- }
-
- private void assertFileContentPersisted(File... expectedFiles) throws Exception {
FileDAO fileDAO = new FileDAO(ds.getDB());
-
- for (File expectedFile : expectedFiles) {
+
+ for (File expectedFile : asList(file1, file2)) {
InputStream inputStream = fileDAO.findOne(expectedFile.getName());
assertNotNull(inputStream, "Failed to find file in database with id " + expectedFile.getName());
File actualFile = new File(getBaseDir(), "actualContent");
actualFile.delete();
StreamUtil.copy(inputStream, new FileOutputStream(actualFile));
assertEquals(sha256(actualFile), sha256(expectedFile), "The SHA-256 hash in the database does not " +
- "match that of " + expectedFile.getPath());
+ "match that of " + expectedFile.getPath());
}
}
+
+ @Test
+ public void persistNewInitialChangeSetForPinnedDriftDef() throws Exception {
+ DriftDefinition driftDef = new DriftDefinition(new Configuration());
+ driftDef.setId(1);
+ driftDef.setName("testdef");
+
+ // This is essentially a test hook. MongoDBDriftServer.persistChangeSet has to call
+ // back into DriftManagerBean to look up the drift definition to get the definition
+ // name. Setting the driftDef property here allows us to avoid introducing EJB into
+ // the test.
+ driftServer.driftDef = driftDef;
+
+ int resourceId = 1;
+
+ // First create the change set from which the pinned change set will be created
+ DriftChangeSetDTO changeSetDTO = new DriftChangeSetDTO();
+ changeSetDTO.setResourceId(resourceId);
+ changeSetDTO.setDriftDefinitionId(driftDef.getId());
+ changeSetDTO.setDriftHandlingMode(plannedChanges);
+ changeSetDTO.setCategory(COVERAGE);
+ changeSetDTO.setCtime(new Date().getTime());
+ changeSetDTO.setVersion(0);
+
+ Set<DriftDTO> driftDTOs = new HashSet<DriftDTO>();
+ DriftDTO drift1DTO = new DriftDTO();
+ drift1DTO.setChangeSet(changeSetDTO);
+ drift1DTO.setCategory(FILE_ADDED);
+ drift1DTO.setPath("./1.bin");
+ drift1DTO.setDirectory(".");
+ drift1DTO.setCtime(new Date().getTime());
+ drift1DTO.setNewDriftFile(newDriftFile(sha256("./1.bin")));
+ driftDTOs.add(drift1DTO);
+
+ DriftDTO drift2DTO = new DriftDTO();
+ drift2DTO.setChangeSet(changeSetDTO);
+ drift2DTO.setCategory(FILE_ADDED);
+ drift2DTO.setPath("./2.bin");
+ drift2DTO.setDirectory(".");
+ drift2DTO.setCtime(new Date().getTime());
+ drift2DTO.setNewDriftFile(newDriftFile(sha256("./2.bin")));
+ driftDTOs.add(drift2DTO);
+
+ changeSetDTO.setDrifts(driftDTOs);
+
+ driftServer.persistChangeSet(null, changeSetDTO);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(driftDef.getId());
+ criteria.fetchDrifts(true);
+
+ List<MongoDBChangeSet> changeSets = changeSetDAO.findByChangeSetCritiera(criteria);
+ assertEquals(changeSets.size(), 1, "There should only be one change set for drift definition id " +
+ driftDef.getId());
+
+ Mapper mapper = new Mapper();
+ DriftChangeSetDTO actualChangeSet = mapper.toDTO(changeSets.get(0));
+ Set<DriftDTO> actualDrifts = new HashSet<DriftDTO>();
+ for (MongoDBChangeSetEntry entry : changeSets.get(0).getDrifts()) {
+ actualDrifts.add(mapper.toDTO(entry));
+ }
+
+ assertChangeSetMatches("Failed to persist change set", changeSetDTO, actualChangeSet);
+ assertDriftMatches("The drift should have been persisted in the change set", drift1DTO,
+ find(actualDrifts, "./1.bin"));
+ assertDriftFileMatches("Failed to persist the drift file data", drift1DTO.getNewDriftFile(),
+ find(actualDrifts, "./1.bin").getNewDriftFile());
+ assertDriftMatches("The drift should have been persisted in the change set", drift2DTO,
+ find(actualDrifts, "./2.bin"));
+ assertDriftFileMatches("Failed to persist the drift file data", drift2DTO.getNewDriftFile(),
+ find(actualDrifts, "./2.bin").getNewDriftFile());
+ }
+
+ @Test
+ public void persistNewChangeSetForPinnedTemplate() throws Exception {
+ // First create the change set from which the pinned change set will be created
+ DriftChangeSetDTO changeSetDTO = new DriftChangeSetDTO();
+ changeSetDTO.setDriftHandlingMode(plannedChanges);
+ changeSetDTO.setCategory(COVERAGE);
+ changeSetDTO.setCtime(new Date().getTime());
+ changeSetDTO.setVersion(0);
+
+ Set<DriftDTO> driftDTOs = new HashSet<DriftDTO>();
+ DriftDTO drift1DTO = new DriftDTO();
+ drift1DTO.setChangeSet(changeSetDTO);
+ drift1DTO.setCategory(FILE_ADDED);
+ drift1DTO.setPath("./1.bin");
+ drift1DTO.setDirectory(".");
+ drift1DTO.setCtime(new Date().getTime());
+ drift1DTO.setNewDriftFile(newDriftFile(sha256("./1.bin")));
+ driftDTOs.add(drift1DTO);
+
+ DriftDTO drift2DTO = new DriftDTO();
+ drift2DTO.setChangeSet(changeSetDTO);
+ drift2DTO.setCategory(FILE_ADDED);
+ drift2DTO.setPath("./2.bin");
+ drift2DTO.setDirectory(".");
+ drift2DTO.setCtime(new Date().getTime());
+ drift2DTO.setNewDriftFile(newDriftFile(sha256("./2.bin")));
+ driftDTOs.add(drift2DTO);
+
+ changeSetDTO.setDrifts(driftDTOs);
+
+ driftServer.persistChangeSet(null, changeSetDTO);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.fetchDrifts(true);
+
+ List<MongoDBChangeSet> changeSets = changeSetDAO.findByChangeSetCritiera(criteria);
+ assertEquals(changeSets.size(), 1, "There should only be one change set.");
+
+ Mapper mapper = new Mapper();
+ DriftChangeSetDTO actualChangeSet = mapper.toDTO(changeSets.get(0));
+ Set<DriftDTO> actualDrifts = new HashSet<DriftDTO>();
+ for (MongoDBChangeSetEntry entry : changeSets.get(0).getDrifts()) {
+ actualDrifts.add(mapper.toDTO(entry));
+ }
+
+ assertChangeSetMatches("Failed to persist change set", changeSetDTO, actualChangeSet);
+ assertDriftMatches("The drift should have been persisted in the change set", drift1DTO,
+ find(actualDrifts, "./1.bin"));
+ assertDriftFileMatches("Failed to persist the drift file data", drift1DTO.getNewDriftFile(),
+ find(actualDrifts, "./1.bin").getNewDriftFile());
+ assertDriftMatches("The drift should have been persisted in the change set", drift2DTO,
+ find(actualDrifts, "./2.bin"));
+ assertDriftFileMatches("Failed to persist the drift file data", drift2DTO.getNewDriftFile(),
+ find(actualDrifts, "./2.bin").getNewDriftFile());
+ }
/**
+ * Performs a property-wise comparison of the change set DTOs. The id, ctime, and drift
+ * properties are excluded from comparison.
+ *
+ * @param msg An error message
+ * @param expected
+ * @param actual
+ */
+ private void assertChangeSetMatches(String msg, DriftChangeSetDTO expected, DriftChangeSetDTO actual) {
+ assertPropertiesMatch(msg + ": " + DriftChangeSetDTO.class.getSimpleName() + " objects do not match.",
+ expected, actual, "id", "ctime", "drifts");
+ }
+
+ /**
+ * Performs a property-wise comparison of the drift DTOs. The id, ctime, changeSet,
+ * oldDriftFile, and newDriftFile properties are excluded from comparison. The
+ * changeSet, oldDriftFile, and newDriftFile properties should be verified using the
+ * {@link #assertChangeSetMatches(String, DriftChangeSetDTO, DriftChangeSetDTO)} and
+ * the {@link #assertDriftFileMatches(String, DriftFileDTO, DriftFileDTO)} methods
+ * respectively.
+ *
+ * @param msg
+ * @param expected
+ * @param actual
+ */
+ private void assertDriftMatches(String msg, DriftDTO expected, DriftDTO actual) {
+ assertPropertiesMatch(msg + ": " + DriftDTO.class.getSimpleName() + " objects do not match.",
+ expected, actual, "id", "ctime", "changeSet", "oldDriftFile", "newDriftFile");
+ }
+
+ /**
+ * Performs a property-wise comparison of the drift file DTOs.
+ *
+ * @param msg
+ * @param expected
+ * @param actual
+ */
+ private void assertDriftFileMatches(String msg, DriftFileDTO expected, DriftFileDTO actual) {
+ assertPropertiesMatch(msg + ": " + DriftFileDTO.class.getSimpleName() + " objects do not match.", expected,
+ actual);
+ }
+
+ /**
+ * Searches the collection of drifts for one with a matching path. The first match
+ * found is returned. An assertion error is thrown if no match is found.
+ *
+ * @param drifts
+ * @param path
+ * @param <D>
+ * @return
+ */
+ private <D extends Drift<?, ?>> D find(Collection<D> drifts, String path) {
+ D match = null;
+ for (D drift : drifts) {
+ if (path.equals(drift.getPath())) {
+ match = drift;
+ break;
+ }
+ }
+ assertNotNull(match, "Failed to find drift with path [" + path + "]");
+ return match;
+ }
+
+ /**
* Generates a change set zip file. This zip file contains a single entry, the change
* set report or meta data. The file is named changeset.zip and is written to
* {@link #getBaseDir() basedir}.
@@ -511,10 +718,18 @@ public class MongoDBDriftServerTest extends MongoDBTest {
return file;
}
+ private DriftFileDTO newDriftFile(String hash) {
+ DriftFileDTO file = new DriftFileDTO();
+ file.setHashId(hash);
+ return file;
+ }
+
private static class TestMongoDBDriftServer extends MongoDBDriftServer {
public DriftAgentService driftAgentService;
+ public DriftDefinition driftDef;
+
@Override
public DriftAgentService getDriftAgentService(int resourceId) {
return driftAgentService;
@@ -523,6 +738,11 @@ public class MongoDBDriftServerTest extends MongoDBTest {
public void setDriftAgentService(DriftAgentService driftAgentService) {
this.driftAgentService = driftAgentService;
}
+
+ @Override
+ protected DriftDefinition getDriftDef(Subject subject, int id) {
+ return driftDef;
+ }
}
/**
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
index d4a381a..076bece 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
@@ -19,6 +19,9 @@
package org.rhq.enterprise.server.plugins.drift.mongodb;
+import java.util.ArrayList;
+import java.util.List;
+
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
@@ -28,9 +31,6 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import org.rhq.test.JMockTest;
import org.testng.annotations.BeforeClass;
-import java.util.ArrayList;
-import java.util.List;
-
import static java.util.Arrays.asList;
import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
commit 60671b9ab6c13a93b9a1f13c8962e59a1b5290ac
Author: John Sanda <jsanda(a)redhat.com>
Date: Fri Mar 2 16:48:16 2012 -0500
Refactoring MongoDBDriftServer to use new Mapper class
This commit also changes how MongoDBChangeSetEntry stores its id. There
is now a changeSetId field in case the change set is nulled out at some.
The objectId of the change set is now initialized at creation time of
the change set object. This eliminates some complications that arose
around MongoDBChangeSetEntry.getId.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java
index 89ceaea..88b9461 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java
@@ -53,7 +53,7 @@ public class Mapper {
dto.setOldDriftFile(newDriftFileDTO(entry.getOldFileHash()));
}
- return null;
+ return dto;
}
private DriftFileDTO newDriftFileDTO(String hash) {
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index aeb600e..05d8275 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -283,27 +283,39 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject,
DriftChangeSetCriteria criteria) {
+ Mapper mapper = new Mapper();
List<MongoDBChangeSet> changeSets = changeSetDAO.findByChangeSetCritiera(criteria);
PageList<DriftChangeSetDTO> results = new PageList<DriftChangeSetDTO>();
+
for (MongoDBChangeSet changeSet : changeSets) {
- DriftChangeSetDTO changeSetDTO = toDTO(changeSet);
- Set<DriftDTO> entries = new HashSet<DriftDTO>();
- for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) {
- entries.add(toDTO(entry, changeSetDTO));
+ DriftChangeSetDTO changeSetDTO = mapper.toDTO(changeSet);
+ if (criteria.isFetchDrifts()) {
+ Set<DriftDTO> entries = new HashSet<DriftDTO>();
+ for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) {
+ DriftDTO driftDTO = mapper.toDTO(entry);
+ driftDTO.setChangeSet(changeSetDTO);
+ entries.add(driftDTO);
+ }
+ changeSetDTO.setDrifts(entries);
}
- changeSetDTO.setDrifts(entries);
results.add(changeSetDTO);
}
-
+
return results;
}
@Override
public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) {
+ Mapper mapper = new Mapper();
List<MongoDBChangeSetEntry> entries = changeSetDAO.findEntries(criteria);
PageList<DriftDTO> results = new PageList<DriftDTO>();
+
for (MongoDBChangeSetEntry entry : entries) {
- results.add(toDTO(entry, toDTO(entry.getChangeSet())));
+ DriftDTO driftDTO = mapper.toDTO(entry);
+ if (criteria.isFetchChangeSet()) {
+ driftDTO.setChangeSet(mapper.toDTO(entry.getChangeSet()));
+ }
+ results.add(driftDTO);
}
return results;
@@ -311,16 +323,20 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) {
- List<MongoDBChangeSet> changeSets = changeSetDAO.findByDriftCriteria(criteria);
+ Mapper mapper = new Mapper();
+ List<MongoDBChangeSetEntry> entries = changeSetDAO.findEntries(criteria);
Map<Integer, Resource> resources = loadResourceMap(subject, criteria.getFilterResourceIds());
PageList<DriftComposite> results = new PageList<DriftComposite>();
- for (MongoDBChangeSet changeSet : changeSets) {
- DriftChangeSetDTO changeSetDTO = toDTO(changeSet);
- for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) {
- results.add(new DriftComposite(toDTO(entry, changeSetDTO), resources.get(changeSet.getResourceId()),
- changeSet.getDriftDefinitionName()));
+ for (MongoDBChangeSetEntry entry : entries) {
+ MongoDBChangeSet changeSet = entry.getChangeSet();
+ DriftDTO driftDTO = mapper.toDTO(entry);
+ if (criteria.isFetchChangeSet()) {
+ DriftChangeSetDTO changeSetDTO = mapper.toDTO(changeSet);
+ driftDTO.setChangeSet(changeSetDTO);
}
+ results.add(new DriftComposite(driftDTO, resources.get(changeSet.getResourceId()),
+ changeSet.getDriftDefinitionName()));
}
return results;
@@ -370,43 +386,6 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return map;
}
- DriftChangeSetDTO toDTO(MongoDBChangeSet changeSet) {
- DriftChangeSetDTO dto = new DriftChangeSetDTO();
- dto.setId(changeSet.getId());
- // TODO copy resource id
- dto.setDriftDefinitionId(changeSet.getDriftDefinitionId());
- dto.setVersion(changeSet.getVersion());
- dto.setCtime(changeSet.getCtime());
- dto.setCategory(changeSet.getCategory());
-
- return dto;
- }
-
- DriftDTO toDTO(MongoDBChangeSetEntry entry, DriftChangeSetDTO changeSetDTO) {
- DriftDTO dto = new DriftDTO();
- dto.setChangeSet(changeSetDTO);
- dto.setId(entry.getId());
- dto.setCtime(entry.getCtime());
- dto.setPath(entry.getPath());
- dto.setDirectory(entry.getDirectory());
- dto.setCategory(entry.getCategory());
-
- switch (entry.getCategory()) {
- case FILE_ADDED:
- dto.setNewDriftFile(newDriftFile(entry.getNewFileHash()));
- break;
- case FILE_CHANGED:
- dto.setNewDriftFile(newDriftFile(entry.getNewFileHash()));
- dto.setOldDriftFile(newDriftFile(entry.getOldFileHash()));
- break;
- default: // FILE_REMOVED
- dto.setOldDriftFile(newDriftFile(entry.getOldFileHash()));
- }
-
- return dto;
- }
-
- @Override
public String persistChangeSet(Subject subject, DriftChangeSet<?> changeSet) {
// if this is a resource level change set we need to fetch the definition so that
// we can persist the definition name; otherwise, we will not be able to delete
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
index 6609538..9ccb226 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
@@ -24,10 +24,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
-import com.google.code.morphia.annotations.Embedded;
-import com.google.code.morphia.annotations.Entity;
-import com.google.code.morphia.annotations.Id;
-import com.google.code.morphia.annotations.PostLoad;
+import com.google.code.morphia.annotations.*;
import org.bson.types.ObjectId;
@@ -46,10 +43,10 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
private static final long serialVersionUID = 1L;
/**
- * The database primary key. This is auto-generated.
+ * The database primary key.
*/
@Id
- private ObjectId id;
+ private ObjectId id = new ObjectId();
/**
* The time that the change set was created.
@@ -170,7 +167,7 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
public MongoDBChangeSet add(MongoDBChangeSetEntry entry) {
entries.add(entry);
- entry.setId(entries.size() - 1);
+ entry.setIndex(entries.size() - 1);
entry.setChangeSet(this);
return this;
}
@@ -188,4 +185,5 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
entry.setChangeSet(this);
}
}
+
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
index ff2a7bd..312cdc6 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
@@ -3,8 +3,10 @@ package org.rhq.enterprise.server.plugins.drift.mongodb.entities;
import java.io.Serializable;
import com.google.code.morphia.annotations.Embedded;
+import com.google.code.morphia.annotations.Property;
import com.google.code.morphia.annotations.Transient;
+import org.bson.types.ObjectId;
import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftCategory;
@@ -18,10 +20,12 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
private static final long serialVersionUID = 1L;
/**
- * This id field is only unique within the parent change set. The purpose of this field
- * is to provide fast, efficient access to a file entry a change set document.
+ * This is the array index of the entry in the document that exists in the database.
+ * Each entry has a unique index relative to its owning change set. The index is used
+ * to form a unique id for the entry.
*/
- private int id;
+ @Property("idx")
+ private int index;
/**
* The time that the entry was created.
@@ -43,6 +47,9 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
@Transient
private MongoDBChangeSet changeSet;
+
+ @Transient
+ private ObjectId changeSetId;
private String oldFileHash;
@@ -60,8 +67,8 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
/**
* Returns an id that uniquely identifies this entry. Since a MongoChangeSetEntry does
- * have a PK in the database, this is a combination of the change set id with the id
- * assigned by the owning change set. The format is:
+ * not have a PK in the database, this is a combination of the change set id with its
+ * index which is assigned by the owning change set. The format is:
* <p/>
* <pre>
* <changeset_id>:<n>
@@ -74,40 +81,30 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
*/
@Override
public String getId() {
- return changeSet.getId() + ":" + id;
+ if (changeSetId == null) {
+ return null;
+ }
+ return changeSetId.toString() + ":" + index;
}
/**
- * Sets the id for the entry which is assumed to be an integer that is assigned
- * by the owning change set.
- *
- * @param id An integer id that should be unique among other entries within the owning
- * change set.
+ * This method does <strong>not</strong> actually set the id. It is here
+ * only because it is required by the {@link Drift} interface.
+ * @param id
*/
@Override
- public void setId(String id) {
- this.id = Integer.parseInt(id);
- }
-
- /**
- * Returns the change set assigned id. This id is unique across file entries within
- * the owning change set.
- *
- * @return The change set assigned id
- */
- public int getInternalId() {
- return id;
+ public void setId(String id) {
}
/**
- * Sets the id for the entry which is assumed to be an integer that is assigned
- * by the owning change set.
+ * Sets the index of the entry which is the array index within the document stored in the
+ * database. The index is used to form a unique id for the entry.
*
- * @param id An integer id that should be unique among other entries within the owning
- * change set.
+ * @param index The array index of the entry as it is stored in the change set document
+ * in the database.
*/
- public void setId(int id) {
- this.id = id;
+ public void setIndex(int index) {
+ this.index = index;
}
@Override
@@ -131,6 +128,7 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
@Override
public void setChangeSet(MongoDBChangeSet changeSet) {
this.changeSet = changeSet;
+ changeSetId = changeSet.getObjectId();
}
@Override
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java
index bf7b62c..c5da2b6 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java
@@ -19,10 +19,16 @@
package org.rhq.enterprise.server.plugins.drift.mongodb;
import org.bson.types.ObjectId;
+import org.rhq.core.domain.drift.DriftCategory;
import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
+import org.rhq.core.domain.drift.dto.DriftDTO;
+import org.rhq.core.domain.drift.dto.DriftFileDTO;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
import org.testng.annotations.Test;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
@@ -56,10 +62,38 @@ public class MapperTest {
DriftChangeSetDTO.class.getSimpleName());
}
-// @Test
-// public void mapNewEntryToDTO() {
-// MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("./foo", FILE_ADDED);
-// entry.setNewFileHash("1ab2c34d");
-// }
+ @Test
+ public void mapNewEntryToDTO() {
+ MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("./foo", FILE_ADDED);
+ entry.setChangeSet(new MongoDBChangeSet());
+ entry.setNewFileHash("1ab2c34d");
+ entry.setOldFileHash("4dc32b1a");
+ entry.setCategory(FILE_CHANGED);
+
+ Mapper mapper = new Mapper();
+ DriftDTO actual = mapper.toDTO(entry);
+
+ DriftDTO expected = new DriftDTO();
+ expected.setId(entry.getId());
+ expected.setCategory(entry.getCategory());
+ expected.setPath(entry.getPath());
+ expected.setDirectory(entry.getDirectory());
+ expected.setCtime(entry.getCtime());
+ expected.setNewDriftFile(newDriftFileDTO(entry.getNewFileHash()));
+ expected.setOldDriftFile(newDriftFileDTO(entry.getOldFileHash()));
+
+ assertPropertiesMatch("Failed to map " + MongoDBChangeSetEntry.class.getSimpleName() + " to " +
+ DriftDTO.class.getSimpleName(),expected, actual, "oldDriftFile", "newDriftFile");
+ assertPropertiesMatch(newDriftFileDTO(entry.getNewFileHash()), actual.getNewDriftFile(),
+ "Failed to map newDriftFile property");
+ assertPropertiesMatch(newDriftFileDTO(entry.getOldFileHash()), actual.getOldDriftFile(),
+ "Failed to map oldDriftFile property");
+ }
+
+ private DriftFileDTO newDriftFileDTO(String hash) {
+ DriftFileDTO dto = new DriftFileDTO();
+ dto.setHashId(hash);
+ return dto;
+ }
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index 5b1b768..b74d3e0 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -19,6 +19,7 @@
package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
+import org.bson.types.ObjectId;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
commit 8f06ccce4935edf163141f5ef473efd4dece0929
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Feb 28 10:29:59 2012 -0500
Initial commit for Mapper and MapperTest
This commit starts refactoring code that maps MongoDB entities into DTOs
into Mapper.java. Having a distinct DTO mapping layer makes it easier to
test and also easier to maintain.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java
new file mode 100644
index 0000000..89ceaea
--- /dev/null
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/Mapper.java
@@ -0,0 +1,65 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.enterprise.server.plugins.drift.mongodb;
+
+import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
+import org.rhq.core.domain.drift.dto.DriftDTO;
+import org.rhq.core.domain.drift.dto.DriftFileDTO;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
+
+public class Mapper {
+
+ public DriftChangeSetDTO toDTO(MongoDBChangeSet changeSet) {
+ DriftChangeSetDTO dto = new DriftChangeSetDTO();
+ dto.setId(changeSet.getId());
+ dto.setResourceId(changeSet.getResourceId());
+ dto.setDriftDefinitionId(changeSet.getDriftDefinitionId());
+ dto.setDriftHandlingMode(changeSet.getDriftHandlingMode());
+ dto.setVersion(changeSet.getVersion());
+ dto.setCtime(changeSet.getCtime());
+ dto.setCategory(changeSet.getCategory());
+
+ return dto;
+ }
+
+ public DriftDTO toDTO(MongoDBChangeSetEntry entry) {
+ DriftDTO dto = new DriftDTO();
+ dto.setId(entry.getId());
+ dto.setCategory(entry.getCategory());
+ dto.setCtime(entry.getCtime());
+ dto.setPath(entry.getPath());
+ dto.setDirectory(entry.getDirectory());
+ if (entry.getNewFileHash() != null) {
+ dto.setNewDriftFile(newDriftFileDTO(entry.getNewFileHash()));
+ }
+ if (entry.getOldFileHash() != null) {
+ dto.setOldDriftFile(newDriftFileDTO(entry.getOldFileHash()));
+ }
+
+ return null;
+ }
+
+ private DriftFileDTO newDriftFileDTO(String hash) {
+ DriftFileDTO dto = new DriftFileDTO();
+ dto.setHashId(hash);
+ return dto;
+ }
+
+}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java
new file mode 100644
index 0000000..bf7b62c
--- /dev/null
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MapperTest.java
@@ -0,0 +1,65 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.enterprise.server.plugins.drift.mongodb;
+
+import org.bson.types.ObjectId;
+import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import org.testng.annotations.Test;
+
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
+import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
+import static org.rhq.test.AssertUtils.assertPropertiesMatch;
+
+public class MapperTest {
+
+ @Test
+ public void mapChangeSetToDTO() {
+ MongoDBChangeSet changeSet = new MongoDBChangeSet();
+ changeSet.setId(new ObjectId());
+ changeSet.setCategory(DRIFT);
+ changeSet.setDriftDefinitionId(1);
+ changeSet.setDriftDefinitionName("testdef");
+ changeSet.setResourceId(1);
+ changeSet.setVersion(1);
+ changeSet.setDriftHandlingMode(normal);
+
+ Mapper mapper = new Mapper();
+ DriftChangeSetDTO actual = mapper.toDTO(changeSet);
+
+ DriftChangeSetDTO expected = new DriftChangeSetDTO();
+ expected.setId(changeSet.getId());
+ expected.setCategory(changeSet.getCategory());
+ expected.setCtime(changeSet.getCtime());
+ expected.setDriftDefinitionId(changeSet.getDriftDefinitionId());
+ expected.setResourceId(changeSet.getResourceId());
+ expected.setDriftHandlingMode(changeSet.getDriftHandlingMode());
+ expected.setVersion(changeSet.getVersion());
+
+ assertPropertiesMatch(expected, actual, "Failed to map " + MongoDBChangeSet.class.getSimpleName() + " to " +
+ DriftChangeSetDTO.class.getSimpleName());
+ }
+
+// @Test
+// public void mapNewEntryToDTO() {
+// MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("./foo", FILE_ADDED);
+// entry.setNewFileHash("1ab2c34d");
+// }
+
+}
commit 7e13b7ca4ea11fae724ba182f18a2fe1a70eef57
Author: John Sanda <jsanda(a)redhat.com>
Date: Mon Feb 27 21:54:10 2012 -0500
Adding test to verify file content is persisted in the db
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index bf2897c..c5eff1a 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -28,19 +28,23 @@ import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.dto.DriftFileDTO;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.ZipUtil;
+import org.rhq.core.util.file.FileUtil;
+import org.rhq.core.util.stream.StreamUtil;
import org.rhq.enterprise.server.plugin.pc.drift.DriftChangeSetSummary;
import org.rhq.enterprise.server.plugins.drift.mongodb.dao.ChangeSetDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.dao.FileDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
+import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import java.io.File;
-import java.io.FileOutputStream;
+import java.io.*;
import java.util.List;
import java.util.Random;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
import static java.util.Arrays.asList;
import static org.apache.commons.io.IOUtils.write;
@@ -52,6 +56,7 @@ import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
public class MongoDBDriftServerTest extends MongoDBTest {
@@ -67,12 +72,28 @@ public class MongoDBDriftServerTest extends MongoDBTest {
random = new Random();
}
+ @AfterClass
+ public void cleanUp() throws Exception {
+ File tmpDir = new File(System.getProperty("java.io.tmpdir"));
+ File[] dirs = tmpDir.listFiles(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.startsWith("changeset_content");
+ }
+ });
+ if (dirs != null) {
+ for (File dir : dirs) {
+ FileUtil.purge(dir, true);
+ }
+ }
+ }
+
@BeforeMethod
public void initTest() {
clearCollections("changesets", "fs.files", "fs.chunks");
File basedir = getBaseDir();
- basedir.delete();
+ FileUtil.purge(basedir, true);
getBaseDir().mkdirs();
driftServer = new TestMongoDBDriftServer();
@@ -319,7 +340,42 @@ public class MongoDBDriftServerTest extends MongoDBTest {
assertPropertiesMatch("The change set summary is wrong", expectedSummary, actualSummary);
}
+
+ @Test
+ public void persistChangeSetFileContent() throws Exception {
+ int size = 1024;
+ File file1 = createRandomFile(getBaseDir(), size);
+ File file2 = createRandomFile(getBaseDir(), size);
+
+ driftServer.saveChangeSetFiles(null, createChangeSetContentZipFile(file1, file2));
+ assertFileContentPersisted(file1, file2);
+ }
+
+ private void assertFileContentPersisted(File... expectedFiles) throws Exception {
+ FileDAO fileDAO = new FileDAO(ds.getDB());
+
+ for (File expectedFile : expectedFiles) {
+ InputStream inputStream = fileDAO.findOne(expectedFile.getName());
+ assertNotNull(inputStream, "Failed to find file in database with id " + expectedFile.getName());
+ File actualFile = new File(getBaseDir(), "actualContent");
+ actualFile.delete();
+ StreamUtil.copy(inputStream, new FileOutputStream(actualFile));
+ assertEquals(sha256(actualFile), sha256(expectedFile), "The SHA-256 hash in the database does not " +
+ "match that of " + expectedFile.getPath());
+ }
+ }
+
+ /**
+ * Generates a change set zip file. This zip file contains a single entry, the change
+ * set report or meta data. The file is named changeset.zip and is written to
+ * {@link #getBaseDir() basedir}.
+ *
+ * @param headers The change set headers
+ * @param fileEntries The entries that will comprise this change set
+ * @return The zip file as a {@link File} object
+ * @throws Exception
+ */
protected File createChangeSetZipFile(Headers headers, FileEntry... fileEntries) throws Exception {
ChangeSetWriter writer = newChangeSetWriter(headers);
for (FileEntry entry : fileEntries) {
@@ -334,6 +390,33 @@ public class MongoDBDriftServerTest extends MongoDBTest {
}
/**
+ * Generates a change set content zip file. This zip file contains the bits of each of
+ * the specified file. The zip file is named changeset_content_<timestamp>.zip
+ * and is written to {@link #getBaseDir() basedir}.
+ *
+ * @param files The files to include in the content zip file
+ * @return The zip file as a {@link File} object
+ * @throws Exception
+ */
+ protected File createChangeSetContentZipFile(File... files) throws Exception {
+ long timestamp = System.currentTimeMillis();
+ File contentDir = new File(getBaseDir(), "content_" + timestamp);
+ contentDir.mkdirs();
+
+ File zipFile = new File(getBaseDir(), "changeset_content_" + timestamp + ".zip");
+ ZipOutputStream zipStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
+ for (File file : files) {
+ FileInputStream fis = new FileInputStream(file);
+ zipStream.putNextEntry(new ZipEntry(file.getName()));
+ StreamUtil.copy(fis, zipStream, false);
+ fis.close();
+ }
+ zipStream.close();
+
+ return zipFile;
+ }
+
+ /**
* Initializes a {@link ChangeSetWriter} that will write to a file returned from
* {@link #getChangeSetFile()}
*
@@ -379,7 +462,24 @@ public class MongoDBDriftServerTest extends MongoDBTest {
protected String sha256(String string) {
return digestGenerator.calcDigestString(string);
}
+
+ protected String sha256(byte[] bytes) throws Exception {
+ return digestGenerator.calcDigestString(bytes);
+ }
+
+ protected String sha256(File file) throws Exception {
+ return digestGenerator.calcDigestString(file);
+ }
+ /**
+ * Generates a file of random bytes.
+ *
+ * @param dir The directory to which the file will be written
+ * @param fileName The name of the file to be created
+ * @param numBytes The size of the file in bytes
+ * @return The generated file as a {@link File} object
+ * @throws Exception
+ */
protected File createRandomFile(File dir, String fileName, int numBytes) throws Exception {
File file = new File(dir, fileName);
FileOutputStream stream = new FileOutputStream(file);
@@ -391,6 +491,26 @@ public class MongoDBDriftServerTest extends MongoDBTest {
return file;
}
+ /**
+ * Generates a file of random bytes where the name of the file is the SHA-256 hash of
+ * those bytes.
+ *
+ * @param dir The directory to which the file will be written
+ * @param numBytes The size of the file in bytes
+ * @return The generated file as a {@link File} object
+ * @throws Exception
+ */
+ protected File createRandomFile(File dir, int numBytes) throws Exception {
+ byte[] bytes = new byte[numBytes];
+ random.nextBytes(bytes);
+ File file = new File(dir, sha256(bytes));
+ FileOutputStream stream = new FileOutputStream(file);
+ write(bytes, stream);
+ stream.close();
+
+ return file;
+ }
+
private static class TestMongoDBDriftServer extends MongoDBDriftServer {
public DriftAgentService driftAgentService;
commit 6cbe9ad5477817b7181f5ce13ee397156feb50cc
Author: John Sanda <jsanda(a)localhost.localdomain>
Date: Mon Feb 27 10:32:09 2012 -0500
Adding more tests for persisting a change set
Two new test methods have been added. One tests persisting an initial
change set where the content is already in the db. The other test
involves persisting a drift change set with a changed file and a removed
file, and the new version of the file is not in the db.
This commit also includes some refactoring test set up/helper methods.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index 242da58..bf2897c 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -18,73 +18,77 @@
*/
package org.rhq.enterprise.server.plugins.drift.mongodb;
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-import com.google.code.morphia.Datastore;
-import com.google.code.morphia.Morphia;
-import com.google.code.morphia.query.Query;
-import com.mongodb.Mongo;
-
-import org.bson.types.ObjectId;
import org.jmock.Expectations;
import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.ChangeSetWriterImpl;
import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.clientapi.agent.drift.DriftAgentService;
-import org.rhq.core.domain.drift.DriftCategory;
-import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.core.domain.drift.DriftConfigurationDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.dto.DriftFileDTO;
import org.rhq.core.util.MessageDigestGenerator;
import org.rhq.core.util.ZipUtil;
+import org.rhq.enterprise.server.plugin.pc.drift.DriftChangeSetSummary;
import org.rhq.enterprise.server.plugins.drift.mongodb.dao.ChangeSetDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.dao.FileDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
-import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
-import org.rhq.test.JMockTest;
-import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.List;
+import java.util.Random;
+
import static java.util.Arrays.asList;
-import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.apache.commons.io.IOUtils.write;
import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
-import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.plannedChanges;
+import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
public class MongoDBDriftServerTest extends MongoDBTest {
- MessageDigestGenerator digestGenerator;
+ private MessageDigestGenerator digestGenerator;
+
+ private Random random;
+
+ private TestMongoDBDriftServer driftServer;
@BeforeClass
public void initClass() throws Exception {
digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ random = new Random();
}
@BeforeMethod
public void initTest() {
- Query deleteAll = ds.createQuery(MongoDBChangeSet.class);
- ds.delete(deleteAll);
+ clearCollections("changesets", "fs.files", "fs.chunks");
File basedir = getBaseDir();
basedir.delete();
getBaseDir().mkdirs();
+
+ driftServer = new TestMongoDBDriftServer();
+ driftServer.setConnection(connection);
+ driftServer.setMorphia(morphia);
+ driftServer.setDatastore(ds);
+ driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, "rhqtest"));
+ driftServer.setFileDAO(new FileDAO(ds.getDB()));
}
@Test
- public void persistChangeSetWithContentNotInDB() throws Exception {
+ public void persistInitialChangeSetWithContentNotInDB() throws Exception {
int driftDefId = 1;
- final String driftDefName = "saveInitialChangeSet";
+ final String driftDefName = "saveInitialChangeSetWithContentNotInDB";
final int resourceId = 1;
-
+
final Headers headers = new Headers();
headers.setBasedir(getBaseDir().getAbsolutePath());
headers.setDriftDefinitionId(driftDefId);
@@ -92,21 +96,16 @@ public class MongoDBDriftServerTest extends MongoDBTest {
headers.setResourceId(resourceId);
headers.setType(COVERAGE);
headers.setVersion(0);
-
- long timestamp = System.currentTimeMillis();
- long size = 1024;
-
+
+ String file1SHA = sha256("1a2b3c4d");
+ String file2SHA = sha256("1a2b3c4d");
+
File changeSetZip = createChangeSetZipFile(headers,
- addedFileEntry("1.txt", sha256("1a2b3c4d"), timestamp, size));
-
- TestMongoDBDriftServer driftServer = new TestMongoDBDriftServer();
- driftServer.setConnection(connection);
- driftServer.setMorphia(morphia);
- driftServer.setDatastore(ds);
- driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, "rhqtest"));
- driftServer.setFileDAO(new FileDAO(ds.getDB()));
-
- final List<? extends DriftFile> missingContent = asList(new TestDriftFile(sha256("1a2b3c4d")));
+ addedFileEntry("1.bin", file1SHA),
+ addedFileEntry("2.bin", file2SHA));
+
+ final List<? extends DriftFile> missingContent = asList(new TestDriftFile(file1SHA),
+ new TestDriftFile(file2SHA));
final DriftAgentService driftAgentService = context.mock(DriftAgentService.class);
context.checking(new Expectations() {{
@@ -116,18 +115,18 @@ public class MongoDBDriftServerTest extends MongoDBTest {
with(missingContent));
}});
driftServer.setDriftAgentService(driftAgentService);
-
+
// We can pass null for the subject because MongoDBDriftServer currently does not
// use the subject argument.
- driftServer.saveChangeSet(null, resourceId, changeSetZip);
-
+ DriftChangeSetSummary actualSummary = driftServer.saveChangeSet(null, resourceId, changeSetZip);
+
// verify that the change set was persisted
ChangeSetDAO changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
List<MongoDBChangeSet> changeSets = changeSetDAO.find().asList();
-
+
assertEquals(changeSets.size(), 1, "Expected to find one change set in the database.");
MongoDBChangeSet actual = changeSets.get(0);
-
+
MongoDBChangeSet expected = new MongoDBChangeSet();
// Need to set the id to actual.id. Since ids are random, we cannot use a canned
// value. We have to set it the same value that is in the database.
@@ -139,14 +138,188 @@ public class MongoDBDriftServerTest extends MongoDBTest {
expected.setVersion(0);
expected.setDriftHandlingMode(normal);
- MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("1.txt", FILE_ADDED);
- entry.setNewFileHash(sha256("1a2b3c4d"));
- expected.add(entry);
-
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("1.bin", FILE_ADDED);
+ entry1.setNewFileHash(file1SHA);
+ expected.add(entry1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("2.bin", FILE_ADDED);
+ entry2.setNewFileHash(file2SHA);
+ expected.add(entry2);
+
String[] ignore = new String[] {"id", "objectId", "ctime"};
assertChangeSetMatches("Failed to persist change set", expected, actual, ignore);
+
+ DriftChangeSetSummary expectedSummary = new DriftChangeSetSummary();
+ expectedSummary.setCategory(COVERAGE);
+ expectedSummary.setResourceId(resourceId);
+ expectedSummary.setDriftDefinitionName(driftDefName);
+ expectedSummary.setCreatedTime(actual.getCtime());
+
+ assertPropertiesMatch("The change set summary is wrong", expectedSummary, actualSummary);
}
-
+
+ @Test
+ public void persistInitialChangeSetWithContentInDB() throws Exception {
+ int driftDefId = 1;
+ final String driftDefName = "saveInitialChangeSetWithContentInDB";
+ final int resourceId = 1;
+
+ final Headers headers = new Headers();
+ headers.setBasedir(getBaseDir().getAbsolutePath());
+ headers.setDriftDefinitionId(driftDefId);
+ headers.setDriftDefinitionName(driftDefName);
+ headers.setResourceId(resourceId);
+ headers.setType(COVERAGE);
+ headers.setVersion(0);
+
+ String file1SHA = sha256("1a2b3c4d");
+ String file2SHA = sha256("1a2b3c4d");
+
+ // store content in the database
+ File file1 = createRandomFile(getBaseDir(), file1SHA, 1024);
+ File file2 = createRandomFile(getBaseDir(), file2SHA, 1024);
+
+ FileDAO fileDAO = new FileDAO(ds.getDB());
+ fileDAO.save(file1);
+ fileDAO.save(file2);
+
+ File changeSetZip = createChangeSetZipFile(headers,
+ addedFileEntry("1.bin", file1SHA),
+ addedFileEntry("2.bin", file2SHA));
+
+
+ final DriftAgentService driftAgentService = context.mock(DriftAgentService.class);
+ context.checking(new Expectations() {{
+ exactly(1).of(driftAgentService).ackChangeSet(resourceId, driftDefName);
+ }});
+ driftServer.setDriftAgentService(driftAgentService);
+
+ // We can pass null for the subject because MongoDBDriftServer currently does not
+ // use the subject argument.
+ DriftChangeSetSummary actualSummary = driftServer.saveChangeSet(null, resourceId, changeSetZip);
+
+ // verify that the change set was persisted
+ ChangeSetDAO changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
+ List<MongoDBChangeSet> changeSets = changeSetDAO.find().asList();
+
+ assertEquals(changeSets.size(), 1, "Expected to find one change set in the database.");
+ MongoDBChangeSet actual = changeSets.get(0);
+
+ MongoDBChangeSet expected = new MongoDBChangeSet();
+ // Need to set the id to actual.id. Since ids are random, we cannot use a canned
+ // value. We have to set it the same value that is in the database.
+ expected.setId(actual.getId());
+ expected.setDriftDefinitionId(driftDefId);
+ expected.setResourceId(resourceId);
+ expected.setDriftDefinitionName(driftDefName);
+ expected.setCategory(COVERAGE);
+ expected.setVersion(0);
+ expected.setDriftHandlingMode(normal);
+
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("1.bin", FILE_ADDED);
+ entry1.setNewFileHash(file1SHA);
+ expected.add(entry1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("2.bin", FILE_ADDED);
+ entry2.setNewFileHash(file2SHA);
+ expected.add(entry2);
+
+ String[] ignore = new String[] {"id", "objectId", "ctime"};
+ assertChangeSetMatches("Failed to persist change set", expected, actual, ignore);
+
+ DriftChangeSetSummary expectedSummary = new DriftChangeSetSummary();
+ expectedSummary.setCategory(COVERAGE);
+ expectedSummary.setResourceId(resourceId);
+ expectedSummary.setDriftDefinitionName(driftDefName);
+ expectedSummary.setCreatedTime(actual.getCtime());
+
+ assertPropertiesMatch("The change set summary is wrong", expectedSummary, actualSummary);
+ }
+
+ @Test
+ public void persistChangeSetWithSomeContentInDB() throws Exception {
+ int driftDefId = 1;
+ final String driftDefName = "saveChangeSetWithSomeContentInDB";
+ final int resourceId = 1;
+
+ final Headers headers = new Headers();
+ headers.setBasedir(getBaseDir().getAbsolutePath());
+ headers.setDriftDefinitionId(driftDefId);
+ headers.setDriftDefinitionName(driftDefName);
+ headers.setResourceId(resourceId);
+ headers.setType(DRIFT);
+ headers.setVersion(1);
+
+ String oldFile1SHA = sha256("1a2b3c4d");
+ String newFile1SHA = sha256("2a3b4c5d");
+ String file2SHA = sha256("1a2b3c4d");
+
+ // store content in the database
+ File oldFile1 = createRandomFile(getBaseDir(), oldFile1SHA, 1024);
+ File file2 = createRandomFile(getBaseDir(), file2SHA, 1024);
+
+ FileDAO fileDAO = new FileDAO(ds.getDB());
+ fileDAO.save(oldFile1);
+ fileDAO.save(file2);
+
+ File changeSetZip = createChangeSetZipFile(headers,
+ changedFileEntry("1.bin", oldFile1SHA, newFile1SHA),
+ removedFileEntry("2.bin", file2SHA));
+
+ final List<? extends DriftFile> missingContent = asList(new TestDriftFile(newFile1SHA));
+ final DriftAgentService driftAgentService = context.mock(DriftAgentService.class);
+ context.checking(new Expectations() {{
+ exactly(1).of(driftAgentService).ackChangeSet(resourceId, driftDefName);
+ exactly(1).of(driftAgentService).requestDriftFiles(with(resourceId), with(any(Headers.class)),
+ with(missingContent));
+ }});
+ driftServer.setDriftAgentService(driftAgentService);
+
+ // We can pass null for the subject because MongoDBDriftServer currently does not
+ // use the subject argument.
+ DriftChangeSetSummary actualSummary = driftServer.saveChangeSet(null, resourceId, changeSetZip);
+
+ // verify that the change set was persisted
+ ChangeSetDAO changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
+ List<MongoDBChangeSet> changeSets = changeSetDAO.find().asList();
+
+ assertEquals(changeSets.size(), 1, "Expected to find one change set in the database.");
+ MongoDBChangeSet actual = changeSets.get(0);
+
+ MongoDBChangeSet expected = new MongoDBChangeSet();
+ // Need to set the id to actual.id. Since ids are random, we cannot use a canned
+ // value. We have to set it the same value that is in the database.
+ expected.setId(actual.getId());
+ expected.setDriftDefinitionId(driftDefId);
+ expected.setResourceId(resourceId);
+ expected.setDriftDefinitionName(driftDefName);
+ expected.setCategory(DRIFT);
+ expected.setVersion(1);
+ expected.setDriftHandlingMode(normal);
+
+ MongoDBChangeSetEntry entry1 = new MongoDBChangeSetEntry("1.bin", FILE_CHANGED);
+ entry1.setOldFileHash(oldFile1SHA);
+ entry1.setNewFileHash(newFile1SHA);
+ expected.add(entry1);
+
+ MongoDBChangeSetEntry entry2 = new MongoDBChangeSetEntry("2.bin", FILE_REMOVED);
+ entry2.setOldFileHash(file2SHA);
+ expected.add(entry2);
+
+ String[] ignore = new String[] {"id", "objectId", "ctime"};
+ assertChangeSetMatches("Failed to persist change set", expected, actual, ignore);
+
+ DriftChangeSetSummary expectedSummary = new DriftChangeSetSummary();
+ expectedSummary.setCategory(DRIFT);
+ expectedSummary.setResourceId(resourceId);
+ expectedSummary.setDriftDefinitionName(driftDefName);
+ expectedSummary.setCreatedTime(actual.getCtime());
+ expectedSummary.addDriftPathname("1.bin");
+ expectedSummary.addDriftPathname("2.bin");
+
+ assertPropertiesMatch("The change set summary is wrong", expectedSummary, actualSummary);
+ }
+
protected File createChangeSetZipFile(Headers headers, FileEntry... fileEntries) throws Exception {
ChangeSetWriter writer = newChangeSetWriter(headers);
for (FileEntry entry : fileEntries) {
@@ -187,13 +360,34 @@ public class MongoDBDriftServerTest extends MongoDBTest {
return new File("target", getClass().getSimpleName());
}
+ protected FileEntry addedFileEntry(String path, String sha256) {
+ long timestamp = System.currentTimeMillis();
+ long size = 1024;
+ return FileEntry.addedFileEntry(path, sha256, timestamp, size);
+ }
+
+ protected FileEntry changedFileEntry(String path, String oldSHA, String newSHA) {
+ long timestamp = System.currentTimeMillis();
+ long size = 1024;
+ return FileEntry.changedFileEntry(path, oldSHA, newSHA, timestamp, size);
+ }
+
+ protected FileEntry removedFileEntry(String path, String oldSHA) {
+ return FileEntry.removedFileEntry(path, oldSHA);
+ }
+
protected String sha256(String string) {
return digestGenerator.calcDigestString(string);
}
- protected DriftFileDTO newDriftFile(String hash) {
- DriftFileDTO file = new DriftFileDTO();
- file.setHashId(hash);
+ protected File createRandomFile(File dir, String fileName, int numBytes) throws Exception {
+ File file = new File(dir, fileName);
+ FileOutputStream stream = new FileOutputStream(file);
+ byte[] bytes = new byte[numBytes];
+ random.nextBytes(bytes);
+ write(bytes, stream);
+ stream.close();
+
return file;
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
index 847ccbd..d4a381a 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
@@ -1,16 +1,32 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 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.enterprise.server.plugins.drift.mongodb;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
-import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
-import org.rhq.enterprise.server.plugins.drift.mongodb.dao.ChangeSetDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import org.rhq.test.JMockTest;
import org.testng.annotations.BeforeClass;
-import org.testng.annotations.BeforeMethod;
import java.util.ArrayList;
import java.util.List;
@@ -42,6 +58,12 @@ public class MongoDBTest extends JMockTest {
ds = morphia.createDatastore(connection, "rhqtest");
}
+ protected void clearCollections(String... collections) {
+ for (String collection : collections) {
+ ds.getDB().getCollection(collection).drop();
+ }
+ }
+
/**
* Verifies that the actual list of change sets match the expected list of change sets.
* The order of the lists is expected to be the same.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index aaee50c..5b1b768 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -19,31 +19,25 @@
package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
-import java.util.List;
-
-import com.google.code.morphia.query.Query;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
+import org.rhq.core.domain.criteria.GenericDriftCriteria;
+import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.util.PageOrdering;
import org.rhq.enterprise.server.plugins.drift.mongodb.MongoDBTest;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
-import org.rhq.core.domain.criteria.GenericDriftCriteria;
-import org.rhq.core.domain.drift.DriftChangeSetCategory;
-import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
-import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
+import java.util.List;
import static java.util.Arrays.asList;
-import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
-import static org.rhq.core.domain.drift.DriftCategory.FILE_CHANGED;
-import static org.rhq.core.domain.drift.DriftCategory.FILE_REMOVED;
+import static org.rhq.core.domain.drift.DriftCategory.*;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.DRIFT;
import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
-import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class ChangeSetDAOTest extends MongoDBTest {
@@ -52,8 +46,7 @@ public class ChangeSetDAOTest extends MongoDBTest {
@BeforeMethod
public void initDAO() {
- Query deleteAll = ds.createQuery(MongoDBChangeSet.class);
- ds.delete(deleteAll);
+ clearCollections("changesets");
dao = new ChangeSetDAO(morphia, connection, "rhqtest");
}
commit 6a2753b1f574c5f3cab6901e149ca4d0aa4dcf10
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Feb 25 10:46:38 2012 -0500
Adding some more verification logic
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index f3f6fcf..242da58 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -27,6 +27,7 @@ import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
+import org.bson.types.ObjectId;
import org.jmock.Expectations;
import org.rhq.common.drift.ChangeSetWriter;
import org.rhq.common.drift.ChangeSetWriterImpl;
@@ -55,6 +56,7 @@ import static java.util.Arrays.asList;
import static org.rhq.common.drift.FileEntry.addedFileEntry;
import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.normal;
import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.plannedChanges;
import static org.testng.Assert.assertEquals;
@@ -121,23 +123,28 @@ public class MongoDBDriftServerTest extends MongoDBTest {
// verify that the change set was persisted
ChangeSetDAO changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
- List<MongoDBChangeSet> actual = changeSetDAO.find().asList();
+ List<MongoDBChangeSet> changeSets = changeSetDAO.find().asList();
- MongoDBChangeSet changeSet = new MongoDBChangeSet();
- changeSet.setDriftDefinitionId(driftDefId);
- changeSet.setResourceId(resourceId);
- changeSet.setDriftDefinitionName(driftDefName);
- changeSet.setCategory(COVERAGE);
- changeSet.setVersion(0);
- changeSet.setDriftHandlingMode(plannedChanges);
+ assertEquals(changeSets.size(), 1, "Expected to find one change set in the database.");
+ MongoDBChangeSet actual = changeSets.get(0);
+
+ MongoDBChangeSet expected = new MongoDBChangeSet();
+ // Need to set the id to actual.id. Since ids are random, we cannot use a canned
+ // value. We have to set it the same value that is in the database.
+ expected.setId(actual.getId());
+ expected.setDriftDefinitionId(driftDefId);
+ expected.setResourceId(resourceId);
+ expected.setDriftDefinitionName(driftDefName);
+ expected.setCategory(COVERAGE);
+ expected.setVersion(0);
+ expected.setDriftHandlingMode(normal);
MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("1.txt", FILE_ADDED);
entry.setNewFileHash(sha256("1a2b3c4d"));
- changeSet.add(entry);
+ expected.add(entry);
- List<MongoDBChangeSet> expected = asList(changeSet);
-
- assertEquals(actual.size(), 1, "Expected to find one change set");
+ String[] ignore = new String[] {"id", "objectId", "ctime"};
+ assertChangeSetMatches("Failed to persist change set", expected, actual, ignore);
}
protected File createChangeSetZipFile(Headers headers, FileEntry... fileEntries) throws Exception {
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
index 75a086b..847ccbd 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
@@ -12,8 +12,10 @@ import org.rhq.test.JMockTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
+import java.util.ArrayList;
import java.util.List;
+import static java.util.Arrays.asList;
import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
@@ -40,6 +42,14 @@ public class MongoDBTest extends JMockTest {
ds = morphia.createDatastore(connection, "rhqtest");
}
+ /**
+ * Verifies that the actual list of change sets match the expected list of change sets.
+ * The order of the lists is expected to be the same.
+ *
+ * @param msg
+ * @param expected
+ * @param actual
+ */
protected void assertChangeSetsMatch(String msg, List<MongoDBChangeSet> expected, List<MongoDBChangeSet> actual) {
assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
int i = 0;
@@ -74,6 +84,31 @@ public class MongoDBTest extends JMockTest {
* This method first checks that the actual change set is not null. It then performs a
* property-wise comparison against the expected change set using
* {@link org.rhq.test.AssertUtils#assertPropertiesMatch(String, Object, Object, String...) assertPropertiesMatch}.
+ * The {@link MongoDBChangeSet#getDrifts() drifts} property is then tested separately
+ * using
+ * {@link org.rhq.test.AssertUtils#assertCollectionMatchesNoOrder(String, java.util.Collection, java.util.Collection, String...) assertCollectionMatches}.
+ *
+ * @param msg An error message
+ * @param expected The expected change set to test against
+ * @param actual The actual change set under test
+ * @param ignoredProperties Properties of the MongoDBChangeSet to exclude from comparison
+ */
+ protected void assertChangeSetMatches(String msg, MongoDBChangeSet expected, MongoDBChangeSet actual,
+ String... ignoredProperties) {
+ assertNotNull(actual, msg + ": change set is null");
+
+ List<String> ignore = new ArrayList<String>(asList(ignoredProperties));
+ ignore.add("drifts");
+ assertPropertiesMatch(msg, expected, actual, ignore);
+
+ assertCollectionMatchesNoOrder(msg + ": " + "change set entries do not match expected entries.", expected
+ .getDrifts(), actual.getDrifts(), "changeSet", "ctime");
+ }
+
+ /**
+ * This method first checks that the actual change set is not null. It then performs a
+ * property-wise comparison against the expected change set using
+ * {@link org.rhq.test.AssertUtils#assertPropertiesMatch(String, Object, Object, String...) assertPropertiesMatch}.
* The {@link org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet#getDrifts() drifts}
* property is then tested separately using
* {@link org.rhq.test.AssertUtils#assertCollectionMatchesNoOrder(String, java.util.Collection, java.util.Collection, String...) assertCollectionMatches}.
commit f8167735f7cad6c01efca7a9fec0cf315f06b316
Author: John Sanda <jsanda(a)redhat.com>
Date: Mon Feb 20 09:50:27 2012 -0500
Refactoring tests to pull common test code into base test class
This is the initial commit for MongoDBTest. A previous commit added the
oldDriftFile and newDriftFile properties in MongoDBChangeSetEntry. This
broke some tests in ChangeSetDAOTest since MongoDBFile does not
implement equals/hashCode. I have implemented equals/hashCode for
MongoDBFile in this commit to fix those failing tests.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java
index 344614b..1da12e3 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java
@@ -71,4 +71,20 @@ public class MongoDBFile implements Serializable, DriftFile {
this.status = status;
}
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ MongoDBFile that = (MongoDBFile) o;
+
+ if (hash != null ? !hash.equals(that.hash) : that.hash != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return hash != null ? hash.hashCode() : 0;
+ }
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index 5ad406f..f3f6fcf 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -24,6 +24,7 @@ import java.util.List;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
+import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import org.jmock.Expectations;
@@ -32,7 +33,9 @@ import org.rhq.common.drift.ChangeSetWriterImpl;
import org.rhq.common.drift.FileEntry;
import org.rhq.common.drift.Headers;
import org.rhq.core.clientapi.agent.drift.DriftAgentService;
+import org.rhq.core.domain.drift.DriftCategory;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
+import org.rhq.core.domain.drift.DriftConfigurationDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.dto.DriftFileDTO;
import org.rhq.core.util.MessageDigestGenerator;
@@ -43,37 +46,32 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import org.rhq.test.JMockTest;
+import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static java.util.Arrays.asList;
import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+import static org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode.plannedChanges;
+import static org.testng.Assert.assertEquals;
-public class MongoDBDriftServerTest extends JMockTest {
-
- Mongo connection;
-
- Morphia morphia;
-
- Datastore ds;
-
- String db = "rhqtest";
+public class MongoDBDriftServerTest extends MongoDBTest {
MessageDigestGenerator digestGenerator;
@BeforeClass
- public void initDB() throws Exception {
- connection = new Mongo("127.0.0.1");
- morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class);
- ds = morphia.createDatastore(connection, db);
-
+ public void initClass() throws Exception {
digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
}
@BeforeMethod
public void initTest() {
+ Query deleteAll = ds.createQuery(MongoDBChangeSet.class);
+ ds.delete(deleteAll);
+
File basedir = getBaseDir();
basedir.delete();
getBaseDir().mkdirs();
@@ -103,7 +101,7 @@ public class MongoDBDriftServerTest extends JMockTest {
driftServer.setConnection(connection);
driftServer.setMorphia(morphia);
driftServer.setDatastore(ds);
- driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, db));
+ driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, "rhqtest"));
driftServer.setFileDAO(new FileDAO(ds.getDB()));
final List<? extends DriftFile> missingContent = asList(new TestDriftFile(sha256("1a2b3c4d")));
@@ -120,6 +118,26 @@ public class MongoDBDriftServerTest extends JMockTest {
// We can pass null for the subject because MongoDBDriftServer currently does not
// use the subject argument.
driftServer.saveChangeSet(null, resourceId, changeSetZip);
+
+ // verify that the change set was persisted
+ ChangeSetDAO changeSetDAO = new ChangeSetDAO(morphia, connection, "rhqtest");
+ List<MongoDBChangeSet> actual = changeSetDAO.find().asList();
+
+ MongoDBChangeSet changeSet = new MongoDBChangeSet();
+ changeSet.setDriftDefinitionId(driftDefId);
+ changeSet.setResourceId(resourceId);
+ changeSet.setDriftDefinitionName(driftDefName);
+ changeSet.setCategory(COVERAGE);
+ changeSet.setVersion(0);
+ changeSet.setDriftHandlingMode(plannedChanges);
+
+ MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry("1.txt", FILE_ADDED);
+ entry.setNewFileHash(sha256("1a2b3c4d"));
+ changeSet.add(entry);
+
+ List<MongoDBChangeSet> expected = asList(changeSet);
+
+ assertEquals(actual.size(), 1, "Expected to find one change set");
}
protected File createChangeSetZipFile(Headers headers, FileEntry... fileEntries) throws Exception {
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
new file mode 100644
index 0000000..75a086b
--- /dev/null
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBTest.java
@@ -0,0 +1,95 @@
+package org.rhq.enterprise.server.plugins.drift.mongodb;
+
+import com.google.code.morphia.Datastore;
+import com.google.code.morphia.Morphia;
+import com.google.code.morphia.query.Query;
+import com.mongodb.Mongo;
+import org.rhq.enterprise.server.plugins.drift.mongodb.dao.ChangeSetDAO;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
+import org.rhq.test.JMockTest;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+
+import java.util.List;
+
+import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
+import static org.rhq.test.AssertUtils.assertPropertiesMatch;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+public class MongoDBTest extends JMockTest {
+
+ // Tests need to be disabled when committed/pushed to the remote repo until we get
+ // mongodb installed on the hudson slave
+ public static final boolean ENABLED = true;
+
+ protected Mongo connection;
+
+ protected Morphia morphia;
+
+ protected Datastore ds;
+
+ @BeforeClass
+ public void initDB() throws Exception {
+ connection = new Mongo("127.0.0.1");
+
+ morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class);
+
+ ds = morphia.createDatastore(connection, "rhqtest");
+ }
+
+ protected void assertChangeSetsMatch(String msg, List<MongoDBChangeSet> expected, List<MongoDBChangeSet> actual) {
+ assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
+ int i = 0;
+ for (MongoDBChangeSet expectedChangeSet : expected) {
+ assertChangeSetMatches("Change sets do not match: " + msg, expectedChangeSet, actual.get(i++));
+ }
+ }
+
+ protected void assertChangeSetsMatchNoOrder(String msg, List<MongoDBChangeSet> expected,
+ List<MongoDBChangeSet> actual) {
+ assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
+ for (MongoDBChangeSet expectedChangeSet : expected) {
+ MongoDBChangeSet actualChangeSet = null;
+ for (MongoDBChangeSet changeSet : actual) {
+ if (expectedChangeSet.getObjectId().equals(changeSet.getObjectId())) {
+ actualChangeSet = changeSet;
+ break;
+ }
+ }
+ assertNotNull(actualChangeSet, msg + ": expected to find change set " + expectedChangeSet);
+ assertChangeSetMatches(msg, expectedChangeSet, actualChangeSet);
+ }
+ }
+
+ protected void assertEntriesMatch(String msg, List<MongoDBChangeSetEntry> expected,
+ List<MongoDBChangeSetEntry> actual) {
+ assertEquals(actual.size(), expected.size(), "The number of entries differ: " + msg);
+ assertCollectionMatchesNoOrder(msg, expected, actual, "changeSet");
+ }
+
+ /**
+ * This method first checks that the actual change set is not null. It then performs a
+ * property-wise comparison against the expected change set using
+ * {@link org.rhq.test.AssertUtils#assertPropertiesMatch(String, Object, Object, String...) assertPropertiesMatch}.
+ * The {@link org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet#getDrifts() drifts}
+ * property is then tested separately using
+ * {@link org.rhq.test.AssertUtils#assertCollectionMatchesNoOrder(String, java.util.Collection, java.util.Collection, String...) assertCollectionMatches}.
+ *
+ * @param msg An error message
+ * @param expected The expected change set to test against
+ * @param actual The actual change set under test
+ */
+ protected void assertChangeSetMatches(String msg, MongoDBChangeSet expected, MongoDBChangeSet actual) {
+ assertNotNull(actual, msg + ": change set is null");
+
+ String ignore = "drifts";
+ assertPropertiesMatch(msg, expected, actual, ignore);
+
+ ignore = "changeSet";
+ assertCollectionMatchesNoOrder(msg + ": " + "change set entries do not match expected entries.", expected
+ .getDrifts(), actual.getDrifts(), ignore);
+ }
+}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index 4e9c0e0..aaee50c 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -21,14 +21,10 @@ package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
import java.util.List;
-import com.google.code.morphia.Datastore;
-import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
-import com.mongodb.Mongo;
-
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.rhq.core.domain.util.PageOrdering;
-import org.testng.annotations.BeforeClass;
+import org.rhq.enterprise.server.plugins.drift.mongodb.MongoDBTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -36,7 +32,6 @@ import org.rhq.core.domain.criteria.GenericDriftCriteria;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
-import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import static java.util.Arrays.asList;
import static org.rhq.core.domain.drift.DriftCategory.FILE_ADDED;
@@ -51,34 +46,14 @@ import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
-public class ChangeSetDAOTest {
-
- // Tests need to be disabled when committed/pushed to the remote repo until we get
- // mongodb installed on the hudson slave
- static final boolean ENABLED = true;
-
- Mongo connection;
-
- Morphia morphia;
-
- Datastore ds;
+public class ChangeSetDAOTest extends MongoDBTest {
ChangeSetDAO dao;
- @BeforeClass
- public void initDB() throws Exception {
- connection = new Mongo("127.0.0.1");
-
- morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class);
-
- ds = morphia.createDatastore(connection, "rhqtest");
- }
-
@BeforeMethod
- public void clearCollections() throws Exception {
+ public void initDAO() {
Query deleteAll = ds.createQuery(MongoDBChangeSet.class);
ds.delete(deleteAll);
-
dao = new ChangeSetDAO(morphia, connection, "rhqtest");
}
@@ -965,59 +940,6 @@ public class ChangeSetDAOTest {
assertTrue(dao.find().asList().isEmpty(), "Failed to delete one or more change sets");
}
-
- private void assertChangeSetsMatch(String msg, List<MongoDBChangeSet> expected, List<MongoDBChangeSet> actual) {
- assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
- int i = 0;
- for (MongoDBChangeSet expectedChangeSet : expected) {
- assertChangeSetMatches("Change sets do not match: " + msg, expectedChangeSet, actual.get(i++));
- }
- }
-
- private void assertChangeSetsMatchNoOrder(String msg, List<MongoDBChangeSet> expected,
- List<MongoDBChangeSet> actual) {
- assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
- for (MongoDBChangeSet expectedChangeSet : expected) {
- MongoDBChangeSet actualChangeSet = null;
- for (MongoDBChangeSet changeSet : actual) {
- if (expectedChangeSet.getObjectId().equals(changeSet.getObjectId())) {
- actualChangeSet = changeSet;
- break;
- }
- }
- assertNotNull(actualChangeSet, msg + ": expected to find change set " + expectedChangeSet);
- assertChangeSetMatches(msg, expectedChangeSet, actualChangeSet);
- }
- }
-
- private void assertEntriesMatch(String msg, List<MongoDBChangeSetEntry> expected,
- List<MongoDBChangeSetEntry> actual) {
- assertEquals(actual.size(), expected.size(), "The number of entries differ: " + msg);
- assertCollectionMatchesNoOrder(msg, expected, actual, "changeSet");
- }
-
- /**
- * This method first checks that the actual change set is not null. It then performs a
- * property-wise comparison against the expected change set using
- * {@link org.rhq.test.AssertUtils#assertPropertiesMatch(String, Object, Object, String...) assertPropertiesMatch}.
- * The {@link org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet#getDrifts() drifts}
- * property is then tested separately using
- * {@link org.rhq.test.AssertUtils#assertCollectionMatchesNoOrder(String, java.util.Collection, java.util.Collection, String...) assertCollectionMatches}.
- *
- * @param msg An error message
- * @param expected The expected change set to test against
- * @param actual The actual change set under test
- */
- void assertChangeSetMatches(String msg, MongoDBChangeSet expected, MongoDBChangeSet actual) {
- assertNotNull(actual, msg + ": change set is null");
-
- String ignore = "drifts";
- assertPropertiesMatch(msg, expected, actual, ignore);
-
- ignore = "changeSet";
- assertCollectionMatchesNoOrder(msg + ": " + "change set entries do not match expected entries.", expected
- .getDrifts(), actual.getDrifts(), ignore);
- }
/**
* A convenience factory method for creating a change set.
commit f17d2b07d9d6745c0d4d745b6feaa46041fe5231
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Feb 19 22:26:57 2012 -0500
Adding verification logic for calls to agent
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
index 66b86f6..5ad406f 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -80,7 +80,7 @@ public class MongoDBDriftServerTest extends JMockTest {
}
@Test
- public void saveInitialChangeSet() throws Exception {
+ public void persistChangeSetWithContentNotInDB() throws Exception {
int driftDefId = 1;
final String driftDefName = "saveInitialChangeSet";
final int resourceId = 1;
@@ -106,13 +106,14 @@ public class MongoDBDriftServerTest extends JMockTest {
driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, db));
driftServer.setFileDAO(new FileDAO(ds.getDB()));
- final List<? extends DriftFile> missingContent = asList(newDriftFile(sha256("1a2b3c4d")));
+ final List<? extends DriftFile> missingContent = asList(new TestDriftFile(sha256("1a2b3c4d")));
final DriftAgentService driftAgentService = context.mock(DriftAgentService.class);
context.checking(new Expectations() {{
- allowing(driftAgentService).ackChangeSet(resourceId, driftDefName);
- allowing(driftAgentService).requestDriftFiles(with(resourceId), with(any(Headers.class)),
- with(any(List.class)));
+ exactly(1).of(driftAgentService).ackChangeSet(resourceId, driftDefName);
+ // TODO Need to verify that we send the correct headers to the agent
+ exactly(1).of(driftAgentService).requestDriftFiles(with(resourceId), with(any(Headers.class)),
+ with(missingContent));
}});
driftServer.setDriftAgentService(driftAgentService);
@@ -184,5 +185,44 @@ public class MongoDBDriftServerTest extends JMockTest {
this.driftAgentService = driftAgentService;
}
}
+
+ /**
+ * {@link DriftFileDTO} does not implement equals/hashCode which makes some of the
+ * verification a little tricky in situations where collections of DriftFile objects
+ * are getting passed around. This subclass implements equals and hashCode.
+ */
+ private static class TestDriftFile extends DriftFileDTO {
+
+ public TestDriftFile(String hash) {
+ super();
+ setHashId(hash);
+ }
+
+ /**
+ * Equality is based soley on the {@link #getHashId() hashId} property.
+ *
+ * @param o The object to compare against
+ * @return true if the object is a TestDriftFile and has the same hashId.
+ */
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || !(o instanceof DriftFileDTO)) return false;
+
+ DriftFileDTO that = (DriftFileDTO) o;
+
+ if (!getHashId().equals(that.getHashId())) return false;
+
+ return true;
+ }
+
+ /**
+ * @return A hash code based on the {@link #getHashId() hashId} property.
+ */
+ @Override
+ public int hashCode() {
+ return getHashId().hashCode();
+ }
+ }
}
commit d0e52b9bc7ebb41e8c6eda4c9da63e6068f71983
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Feb 18 22:35:55 2012 -0500
Initial commit for MongoDBDriftServerTest
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 3d6cbd8..aeb600e 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -98,6 +98,46 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
private FileDAO fileDAO;
+ public Mongo getConnection() {
+ return connection;
+ }
+
+ public void setConnection(Mongo connection) {
+ this.connection = connection;
+ }
+
+ public Morphia getMorphia() {
+ return morphia;
+ }
+
+ public void setMorphia(Morphia morphia) {
+ this.morphia = morphia;
+ }
+
+ public Datastore getDatastore() {
+ return ds;
+ }
+
+ public void setDatastore(Datastore ds) {
+ this.ds = ds;
+ }
+
+ public ChangeSetDAO getChangeSetDAO() {
+ return changeSetDAO;
+ }
+
+ public void setChangeSetDAO(ChangeSetDAO changeSetDAO) {
+ this.changeSetDAO = changeSetDAO;
+ }
+
+ public FileDAO getFileDAO() {
+ return fileDAO;
+ }
+
+ public void setFileDAO(FileDAO fileDAO) {
+ this.fileDAO = fileDAO;
+ }
+
@Override
public void initialize(ServerPluginContext context) throws Exception {
connection = new Mongo("127.0.0.1");
@@ -109,22 +149,19 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public void start() {
-
}
@Override
public void stop() {
-
}
@Override
public void shutdown() {
-
}
@Override
public DriftChangeSetSummary saveChangeSet(final Subject subject, final int resourceId, final File changeSetZip)
- throws Exception {
+ throws Exception {
final DriftChangeSetSummary summary = new DriftChangeSetSummary();
@@ -197,8 +234,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
// in effect suspend drift detection (for the particular definition) until
// it receives the ACK. Secondly, we need to tell the agent to send the
// actual file bits for any change set content we do not have.
- AgentClient agent = getAgentManager().getAgentClient(getSubjectManager().getOverlord(), resourceId);
- DriftAgentService driftService = agent.getDriftAgentService();
+ DriftAgentService driftService = getDriftAgentService(resourceId);
driftService.ackChangeSet(headers.getResourceId(), headers.getDriftDefinitionName());
if (!missingContent.isEmpty()) {
driftService.requestDriftFiles(resourceId, headers, missingContent);
@@ -210,6 +246,11 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return summary;
}
+
+ protected DriftAgentService getDriftAgentService(int resourceId) {
+ AgentClient agent = getAgentManager().getAgentClient(getSubjectManager().getOverlord(), resourceId);
+ return agent.getDriftAgentService();
+ }
private DriftFileDTO newDriftFile(String hash) {
DriftFileDTO file = new DriftFileDTO();
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
new file mode 100644
index 0000000..66b86f6
--- /dev/null
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServerTest.java
@@ -0,0 +1,188 @@
+/*
+ * RHQ Management Platform
+ * Copyright (C) 2005-2008 Red Hat, Inc.
+ * All rights reserved.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation version 2 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+package org.rhq.enterprise.server.plugins.drift.mongodb;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import com.google.code.morphia.Datastore;
+import com.google.code.morphia.Morphia;
+import com.mongodb.Mongo;
+
+import org.jmock.Expectations;
+import org.rhq.common.drift.ChangeSetWriter;
+import org.rhq.common.drift.ChangeSetWriterImpl;
+import org.rhq.common.drift.FileEntry;
+import org.rhq.common.drift.Headers;
+import org.rhq.core.clientapi.agent.drift.DriftAgentService;
+import org.rhq.core.domain.drift.DriftChangeSetCategory;
+import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.dto.DriftFileDTO;
+import org.rhq.core.util.MessageDigestGenerator;
+import org.rhq.core.util.ZipUtil;
+import org.rhq.enterprise.server.plugins.drift.mongodb.dao.ChangeSetDAO;
+import org.rhq.enterprise.server.plugins.drift.mongodb.dao.FileDAO;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
+import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
+import org.rhq.test.JMockTest;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static java.util.Arrays.asList;
+import static org.rhq.common.drift.FileEntry.addedFileEntry;
+import static org.rhq.core.domain.drift.DriftChangeSetCategory.COVERAGE;
+
+public class MongoDBDriftServerTest extends JMockTest {
+
+ Mongo connection;
+
+ Morphia morphia;
+
+ Datastore ds;
+
+ String db = "rhqtest";
+
+ MessageDigestGenerator digestGenerator;
+
+ @BeforeClass
+ public void initDB() throws Exception {
+ connection = new Mongo("127.0.0.1");
+ morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class);
+ ds = morphia.createDatastore(connection, db);
+
+ digestGenerator = new MessageDigestGenerator(MessageDigestGenerator.SHA_256);
+ }
+
+ @BeforeMethod
+ public void initTest() {
+ File basedir = getBaseDir();
+ basedir.delete();
+ getBaseDir().mkdirs();
+ }
+
+ @Test
+ public void saveInitialChangeSet() throws Exception {
+ int driftDefId = 1;
+ final String driftDefName = "saveInitialChangeSet";
+ final int resourceId = 1;
+
+ final Headers headers = new Headers();
+ headers.setBasedir(getBaseDir().getAbsolutePath());
+ headers.setDriftDefinitionId(driftDefId);
+ headers.setDriftDefinitionName(driftDefName);
+ headers.setResourceId(resourceId);
+ headers.setType(COVERAGE);
+ headers.setVersion(0);
+
+ long timestamp = System.currentTimeMillis();
+ long size = 1024;
+
+ File changeSetZip = createChangeSetZipFile(headers,
+ addedFileEntry("1.txt", sha256("1a2b3c4d"), timestamp, size));
+
+ TestMongoDBDriftServer driftServer = new TestMongoDBDriftServer();
+ driftServer.setConnection(connection);
+ driftServer.setMorphia(morphia);
+ driftServer.setDatastore(ds);
+ driftServer.setChangeSetDAO(new ChangeSetDAO(morphia, connection, db));
+ driftServer.setFileDAO(new FileDAO(ds.getDB()));
+
+ final List<? extends DriftFile> missingContent = asList(newDriftFile(sha256("1a2b3c4d")));
+
+ final DriftAgentService driftAgentService = context.mock(DriftAgentService.class);
+ context.checking(new Expectations() {{
+ allowing(driftAgentService).ackChangeSet(resourceId, driftDefName);
+ allowing(driftAgentService).requestDriftFiles(with(resourceId), with(any(Headers.class)),
+ with(any(List.class)));
+ }});
+ driftServer.setDriftAgentService(driftAgentService);
+
+ // We can pass null for the subject because MongoDBDriftServer currently does not
+ // use the subject argument.
+ driftServer.saveChangeSet(null, resourceId, changeSetZip);
+ }
+
+ protected File createChangeSetZipFile(Headers headers, FileEntry... fileEntries) throws Exception {
+ ChangeSetWriter writer = newChangeSetWriter(headers);
+ for (FileEntry entry : fileEntries) {
+ writer.write(entry);
+ }
+ writer.close();
+
+ File zipFile = new File(getBaseDir(), "changeset.zip");
+ ZipUtil.zipFileOrDirectory(getChangeSetFile(), zipFile);
+
+ return zipFile;
+ }
+
+ /**
+ * Initializes a {@link ChangeSetWriter} that will write to a file returned from
+ * {@link #getChangeSetFile()}
+ *
+ * @return A new {@link ChangeSetWriter}
+ */
+ protected ChangeSetWriter newChangeSetWriter(Headers headers) throws Exception {
+ return new ChangeSetWriterImpl(getChangeSetFile(), headers);
+ }
+
+ /**
+ * @return A file named changeset.txt located in {@link #getBaseDir() basedir}
+ */
+ protected File getChangeSetFile() {
+ return new File(getBaseDir(), "changeset.txt");
+ }
+
+ /**
+ * Returns a File object that denotes the base directory for this test class. That
+ * directory by default is <project_basedir>target/<test_class_name>
+ *
+ * @return The base directory for this test class
+ */
+ protected File getBaseDir() {
+ return new File("target", getClass().getSimpleName());
+ }
+
+ protected String sha256(String string) {
+ return digestGenerator.calcDigestString(string);
+ }
+
+ protected DriftFileDTO newDriftFile(String hash) {
+ DriftFileDTO file = new DriftFileDTO();
+ file.setHashId(hash);
+ return file;
+ }
+
+ private static class TestMongoDBDriftServer extends MongoDBDriftServer {
+
+ public DriftAgentService driftAgentService;
+
+ @Override
+ public DriftAgentService getDriftAgentService(int resourceId) {
+ return driftAgentService;
+ }
+
+ public void setDriftAgentService(DriftAgentService driftAgentService) {
+ this.driftAgentService = driftAgentService;
+ }
+ }
+
+}
commit 67b9ce8f6d375764e2f99e666477902b3455d043
Author: John Sanda <jsanda(a)redhat.com>
Date: Thu Feb 16 21:31:59 2012 -0500
Adding initial impl for copyChangeSet
copyChangeSet is called from DriftManagerBean when creating a definition
from a pinned template.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index fc1155e..3d6cbd8 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -387,8 +387,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
newChangeSet.setDriftDefinitionId(changeSet.getDriftDefinitionId());
if (!isTemplateChangeSet(changeSet)) {
- DriftManagerLocal driftMgr = LookupUtil.getDriftManager();
- DriftDefinition driftDef = driftMgr.getDriftDefinition(subject, changeSet.getDriftDefinitionId());
+ DriftDefinition driftDef = getDriftDef(subject, changeSet.getDriftDefinitionId());
if (driftDef == null) {
throw new IllegalArgumentException("Cannot persist change set. " +
DriftDefinition.class.getSimpleName() + " with id " + changeSet.getDriftDefinitionId() +
@@ -407,9 +406,9 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
newChangeSet.add(entry);
}
- Key key = changeSetDAO.save(newChangeSet);
- ObjectId id = (ObjectId) key.getId();
- return id.toString();
+ changeSetDAO.save(newChangeSet);
+
+ return newChangeSet.getId();
}
private boolean isTemplateChangeSet(DriftChangeSet<?> changeSet) {
@@ -418,8 +417,21 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public String copyChangeSet(Subject subject, String changeSetId, int driftDefId, int resourceId) {
- // TODO Auto-generated method stub
- return null;
+ // TODO Pass definition name in as an argument
+ // We need to store the definition name to support deletes. This method is invoked
+ // from DriftManagerBean.updateDriftDefinition when creating a definition from a
+ // pinned template. Because the transaction in which the definition is created has
+ // not yet been committed when this method is invoked, we cannot look up the
+ // definition.
+
+ MongoDBChangeSet changeSet = changeSetDAO.findOne("id", new ObjectId(changeSetId));
+ changeSet.setDriftDefinitionId(driftDefId);
+ changeSet.setResourceId(resourceId);
+ changeSet.setId(new ObjectId());
+
+ changeSetDAO.save(changeSet);
+
+ return changeSet.getId();
}
@Override
@@ -430,4 +442,9 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
}
return StreamUtil.slurp(file.getInputStream());
}
+
+ private DriftDefinition getDriftDef(Subject subject, int id) {
+ DriftManagerLocal driftMgr = LookupUtil.getDriftManager();
+ return driftMgr.getDriftDefinition(subject, id);
+ }
}
commit 8e2c6f21f3c11cdf65e9a3d8c9b430683e36c168
Author: John Sanda <jsanda(a)redhat.com>
Date: Thu Feb 16 17:37:15 2012 -0500
Fixing a couple bugs involving file hashes
In saveChangeSet, I was not setting the file hash on the drift entry
for remove files. And in persistChangeSet, I was not persisting the hash
correctly. I introduced a new property in MongoDBChangeSetEntry that has
since been removed. The hash is now persisted in the newFileHash
property as expected.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 2f4b967..fc1155e 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -171,6 +171,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
}
break;
default: // FILE_REMOVED
+ entry.setOldFileHash(fileEntry.getOldSHA());
if (fileDAO.findOne(fileEntry.getOldSHA()) == null) {
missingContent.add(newDriftFile(fileEntry.getOldSHA()));
}
@@ -349,7 +350,6 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
dto.setDirectory(entry.getDirectory());
dto.setCategory(entry.getCategory());
- // TODO Generate DriftFile DTOs for oldDriftFile and newDriftFile properties
switch (entry.getCategory()) {
case FILE_ADDED:
dto.setNewDriftFile(newDriftFile(entry.getNewFileHash()));
@@ -401,9 +401,9 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry();
entry.setPath(drift.getPath());
entry.setCategory(drift.getCategory());
- // we only need to initialize the newDriftFile property here since each drift
+ // we only need to initialize the newFileHash property here since each drift
// is going to be a FILE_ADDED entry.
- entry.setNewDriftFile(new MongoDBFile(drift.getNewDriftFile().getHashId()));
+ entry.setNewFileHash(drift.getNewDriftFile().getHashId());
newChangeSet.add(entry);
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
index f17794e..ff2a7bd 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
@@ -44,10 +44,6 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
@Transient
private MongoDBChangeSet changeSet;
- private MongoDBFile oldFile;
-
- private MongoDBFile newFile;
-
private String oldFileHash;
private String newFileHash;
@@ -187,21 +183,21 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
@Override
public MongoDBFile getOldDriftFile() {
- return oldFile;
+ return new MongoDBFile(oldFileHash);
}
@Override
public void setOldDriftFile(MongoDBFile oldDriftFile) {
- oldFile = oldDriftFile;
+ oldFileHash = oldDriftFile.getHashId();
}
@Override
public MongoDBFile getNewDriftFile() {
- return newFile;
+ return new MongoDBFile(newFileHash);
}
@Override
public void setNewDriftFile(MongoDBFile newDriftFile) {
- newFile = newDriftFile;
+ newFileHash = newDriftFile.getHashId();
}
}
commit 94d5ba17a34aa21914c9c8fb1a434f06d5f4c920
Author: John Sanda <jsanda(a)redhat.com>
Date: Thu Feb 16 11:17:57 2012 -0500
Adding initial impl for MongoDBDriftServer.persistChangeSet
persistChangeSet is invoked when pinning a snapshot to a definition or
to a template. There will be some additional changes to this method and
unit tests are needed as the logic is fairly involved.
Refactoring the logic for
MongoDBDriftServer.findDriftCompositesByCriteria to use ChangeSetDAO.
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
index a9d7f30..c2bd3ff 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/plugin/pc/drift/DriftServerPluginFacet.java
@@ -98,10 +98,20 @@ public interface DriftServerPluginFacet {
DriftChangeSetSummary saveChangeSet(Subject subject, int resourceId, File changeSetZip) throws Exception;
/**
+ * Persists a new initial change set for a pinned snapshot. This can happen when pinning
+ * a snapshot to a definition (resource level) or when pinning a snapshot to a template
+ * (resource type level). The RHQ server takes a snapshot, converts it into a change
+ * set, and then calls this method to persist the newly created change set. Note that
+ * when the RHQ server is pinning a snapshot to a definition, the change set will have
+ * a valid resource id associated with it, but when the snapshot is getting pinned to a
+ * template, the {@link DriftChangeSet#getResourceId() resourceId} property can be
+ * ignored.
*
- * @param subject
- * @param changeSet
- * @return The change set id
+ * @param subject The user submitting the request
+ * @param changeSet The change set to persist which may be a resource level change set meaning it belongs
+ * to a drift definition, or it may be a type level change set meaning it belongs to
+ * a {@link org.rhq.core.domain.drift.DriftDefinitionTemplate template}
+ * @return The id of the newly persisted change set
*/
String persistChangeSet(Subject subject, DriftChangeSet<?> changeSet);
@@ -123,7 +133,7 @@ public interface DriftServerPluginFacet {
* When a user wants to completely remove all data related to a drift definition,
* this method will be called to give the plugin a chance to clean up any data related
* to the drift definition that is going to be deleted.
- * @param Subject
+ * @param subject
* @param resourceId the resource whose drift definition is being purged
* @param driftDefName identifies the data that is to be purged
*/
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index c0db954..2f4b967 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -32,6 +32,7 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import com.google.code.morphia.Datastore;
+import com.google.code.morphia.Key;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
@@ -39,6 +40,7 @@ import com.mongodb.gridfs.GridFSDBFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.bson.types.ObjectId;
import org.rhq.common.drift.ChangeSetReader;
import org.rhq.common.drift.ChangeSetReaderImpl;
import org.rhq.common.drift.FileEntry;
@@ -53,6 +55,7 @@ import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftComposite;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+import org.rhq.core.domain.drift.DriftDefinition;
import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftFileStatus;
import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
@@ -64,6 +67,7 @@ import org.rhq.core.util.ZipUtil;
import org.rhq.core.util.file.FileUtil;
import org.rhq.core.util.stream.StreamUtil;
import org.rhq.enterprise.server.agentclient.AgentClient;
+import org.rhq.enterprise.server.drift.DriftManagerLocal;
import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent;
import org.rhq.enterprise.server.plugin.pc.ServerPluginContext;
import org.rhq.enterprise.server.plugin.pc.drift.DriftChangeSetSummary;
@@ -74,6 +78,7 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import org.rhq.enterprise.server.resource.ResourceManagerLocal;
+import org.rhq.enterprise.server.util.LookupUtil;
import static org.rhq.enterprise.server.util.LookupUtil.getAgentManager;
import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager;
@@ -123,11 +128,9 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
final DriftChangeSetSummary summary = new DriftChangeSetSummary();
- ZipUtil.walkZipFile(changeSetZip, new ZipUtil.ZipEntryVisitor()
- {
+ ZipUtil.walkZipFile(changeSetZip, new ZipUtil.ZipEntryVisitor() {
@Override
- public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception
- {
+ public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception {
ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new InputStreamReader(stream)));
Headers headers = reader.getHeaders();
@@ -146,35 +149,29 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
summary.setDriftDefinitionName(headers.getDriftDefinitionName());
summary.setCreatedTime(changeSet.getCtime());
- for (FileEntry fileEntry : reader)
- {
+ for (FileEntry fileEntry : reader) {
String path = FileUtil.useForwardSlash(fileEntry.getFile());
MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(path, fileEntry.getType());
- switch (fileEntry.getType())
- {
+ switch (fileEntry.getType()) {
case FILE_ADDED:
entry.setNewFileHash(fileEntry.getNewSHA());
- if (fileDAO.findOne(fileEntry.getNewSHA()) == null)
- {
+ if (fileDAO.findOne(fileEntry.getNewSHA()) == null) {
missingContent.add(newDriftFile(fileEntry.getNewSHA()));
}
break;
case FILE_CHANGED:
entry.setOldFileHash(fileEntry.getOldSHA());
entry.setNewFileHash(fileEntry.getNewSHA());
- if (fileDAO.findOne(fileEntry.getNewSHA()) == null)
- {
+ if (fileDAO.findOne(fileEntry.getNewSHA()) == null) {
missingContent.add(newDriftFile(fileEntry.getNewSHA()));
}
- if (fileDAO.findOne(fileEntry.getOldSHA()) == null)
- {
+ if (fileDAO.findOne(fileEntry.getOldSHA()) == null) {
missingContent.add(newDriftFile(fileEntry.getNewSHA()));
}
break;
default: // FILE_REMOVED
- if (fileDAO.findOne(fileEntry.getOldSHA()) == null)
- {
+ if (fileDAO.findOne(fileEntry.getOldSHA()) == null) {
missingContent.add(newDriftFile(fileEntry.getOldSHA()));
}
}
@@ -184,8 +181,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
// if the change set is a DRIFT report. If its a coverage report, it is not used (we do
// not alert on coverage reports) - so don't waste memory by collecting all the paths
// when we know they aren't going to be used anyway.
- if (headers.getType() == DriftChangeSetCategory.DRIFT)
- {
+ if (headers.getType() == DriftChangeSetCategory.DRIFT) {
summary.addDriftPathname(path);
}
}
@@ -203,8 +199,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
AgentClient agent = getAgentManager().getAgentClient(getSubjectManager().getOverlord(), resourceId);
DriftAgentService driftService = agent.getDriftAgentService();
driftService.ackChangeSet(headers.getResourceId(), headers.getDriftDefinitionName());
- if (!missingContent.isEmpty())
- {
+ if (!missingContent.isEmpty()) {
driftService.requestDriftFiles(resourceId, headers, missingContent);
}
@@ -274,18 +269,15 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public PageList<DriftComposite> findDriftCompositesByCriteria(Subject subject, DriftCriteria criteria) {
- Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class).filter("files.category in ",
- criteria.getFilterCategories()).filter("resourceId in", criteria.getFilterResourceIds());
-
- PageList<DriftComposite> results = new PageList<DriftComposite>();
+ List<MongoDBChangeSet> changeSets = changeSetDAO.findByDriftCriteria(criteria);
Map<Integer, Resource> resources = loadResourceMap(subject, criteria.getFilterResourceIds());
+ PageList<DriftComposite> results = new PageList<DriftComposite>();
- for (MongoDBChangeSet changeSet : query) {
+ for (MongoDBChangeSet changeSet : changeSets) {
DriftChangeSetDTO changeSetDTO = toDTO(changeSet);
for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) {
- // TODO: need to access config name
results.add(new DriftComposite(toDTO(entry, changeSetDTO), resources.get(changeSet.getResourceId()),
- "TODO"));
+ changeSet.getDriftDefinitionName()));
}
}
@@ -358,8 +350,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
dto.setCategory(entry.getCategory());
// TODO Generate DriftFile DTOs for oldDriftFile and newDriftFile properties
- switch (entry.getCategory())
- {
+ switch (entry.getCategory()) {
case FILE_ADDED:
dto.setNewDriftFile(newDriftFile(entry.getNewFileHash()));
break;
@@ -373,11 +364,56 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return dto;
}
-
+
@Override
public String persistChangeSet(Subject subject, DriftChangeSet<?> changeSet) {
- return null;
- // TODO Auto-generated method stub
+ // if this is a resource level change set we need to fetch the definition so that
+ // we can persist the definition name; otherwise, we will not be able to delete
+ // this and any other future change sets that belong to the definition.
+
+ // TODO Refactor caller logic of persistChangeSet to pass the definition name
+ // It might make sense to break persistChangeSet into two separate methods,
+ // something along the lines of persistTemplateChangeSet and
+ // persistDefinitionChangeSet where the definition is passed as an argument to
+ // the latter. As it stands right now, each plugin implementation will have
+ // duplicate logic for determining whether this is a template or definition change
+ // set. That logic could be pulled up into DriftManagerBean.
+
+ MongoDBChangeSet newChangeSet = new MongoDBChangeSet();
+ newChangeSet.setResourceId(changeSet.getResourceId());
+ newChangeSet.setDriftDefinitionId(changeSet.getDriftDefinitionId());
+ newChangeSet.setDriftHandlingMode(changeSet.getDriftHandlingMode());
+ newChangeSet.setCategory(changeSet.getCategory());
+ newChangeSet.setDriftDefinitionId(changeSet.getDriftDefinitionId());
+
+ if (!isTemplateChangeSet(changeSet)) {
+ DriftManagerLocal driftMgr = LookupUtil.getDriftManager();
+ DriftDefinition driftDef = driftMgr.getDriftDefinition(subject, changeSet.getDriftDefinitionId());
+ if (driftDef == null) {
+ throw new IllegalArgumentException("Cannot persist change set. " +
+ DriftDefinition.class.getSimpleName() + " with id " + changeSet.getDriftDefinitionId() +
+ " cannot be found.");
+ }
+ newChangeSet.setDriftDefinitionName(driftDef.getName());
+ }
+
+ for (Drift drift : changeSet.getDrifts()) {
+ MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry();
+ entry.setPath(drift.getPath());
+ entry.setCategory(drift.getCategory());
+ // we only need to initialize the newDriftFile property here since each drift
+ // is going to be a FILE_ADDED entry.
+ entry.setNewDriftFile(new MongoDBFile(drift.getNewDriftFile().getHashId()));
+ newChangeSet.add(entry);
+ }
+
+ Key key = changeSetDAO.save(newChangeSet);
+ ObjectId id = (ObjectId) key.getId();
+ return id.toString();
+ }
+
+ private boolean isTemplateChangeSet(DriftChangeSet<?> changeSet) {
+ return changeSet.getResourceId() == 0 && changeSet.getDriftDefinitionId() == 0;
}
@Override
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
index f12128d..f17794e 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
@@ -155,6 +155,8 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
@Override
public void setPath(String path) {
this.path = path;
+ int i = path.lastIndexOf("/");
+ directory = (i != -1) ? path.substring(0, i) : "./";
}
@Override
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java
index a3ecfbc..344614b 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBFile.java
@@ -30,6 +30,11 @@ public class MongoDBFile implements Serializable, DriftFile {
public MongoDBFile(String hash) {
this.hash = hash;
}
+
+ public MongoDBFile(DriftFile driftFile) {
+ hash = driftFile.getHashId();
+ size = driftFile.getDataSize();
+ }
@Override
public String getHashId() {
commit 2b444ccd185dfcbc485bba6ae1873b100ef67ef1
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Feb 15 21:51:38 2012 -0500
Adding support for deleting change sets
Change sets get deleted when a drift definition is deleted. Implemeneted
ChangeSetDAO.deleteChangeSets. Deletion is done by a combination of
resource id and drift definition name. We previously were not storing
the drift definition name. This commit also updates MongoDBChangeSet to
store the definition name in order to support deletes. Also implementing
MongoDBDriftServer.getDriftFileAsByteArray.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 88f15b0..c0db954 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -123,9 +123,11 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
final DriftChangeSetSummary summary = new DriftChangeSetSummary();
- ZipUtil.walkZipFile(changeSetZip, new ZipUtil.ZipEntryVisitor() {
+ ZipUtil.walkZipFile(changeSetZip, new ZipUtil.ZipEntryVisitor()
+ {
@Override
- public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception {
+ public boolean visit(ZipEntry zipEntry, ZipInputStream stream) throws Exception
+ {
ChangeSetReader reader = new ChangeSetReaderImpl(new BufferedReader(new InputStreamReader(stream)));
Headers headers = reader.getHeaders();
@@ -135,6 +137,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
changeSet.setCategory(headers.getType());
changeSet.setResourceId(resourceId);
changeSet.setDriftDefinitionId(headers.getDriftDefinitionId());
+ changeSet.setDriftDefinitionName(headers.getDriftDefinitionName());
changeSet.setDriftHandlingMode(DriftHandlingMode.normal);
changeSet.setVersion(headers.getVersion());
@@ -143,31 +146,37 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
summary.setDriftDefinitionName(headers.getDriftDefinitionName());
summary.setCreatedTime(changeSet.getCtime());
- for (FileEntry fileEntry : reader) {
+ for (FileEntry fileEntry : reader)
+ {
String path = FileUtil.useForwardSlash(fileEntry.getFile());
MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(path, fileEntry.getType());
- switch (fileEntry.getType()) {
- case FILE_ADDED:
- entry.setNewFileHash(fileEntry.getNewSHA());
- if (fileDAO.findOne(fileEntry.getNewSHA()) == null) {
- missingContent.add(newDriftFile(fileEntry.getNewSHA()));
- }
- break;
- case FILE_CHANGED:
- entry.setOldFileHash(fileEntry.getOldSHA());
- entry.setNewFileHash(fileEntry.getNewSHA());
- if (fileDAO.findOne(fileEntry.getNewSHA()) == null) {
- missingContent.add(newDriftFile(fileEntry.getNewSHA()));
- }
- if (fileDAO.findOne(fileEntry.getOldSHA()) == null) {
- missingContent.add(newDriftFile(fileEntry.getNewSHA()));
- }
- break;
- default: // FILE_REMOVED
- if (fileDAO.findOne(fileEntry.getOldSHA()) == null) {
- missingContent.add(newDriftFile(fileEntry.getOldSHA()));
- }
+ switch (fileEntry.getType())
+ {
+ case FILE_ADDED:
+ entry.setNewFileHash(fileEntry.getNewSHA());
+ if (fileDAO.findOne(fileEntry.getNewSHA()) == null)
+ {
+ missingContent.add(newDriftFile(fileEntry.getNewSHA()));
+ }
+ break;
+ case FILE_CHANGED:
+ entry.setOldFileHash(fileEntry.getOldSHA());
+ entry.setNewFileHash(fileEntry.getNewSHA());
+ if (fileDAO.findOne(fileEntry.getNewSHA()) == null)
+ {
+ missingContent.add(newDriftFile(fileEntry.getNewSHA()));
+ }
+ if (fileDAO.findOne(fileEntry.getOldSHA()) == null)
+ {
+ missingContent.add(newDriftFile(fileEntry.getNewSHA()));
+ }
+ break;
+ default: // FILE_REMOVED
+ if (fileDAO.findOne(fileEntry.getOldSHA()) == null)
+ {
+ missingContent.add(newDriftFile(fileEntry.getOldSHA()));
+ }
}
changeSet.add(entry);
@@ -175,7 +184,8 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
// if the change set is a DRIFT report. If its a coverage report, it is not used (we do
// not alert on coverage reports) - so don't waste memory by collecting all the paths
// when we know they aren't going to be used anyway.
- if (headers.getType() == DriftChangeSetCategory.DRIFT) {
+ if (headers.getType() == DriftChangeSetCategory.DRIFT)
+ {
summary.addDriftPathname(path);
}
}
@@ -193,7 +203,8 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
AgentClient agent = getAgentManager().getAgentClient(getSubjectManager().getOverlord(), resourceId);
DriftAgentService driftService = agent.getDriftAgentService();
driftService.ackChangeSet(headers.getResourceId(), headers.getDriftDefinitionName());
- if (!missingContent.isEmpty()) {
+ if (!missingContent.isEmpty())
+ {
driftService.requestDriftFiles(resourceId, headers, missingContent);
}
@@ -292,7 +303,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public void purgeByDriftDefinitionName(Subject subject, int resourceId, String driftDefName) throws Exception {
- // TODO implement me!
+ changeSetDAO.deleteChangeSets(resourceId, driftDefName);
}
@Override
@@ -377,7 +388,10 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public byte[] getDriftFileAsByteArray(Subject subject, String hash) {
- // TODO Auto-generated method stub
- return null;
+ GridFSDBFile file = fileDAO.findById(hash);
+ if (file == null) {
+ return null;
+ }
+ return StreamUtil.slurp(file.getInputStream());
}
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index f6abf5d..07792db 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -243,5 +243,11 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
}
return null;
}
+
+ public void deleteChangeSets(int resourceId, String driftDefName) {
+ deleteByQuery(createQuery()
+ .field("resourceId").equal(resourceId)
+ .field("driftDefName").equal(driftDefName));
+ }
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
index d9ea1db..6609538 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
@@ -69,6 +69,8 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
private DriftHandlingMode driftHandlingMode;
private int resourceId;
+
+ private String driftDefName;
@Embedded("files")
private List<MongoDBChangeSetEntry> entries = new ArrayList<MongoDBChangeSetEntry>();
@@ -133,6 +135,14 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
public void setDriftDefinitionId(int id) {
driftDefId = id;
}
+
+ public String getDriftDefinitionName() {
+ return driftDefName;
+ }
+
+ public void setDriftDefinitionName(String name) {
+ driftDefName = name;
+ }
@Override
public DriftHandlingMode getDriftHandlingMode() {
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index 02f0307..4e9c0e0 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -943,6 +943,29 @@ public class ChangeSetDAOTest {
actual);
}
+ @Test(enabled = ENABLED)
+ public void deleteChangeSets() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ c1.setDriftDefinitionName("delete-test");
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ c2.setDriftDefinitionName("delete-test");
+ dao.save(c2);
+
+ dao.deleteChangeSets(1, "delete-test");
+
+ assertTrue(dao.find().asList().isEmpty(), "Failed to delete one or more change sets");
+ }
+
private void assertChangeSetsMatch(String msg, List<MongoDBChangeSet> expected, List<MongoDBChangeSet> actual) {
assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
int i = 0;
commit bbd463cc90701e33704cbb643ab45ff5d10d8dce
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Feb 15 15:12:04 2012 -0500
The end version for DriftChangeSetCriteria should be inclusive.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index 5d812df..f6abf5d 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -74,7 +74,7 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
}
if (criteria.getFilterEndVersion() != null) {
- query.field("version").lessThan(Integer.parseInt(criteria.getFilterEndVersion()));
+ query.field("version").lessThanOrEq(Integer.parseInt(criteria.getFilterEndVersion()));
}
if (criteria.getFilterCreatedAfter() != null) {
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index d97be29..02f0307 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -286,13 +286,13 @@ public class ChangeSetDAOTest {
GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
criteria.addFilterDriftDefinitionId(1);
- criteria.addFilterEndVersion("3");
+ criteria.addFilterEndVersion("2");
List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
List<MongoDBChangeSet> expected = asList(c1, c2);
String ignore = "drifts";
- assertCollectionMatchesNoOrder("Failed to find change sets by drift change criteria with start version filter",
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change criteria with end version filter",
expected, actual, ignore);
}
commit 796de85c5039c5f57cb214a3cf09a34522058d41
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Feb 15 14:24:09 2012 -0500
Adding support for retrieving drift file content
This commit provides the initial impl for the methods getDriftFile and
getDriftFileBits in MongoDBDriftServer. The logic for creating a
DriftDTO has been updated as well to populate the newDriftFile and
oldDriftFile properties with DriftFileDTO objects.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index a6574a5..88f15b0 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -19,10 +19,6 @@
package org.rhq.enterprise.server.plugins.drift.mongodb;
-import static org.rhq.enterprise.server.util.LookupUtil.getAgentManager;
-import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager;
-import static org.rhq.enterprise.server.util.LookupUtil.getSubjectManager;
-
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
@@ -39,11 +35,10 @@ import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
+import com.mongodb.gridfs.GridFSDBFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.bson.types.ObjectId;
-
import org.rhq.common.drift.ChangeSetReader;
import org.rhq.common.drift.ChangeSetReaderImpl;
import org.rhq.common.drift.FileEntry;
@@ -57,8 +52,9 @@ import org.rhq.core.domain.drift.Drift;
import org.rhq.core.domain.drift.DriftChangeSet;
import org.rhq.core.domain.drift.DriftChangeSetCategory;
import org.rhq.core.domain.drift.DriftComposite;
-import org.rhq.core.domain.drift.DriftFile;
import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
+import org.rhq.core.domain.drift.DriftFile;
+import org.rhq.core.domain.drift.DriftFileStatus;
import org.rhq.core.domain.drift.dto.DriftChangeSetDTO;
import org.rhq.core.domain.drift.dto.DriftDTO;
import org.rhq.core.domain.drift.dto.DriftFileDTO;
@@ -66,6 +62,7 @@ import org.rhq.core.domain.resource.Resource;
import org.rhq.core.domain.util.PageList;
import org.rhq.core.util.ZipUtil;
import org.rhq.core.util.file.FileUtil;
+import org.rhq.core.util.stream.StreamUtil;
import org.rhq.enterprise.server.agentclient.AgentClient;
import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent;
import org.rhq.enterprise.server.plugin.pc.ServerPluginContext;
@@ -78,6 +75,10 @@ import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBFile;
import org.rhq.enterprise.server.resource.ResourceManagerLocal;
+import static org.rhq.enterprise.server.util.LookupUtil.getAgentManager;
+import static org.rhq.enterprise.server.util.LookupUtil.getResourceManager;
+import static org.rhq.enterprise.server.util.LookupUtil.getSubjectManager;
+
public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
private Log log = LogFactory.getLog(MongoDBDriftServer.class);
@@ -209,6 +210,13 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
return file;
}
+ private DriftFileDTO newDriftFile(String hash, DriftFileStatus status) {
+ DriftFileDTO file = new DriftFileDTO();
+ file.setHashId(hash);
+ file.setStatus(status);
+ return file;
+ }
+
@Override
public void saveChangeSetFiles(final Subject subject, final File changeSetFilesZip) throws Exception {
String zipFileName = changeSetFilesZip.getName();
@@ -275,8 +283,11 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public DriftFile getDriftFile(Subject subject, String hashId) throws Exception {
- // TODO
- return null;
+ GridFSDBFile gridFSDBFile = fileDAO.findById(hashId);
+ if (gridFSDBFile == null) {
+ return null;
+ }
+ return newDriftFile(hashId, DriftFileStatus.LOADED);
}
@Override
@@ -292,7 +303,11 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public String getDriftFileBits(Subject subject, String hash) {
- return null;
+ GridFSDBFile file = fileDAO.findById(hash);
+ if (file == null) {
+ return null;
+ }
+ return new String(StreamUtil.slurp(file.getInputStream()));
}
Map<Integer, Resource> loadResourceMap(Subject subject, Integer[] resourceIds) {
@@ -332,14 +347,22 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
dto.setCategory(entry.getCategory());
// TODO Generate DriftFile DTOs for oldDriftFile and newDriftFile properties
- DriftFileDTO fileDTO = new DriftFileDTO();
-
- dto.setOldDriftFile(fileDTO);
- dto.setNewDriftFile(fileDTO);
-
+ switch (entry.getCategory())
+ {
+ case FILE_ADDED:
+ dto.setNewDriftFile(newDriftFile(entry.getNewFileHash()));
+ break;
+ case FILE_CHANGED:
+ dto.setNewDriftFile(newDriftFile(entry.getNewFileHash()));
+ dto.setOldDriftFile(newDriftFile(entry.getOldFileHash()));
+ break;
+ default: // FILE_REMOVED
+ dto.setOldDriftFile(newDriftFile(entry.getOldFileHash()));
+ }
+
return dto;
}
-
+
@Override
public String persistChangeSet(Subject subject, DriftChangeSet<?> changeSet) {
return null;
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java
index 33fadf5..874fdf6 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/FileDAO.java
@@ -41,6 +41,10 @@ public class FileDAO {
this.db = db;
gridFS = new GridFS(this.db);
}
+
+ public GridFSDBFile findById(String hash) {
+ return gridFS.findOne(new BasicDBObject("_id", hash));
+ }
public InputStream findOne(String hash) {
GridFSDBFile dbFile = gridFS.findOne(new BasicDBObject("_id", hash));
commit 56044e2ccd64f0345bce8b0f02084fa31fbe1707
Author: John Sanda <jsanda(a)redhat.com>
Date: Mon Feb 13 09:52:12 2012 -0500
Refactoring findDriftsByCriteria to use ChangeSetDAO
ChangeSetDAO supports queries with DriftCriteria (though not completely
yet), and MongoDBDriftServer will use ChangeSetDAO as the data access
layer for for change sets and drift entries.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index be1bdde..a6574a5 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -244,29 +244,10 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public PageList<? extends Drift<?, ?>> findDriftsByCriteria(Subject subject, DriftCriteria criteria) {
- Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class);
- boolean changeSetIdFiltered = false;
-
- if (criteria.getFilterId() != null) {
- String[] idFields = criteria.getFilterId().split(":");
- ObjectId changeSetId = new ObjectId(idFields[0]);
- String path = idFields[1];
-
- query.filter("files.path = ", path);
- query.filter("id = ", changeSetId);
- }
-
- if (!changeSetIdFiltered && criteria.getFilterChangeSetId() != null) {
- query.filter("id = ", new ObjectId(criteria.getFilterChangeSetId()));
- }
-
+ List<MongoDBChangeSetEntry> entries = changeSetDAO.findEntries(criteria);
PageList<DriftDTO> results = new PageList<DriftDTO>();
-
- for (MongoDBChangeSet changeSet : query) {
- DriftChangeSetDTO changeSetDTO = toDTO(changeSet);
- for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) {
- results.add((toDTO(entry, changeSetDTO)));
- }
+ for (MongoDBChangeSetEntry entry : entries) {
+ results.add(toDTO(entry, toDTO(entry.getChangeSet())));
}
return results;
@@ -352,7 +333,6 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
// TODO Generate DriftFile DTOs for oldDriftFile and newDriftFile properties
DriftFileDTO fileDTO = new DriftFileDTO();
- fileDTO.setHashId("1a2b3c4e5f");
dto.setOldDriftFile(fileDTO);
dto.setNewDriftFile(fileDTO);
commit f620fa94a53d03332278826b93e6872f4e6dfbba
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Feb 12 21:57:40 2012 -0500
Rounding out support for DriftChangeSetCriteria queries
This commit adds support for including/excluding drift entries from the
results and for sorting by version. There is no support yet for the
methods defined in BaseCriteria. I'll probably defer that to a later
time after the plugin can be considered functionally complete. I do not
think supporting those methods is necessary to be complete.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 661b4a9..be1bdde 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -350,6 +350,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
dto.setDirectory(entry.getDirectory());
dto.setCategory(entry.getCategory());
+ // TODO Generate DriftFile DTOs for oldDriftFile and newDriftFile properties
DriftFileDTO fileDTO = new DriftFileDTO();
fileDTO.setHashId("1a2b3c4e5f");
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index eb2b11e..5d812df 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -34,6 +34,7 @@ import org.bson.types.ObjectId;
import org.rhq.core.domain.criteria.DriftChangeSetCriteria;
import org.rhq.core.domain.criteria.DriftCriteria;
+import org.rhq.core.domain.util.PageOrdering;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
@@ -100,6 +101,18 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
query.field("files.category").in(criteria.getFilterDriftCategories());
}
+ if (!criteria.isFetchDrifts()) {
+ query.retrievedFields(false, "files");
+ }
+
+ if (criteria.getSortVersion() != null) {
+ if (criteria.getSortVersion() == PageOrdering.ASC) {
+ query.order("version");
+ } else {
+ query.order("-version");
+ }
+ }
+
return query.asList();
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index 604412b..d97be29 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -27,6 +27,7 @@ import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
+import org.rhq.core.domain.util.PageOrdering;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -48,6 +49,7 @@ import static org.rhq.test.AssertUtils.assertCollectionMatchesNoOrder;
import static org.rhq.test.AssertUtils.assertPropertiesMatch;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
public class ChangeSetDAOTest {
@@ -530,6 +532,96 @@ public class ChangeSetDAOTest {
assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with drift categories filter",
expected, actual, ignore);
}
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaAndDoNotFetchDrifts() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(COVERAGE);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ c1.add(new MongoDBChangeSetEntry("foo.txt", FILE_ADDED));
+ c1.add(new MongoDBChangeSetEntry("bar.txt", FILE_ADDED));
+ dao.save(c1);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.fetchDrifts(false);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change set when not fetching drifts", expected, actual, ignore);
+ assertTrue(actual.get(0).getDrifts().isEmpty(),
+ "The drift entries should not have been fetched with the change set");
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaAndSortByVersionAscending() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(COVERAGE);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = new MongoDBChangeSet();
+ c3.setCategory(DRIFT);
+ c3.setVersion(3);
+ c3.setResourceId(1);
+ c3.setDriftDefinitionId(1);
+ dao.save(c3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addSortVersion(PageOrdering.ASC);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1, c2, c3);
+
+ assertChangeSetsMatch("Failed to sort change sets by version in ascending order", expected, actual);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaAndSortByVersionDescending() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(COVERAGE);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = new MongoDBChangeSet();
+ c3.setCategory(DRIFT);
+ c3.setVersion(3);
+ c3.setResourceId(1);
+ c3.setDriftDefinitionId(1);
+ dao.save(c3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addSortVersion(PageOrdering.DESC);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c3, c2, c1);
+
+ assertChangeSetsMatch("Failed to sort change sets by version in descending order", expected, actual);
+ }
@Test(enabled = ENABLED)
public void findByDriftCriteriaWithResourceIdFilter() throws Exception {
@@ -847,12 +939,21 @@ public class ChangeSetDAOTest {
List<MongoDBChangeSet> actual = dao.findByDriftCriteria(criteria);
- assertChangeSetsMatch("Failed to find change sets by drift criteria with change set id filter", asList(c2),
- actual);
+ assertChangeSetsMatchNoOrder("Failed to find change sets by drift criteria with change set id filter", asList(c2),
+ actual);
}
-
+
private void assertChangeSetsMatch(String msg, List<MongoDBChangeSet> expected, List<MongoDBChangeSet> actual) {
assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
+ int i = 0;
+ for (MongoDBChangeSet expectedChangeSet : expected) {
+ assertChangeSetMatches("Change sets do not match: " + msg, expectedChangeSet, actual.get(i++));
+ }
+ }
+
+ private void assertChangeSetsMatchNoOrder(String msg, List<MongoDBChangeSet> expected,
+ List<MongoDBChangeSet> actual) {
+ assertEquals(actual.size(), expected.size(), "The number of change sets differ: " + msg);
for (MongoDBChangeSet expectedChangeSet : expected) {
MongoDBChangeSet actualChangeSet = null;
for (MongoDBChangeSet changeSet : actual) {
commit fe059e740059481cfd604fea921360af04742111
Author: John Sanda <jsanda(a)redhat.com>
Date: Sun Feb 12 21:09:40 2012 -0500
Adding support for querying on the Drift.directory property
Prior to this commit, the directory was not get persisted as its own
field. Although it can be parsed out from the Drift.path property, the
directory is stored separately to allow for faster querying on the
snapshot view, where the querying is done by directory.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 5f57f96..661b4a9 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -144,9 +144,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
for (FileEntry fileEntry : reader) {
String path = FileUtil.useForwardSlash(fileEntry.getFile());
- MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry();
- entry.setCategory(fileEntry.getType());
- entry.setPath(path);
+ MongoDBChangeSetEntry entry = new MongoDBChangeSetEntry(path, fileEntry.getType());
switch (fileEntry.getType()) {
case FILE_ADDED:
@@ -242,7 +240,6 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
}
return results;
- //return new PageList<DriftChangeSet>();
}
@Override
@@ -350,6 +347,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
dto.setId(entry.getId());
dto.setCtime(entry.getCtime());
dto.setPath(entry.getPath());
+ dto.setDirectory(entry.getDirectory());
dto.setCategory(entry.getCategory());
DriftFileDTO fileDTO = new DriftFileDTO();
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index 7205c79..eb2b11e 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -87,6 +87,18 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
if (criteria.getFilterDriftPath() != null) {
query.field("files.path").equal(Pattern.compile(".*" + criteria.getFilterDriftPath() + ".*"));
}
+
+ if (criteria.getFilterDriftDirectory() != null) {
+ query.field("files.directory").equal(criteria.getFilterDriftDirectory());
+ }
+
+ if (criteria.getFilterCategory() != null) {
+ query.field("category").equal(criteria.getFilterCategory());
+ }
+
+ if (criteria.getFilterDriftCategories() != null) {
+ query.field("files.category").in(criteria.getFilterDriftCategories());
+ }
return query.asList();
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
index 9b1f09e..f12128d 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
@@ -57,6 +57,8 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
public MongoDBChangeSetEntry(String path, DriftCategory category) {
this.path = path;
+ int i = path.lastIndexOf("/");
+ directory = (i != -1) ? path.substring(0, i) : "./";
this.category = category;
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index bbcb815..604412b 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -424,6 +424,114 @@ public class ChangeSetDAOTest {
}
@Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithDirectoryFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+
+ MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("./foo/foo.txt", FILE_ADDED);
+ c1.add(e1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+
+ MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("./bar/bar.txt", FILE_ADDED);
+ c2.add(e2);
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterDriftDirectory("./bar");
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c2);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set critiera with drift directory filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithCategoryFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(COVERAGE);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = new MongoDBChangeSet();
+ c3.setCategory(DRIFT);
+ c3.setVersion(3);
+ c3.setResourceId(1);
+ c3.setDriftDefinitionId(1);
+ dao.save(c3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterCategory(DRIFT);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c2, c3);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with category filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithDriftCategoryFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(COVERAGE);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ c1.add(new MongoDBChangeSetEntry("foo.txt", FILE_ADDED));
+ c1.add(new MongoDBChangeSetEntry("bar.txt", FILE_ADDED));
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ c2.add(new MongoDBChangeSetEntry("foo.txt", FILE_CHANGED));
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = new MongoDBChangeSet();
+ c3.setCategory(DRIFT);
+ c3.setVersion(3);
+ c3.setResourceId(1);
+ c3.setDriftDefinitionId(1);
+ c3.add(new MongoDBChangeSetEntry("bar.txt", FILE_REMOVED));
+ dao.save(c3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterDriftCategories(FILE_CHANGED, FILE_REMOVED);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c2, c3);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with drift categories filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
public void findByDriftCriteriaWithResourceIdFilter() throws Exception {
MongoDBChangeSet c1 = new MongoDBChangeSet();
c1.setCategory(DRIFT);
commit 49e502c91490ea127b51a6b1c145e8bff749527a
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Feb 11 22:31:48 2012 -0500
Adding support for more DriftChangeSetCriteria filters
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index 8ba645c..7205c79 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -21,6 +21,7 @@ package org.rhq.enterprise.server.plugins.drift.mongodb.dao;
import java.util.ArrayList;
import java.util.List;
+import java.util.regex.Pattern;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
@@ -50,6 +51,11 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
public List<MongoDBChangeSet> findByChangeSetCritiera(DriftChangeSetCriteria criteria) {
Query<MongoDBChangeSet> query = createQuery();
+ if (criteria.getFilterId() != null) {
+ // There is no need to apply any additional filters if the id filter is specified
+ return query.field("id").equal(new ObjectId(criteria.getFilterId())).asList();
+ }
+
if (criteria.getFilterResourceId() != null) {
query.field("resourceId").equal(criteria.getFilterResourceId());
}
@@ -57,6 +63,30 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
if (criteria.getFilterDriftDefinitionId() != null) {
query.field("driftDefId").equal(criteria.getFilterDriftDefinitionId());
}
+
+ if (criteria.getFilterVersion() != null) {
+ query.field("version").equal(Integer.parseInt(criteria.getFilterVersion()));
+ }
+
+ if (criteria.getFilterStartVersion() != null) {
+ query.field("version").greaterThanOrEq(Integer.parseInt(criteria.getFilterStartVersion()));
+ }
+
+ if (criteria.getFilterEndVersion() != null) {
+ query.field("version").lessThan(Integer.parseInt(criteria.getFilterEndVersion()));
+ }
+
+ if (criteria.getFilterCreatedAfter() != null) {
+ query.field("ctime").greaterThanOrEq(criteria.getFilterCreatedAfter());
+ }
+
+ if (criteria.getFilterCreatedBefore() != null) {
+ query.field("ctime").lessThan(criteria.getFilterCreatedBefore());
+ }
+
+ if (criteria.getFilterDriftPath() != null) {
+ query.field("files.path").equal(Pattern.compile(".*" + criteria.getFilterDriftPath() + ".*"));
+ }
return query.asList();
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index e8e9696..bbcb815 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -143,7 +143,7 @@ public class ChangeSetDAOTest {
}
@Test(enabled = ENABLED)
- public void findByChangeSetCriteriaWithResourceIdFilter() throws Exception {
+ public void findByChangeSetCriteriaWithIdFilter() throws Exception {
MongoDBChangeSet c1 = new MongoDBChangeSet();
c1.setCategory(DRIFT);
c1.setVersion(1);
@@ -159,6 +159,33 @@ public class ChangeSetDAOTest {
dao.save(c2);
GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterId(c1.getId());
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with id filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithResourceIdFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(2);
+ c2.setDriftDefinitionId(2);
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
criteria.addFilterResourceId(1);
List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
@@ -170,6 +197,104 @@ public class ChangeSetDAOTest {
}
@Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithVersionFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterVersion("2");
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c2);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change criteria with version filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithStartVersionFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = new MongoDBChangeSet();
+ c3.setCategory(DRIFT);
+ c3.setVersion(3);
+ c3.setResourceId(1);
+ c3.setDriftDefinitionId(1);
+ dao.save(c3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterStartVersion("2");
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c2, c3);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change criteria with start version filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithEndVersionFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ dao.save(c2);
+
+ MongoDBChangeSet c3 = new MongoDBChangeSet();
+ c3.setCategory(DRIFT);
+ c3.setVersion(3);
+ c3.setResourceId(1);
+ c3.setDriftDefinitionId(1);
+ dao.save(c3);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterEndVersion("3");
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1, c2);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change criteria with start version filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
public void findByChangeSetCriteriaWithDriftDefIdFilter() throws Exception {
MongoDBChangeSet c1 = new MongoDBChangeSet();
c1.setCategory(DRIFT);
@@ -204,6 +329,101 @@ public class ChangeSetDAOTest {
}
@Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithCreatedAfterFilter() throws Exception {
+ long creationTime = System.currentTimeMillis() - (1000 * 60 * 10); // 10 minutes ago
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ c1.setCtime(creationTime);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ c2.setCtime(c1.getCtime() + (1000 * 60 * 5)); // 5 minutes ago
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterCreatedAfter(creationTime + 1000);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c2);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with created after " +
+ "filter", expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithCreatedBeforeFilter() throws Exception {
+ long creationTime = System.currentTimeMillis() - (1000 * 60 * 10); // 10 minutes ago
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ c1.setCtime(creationTime);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+ c2.setCtime(c1.getCtime() + (1000 * 60 * 5)); // 5 minutes ago
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+ criteria.addFilterCreatedBefore(c2.getCtime());
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with created after " +
+ "filter", expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithPathFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+
+ MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("/test/foo.txt", FILE_ADDED);
+ c1.add(e1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(2);
+ c2.setResourceId(1);
+ c2.setDriftDefinitionId(1);
+
+ MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("/test/bar.txt", FILE_ADDED);
+ c2.add(e2);
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftPath("foo");
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set critiera with drift path filter",
+ expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
public void findByDriftCriteriaWithResourceIdFilter() throws Exception {
MongoDBChangeSet c1 = new MongoDBChangeSet();
c1.setCategory(DRIFT);
commit 4a28bf8f52279a8678df74ade5b20497c58ec26e
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Feb 11 13:03:04 2012 -0500
Adding initial support for change set criteria queries.
This commit adds initial support for DriftChangeSetCriteria queries. It
not fully supported yet. A coupple field names have also been refactored
from configId to driftDefId to be more inline with terminology.
diff --git a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
index 28ed5ef..c6dacb3 100644
--- a/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
+++ b/modules/core/domain/src/main/java/org/rhq/core/domain/drift/dto/DriftChangeSetDTO.java
@@ -20,7 +20,7 @@ public class DriftChangeSetDTO implements DriftChangeSet<DriftDTO>, Serializable
private DriftChangeSetCategory category;
- private int configId;
+ private int driftDefId;
private DriftHandlingMode driftHandlingMode;
@@ -69,12 +69,12 @@ public class DriftChangeSetDTO implements DriftChangeSet<DriftDTO>, Serializable
@Override
public int getDriftDefinitionId() {
- return configId;
+ return driftDefId;
}
@Override
public void setDriftDefinitionId(int id) {
- configId = id;
+ driftDefId = id;
}
@Override
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
index 7f594de..e93d680 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
@@ -20,8 +20,8 @@
Tests are temporarily disabled until a MongoDB server is set up for use with
hudson builds. They can however be run locally provided you have MongoDB installed.
- jsanda
- -->
<skipTests>true</skipTests>
+ -->
</properties>
<dependencies>
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index 4eac1ec..5f57f96 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -71,6 +71,7 @@ import org.rhq.enterprise.server.plugin.pc.ServerPluginComponent;
import org.rhq.enterprise.server.plugin.pc.ServerPluginContext;
import org.rhq.enterprise.server.plugin.pc.drift.DriftChangeSetSummary;
import org.rhq.enterprise.server.plugin.pc.drift.DriftServerPluginFacet;
+import org.rhq.enterprise.server.plugins.drift.mongodb.dao.ChangeSetDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.dao.FileDAO;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
@@ -86,6 +87,8 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
private Morphia morphia;
private Datastore ds;
+
+ private ChangeSetDAO changeSetDAO;
private FileDAO fileDAO;
@@ -94,6 +97,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
connection = new Mongo("127.0.0.1");
morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class);
ds = morphia.createDatastore(connection, "rhq");
+ changeSetDAO = new ChangeSetDAO(morphia, connection, "rhq");
fileDAO = new FileDAO(ds.getDB());
}
@@ -225,11 +229,9 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public PageList<? extends DriftChangeSet<?>> findDriftChangeSetsByCriteria(Subject subject,
DriftChangeSetCriteria criteria) {
- Query<MongoDBChangeSet> query = ds.createQuery(MongoDBChangeSet.class).filter("resourceId =",
- criteria.getFilterResourceId());
-
+ List<MongoDBChangeSet> changeSets = changeSetDAO.findByChangeSetCritiera(criteria);
PageList<DriftChangeSetDTO> results = new PageList<DriftChangeSetDTO>();
- for (MongoDBChangeSet changeSet : query) {
+ for (MongoDBChangeSet changeSet : changeSets) {
DriftChangeSetDTO changeSetDTO = toDTO(changeSet);
Set<DriftDTO> entries = new HashSet<DriftDTO>();
for (MongoDBChangeSetEntry entry : changeSet.getDrifts()) {
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
index 85ab7cb..8ba645c 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAO.java
@@ -31,6 +31,7 @@ import com.mongodb.Mongo;
import org.bson.types.ObjectId;
+import org.rhq.core.domain.criteria.DriftChangeSetCriteria;
import org.rhq.core.domain.criteria.DriftCriteria;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSet;
import org.rhq.enterprise.server.plugins.drift.mongodb.entities.MongoDBChangeSetEntry;
@@ -45,6 +46,20 @@ public class ChangeSetDAO extends BasicDAO<MongoDBChangeSet, ObjectId> {
super(mongo, morphia, db);
this.morphia = morphia;
}
+
+ public List<MongoDBChangeSet> findByChangeSetCritiera(DriftChangeSetCriteria criteria) {
+ Query<MongoDBChangeSet> query = createQuery();
+
+ if (criteria.getFilterResourceId() != null) {
+ query.field("resourceId").equal(criteria.getFilterResourceId());
+ }
+
+ if (criteria.getFilterDriftDefinitionId() != null) {
+ query.field("driftDefId").equal(criteria.getFilterDriftDefinitionId());
+ }
+
+ return query.asList();
+ }
public List<MongoDBChangeSet> findByDriftCriteria(DriftCriteria criteria) {
Query<MongoDBChangeSet> query = createQuery();
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
index ed4d4e7..d9ea1db 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
@@ -64,7 +64,7 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
private DriftChangeSetCategory category;
- private int configId;
+ private int driftDefId;
private DriftHandlingMode driftHandlingMode;
@@ -96,6 +96,14 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
return ctime;
}
+ /**
+ * This is here only for testing.
+ * @param ctime The timestamp
+ */
+ public void setCtime(Long ctime) {
+ this.ctime = ctime;
+ }
+
@Override
public int getVersion() {
return version;
@@ -118,12 +126,12 @@ public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>,
@Override
public int getDriftDefinitionId() {
- return configId;
+ return driftDefId;
}
@Override
public void setDriftDefinitionId(int id) {
- configId = id;
+ driftDefId = id;
}
@Override
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
index f037090..9b1f09e 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSetEntry.java
@@ -117,6 +117,14 @@ public class MongoDBChangeSetEntry implements Drift<MongoDBChangeSet, MongoDBFil
return ctime;
}
+ /**
+ * This is here only for testing.
+ * @param ctime The timestamp
+ */
+ public void setCtime(Long ctime) {
+ this.ctime = ctime;
+ }
+
@Override
public MongoDBChangeSet getChangeSet() {
return changeSet;
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
index 4118e57..e8e9696 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/test/java/org/rhq/enterprise/server/plugins/drift/mongodb/dao/ChangeSetDAOTest.java
@@ -26,6 +26,7 @@ import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
+import org.rhq.core.domain.criteria.GenericDriftChangeSetCriteria;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
@@ -142,6 +143,67 @@ public class ChangeSetDAOTest {
}
@Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithResourceIdFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(1);
+ c2.setResourceId(2);
+ c2.setDriftDefinitionId(2);
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterResourceId(1);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with resource id " +
+ "filter", expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
+ public void findByChangeSetCriteriaWithDriftDefIdFilter() throws Exception {
+ MongoDBChangeSet c1 = new MongoDBChangeSet();
+ c1.setCategory(DRIFT);
+ c1.setVersion(1);
+ c1.setResourceId(1);
+ c1.setDriftDefinitionId(1);
+ dao.save(c1);
+
+ MongoDBChangeSet c11 = new MongoDBChangeSet();
+ c11.setCategory(DRIFT);
+ c11.setVersion(2);
+ c11.setResourceId(1);
+ c11.setDriftDefinitionId(1);
+ dao.save(c11);
+
+ MongoDBChangeSet c2 = new MongoDBChangeSet();
+ c2.setCategory(DRIFT);
+ c2.setVersion(1);
+ c2.setResourceId(2);
+ c2.setDriftDefinitionId(2);
+ dao.save(c2);
+
+ GenericDriftChangeSetCriteria criteria = new GenericDriftChangeSetCriteria();
+ criteria.addFilterDriftDefinitionId(1);
+
+ List<MongoDBChangeSet> actual = dao.findByChangeSetCritiera(criteria);
+ List<MongoDBChangeSet> expected = asList(c1, c11);
+
+ String ignore = "drifts";
+ assertCollectionMatchesNoOrder("Failed to find change sets by drift change set criteria with drift " +
+ "definition id filter", expected, actual, ignore);
+ }
+
+ @Test(enabled = ENABLED)
public void findByDriftCriteriaWithResourceIdFilter() throws Exception {
MongoDBChangeSet c1 = new MongoDBChangeSet();
c1.setCategory(DRIFT);
@@ -155,6 +217,7 @@ public class ChangeSetDAOTest {
c2.setVersion(1);
c2.setResourceId(2);
c2.setDriftDefinitionId(2);
+ dao.save(c2);
GenericDriftCriteria criteria = new GenericDriftCriteria();
criteria.addFilterResourceIds(1);
@@ -275,17 +338,18 @@ public class ChangeSetDAOTest {
@Test(enabled = ENABLED)
public void findByDriftCriteriaWithStartTimeFilter() throws Exception {
+ long startTime = System.currentTimeMillis() - (1000 * 60 * 60); // one hour ago
+
int resourceId = 1;
MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, resourceId, 1);
+ c1.setCtime(startTime - (1000 * 5)); // c1 is created 5 seconds before startTime
MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
+ e1.setCtime(startTime - (1000 * 5)); // e1 is created 5 seconds before startTime
c1.add(e1);
dao.save(c1);
- long startTime = System.currentTimeMillis();
- Thread.sleep(10);
-
MongoDBChangeSet c2 = createChangeSet(DRIFT, 2, resourceId, 1);
MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("c1-1.txt", FILE_CHANGED);
c2.add(e2);
@@ -354,15 +418,19 @@ public class ChangeSetDAOTest {
@Test(enabled = ENABLED)
public void findEntriesWithResourceIdAndStartTimeFilter() throws Exception {
+ long startTime = System.currentTimeMillis() - (1000 * 60 * 60); // one hour ago
+
MongoDBChangeSet c1 = createChangeSet(COVERAGE, 1, 1, 1);
+ c1.setCtime(startTime - (1000 * 5)); // c1 is created 5 seconds before startTime
MongoDBChangeSetEntry e1 = new MongoDBChangeSetEntry("c1-1.txt", FILE_ADDED);
c1.add(e1);
+ e1.setCtime(startTime - (1000 * 5)); // e1 is created 5 seconds before startTime
dao.save(c1);
- long startTime = System.currentTimeMillis();
- Thread.sleep(10);
-
MongoDBChangeSet c2 = createChangeSet(COVERAGE, 1, 2, 1);
+ c2.setCtime(startTime - (1000 * 5)); // c2 is created 5 seconds before startTime
+ MongoDBChangeSetEntry e2 = new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED);
+ e2.setCtime(startTime - (1000 * 5)); // e2 is created 5 seconds before startTime
c2.add(new MongoDBChangeSetEntry("c2-1.txt", FILE_ADDED));
dao.save(c2);
commit 827ecf4181ad09e9fe7cd31bfc8200a333f7cc84
Author: John Sanda <jsanda(a)redhat.com>
Date: Sat Feb 11 11:28:36 2012 -0500
Send agent change set ack
Updating MongoDBDriftServer.saveChangeSet to send the agent the change
set acknowledgement. Also reverting the version of morphia to 0.99 for
now. The 1.00 snapshot version now requires a newer version of the
MongoDB driver, and I am not ready just yet to upgrade. I need to do
some more testing to see what does and does not currently work.
diff --git a/modules/enterprise/server/plugins/drift-mongodb/pom.xml b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
index 4026ee5..7f594de 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/pom.xml
+++ b/modules/enterprise/server/plugins/drift-mongodb/pom.xml
@@ -54,7 +54,7 @@
<dependency>
<groupId>com.google.code.morphia</groupId>
<artifactId>morphia</artifactId>
- <version>1.00-SNAPSHOT</version>
+ <version>0.99</version>
</dependency>
<dependency>
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
index a98ff59..4eac1ec 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/MongoDBDriftServer.java
@@ -40,6 +40,8 @@ import com.google.code.morphia.Morphia;
import com.google.code.morphia.query.Query;
import com.mongodb.Mongo;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.bson.types.ObjectId;
import org.rhq.common.drift.ChangeSetReader;
@@ -77,7 +79,7 @@ import org.rhq.enterprise.server.resource.ResourceManagerLocal;
public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginComponent {
- //private final Log log = LogFactory.getLog(MongoDBDriftServer.class);
+ private Log log = LogFactory.getLog(MongoDBDriftServer.class);
private Mongo connection;
@@ -89,7 +91,7 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
@Override
public void initialize(ServerPluginContext context) throws Exception {
- connection = new Mongo("localhost");
+ connection = new Mongo("127.0.0.1");
morphia = new Morphia().map(MongoDBChangeSet.class).map(MongoDBChangeSetEntry.class).map(MongoDBFile.class);
ds = morphia.createDatastore(connection, "rhq");
fileDAO = new FileDAO(ds.getDB());
@@ -177,9 +179,18 @@ public class MongoDBDriftServer implements DriftServerPluginFacet, ServerPluginC
ds.save(changeSet);
+ // The following section of code really should not be part of the plugin
+ // implementation, but it is currently required due to a flaw in the design
+ // of the drift plugin framework. Two things are done here. First, if we
+ // successfully persist the change set, then we need to send an
+ // acknowledgement to the agent. This is critical because the agent will
+ // in effect suspend drift detection (for the particular definition) until
+ // it receives the ACK. Secondly, we need to tell the agent to send the
+ // actual file bits for any change set content we do not have.
+ AgentClient agent = getAgentManager().getAgentClient(getSubjectManager().getOverlord(), resourceId);
+ DriftAgentService driftService = agent.getDriftAgentService();
+ driftService.ackChangeSet(headers.getResourceId(), headers.getDriftDefinitionName());
if (!missingContent.isEmpty()) {
- AgentClient agent = getAgentManager().getAgentClient(getSubjectManager().getOverlord(), resourceId);
- DriftAgentService driftService = agent.getDriftAgentService();
driftService.requestDriftFiles(resourceId, headers, missingContent);
}
diff --git a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
index f52391f..ed4d4e7 100644
--- a/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
+++ b/modules/enterprise/server/plugins/drift-mongodb/src/main/java/org/rhq/enterprise/server/plugins/drift/mongodb/entities/MongoDBChangeSet.java
@@ -37,7 +37,8 @@ import org.rhq.core.domain.drift.DriftConfigurationDefinition.DriftHandlingMode;
/**
* A change set that is stored in a MongoDB database. The change set along with its entries
- * are stored as a single document.
+ * are stored as a single document. A change set consists of one or more
+ * {@link MongoDBChangeSetEntry entries}.
*/
@Entity("changesets")
public class MongoDBChangeSet implements DriftChangeSet<MongoDBChangeSetEntry>, Serializable {
12 years, 1 month
[rhq] Branch 'feature/export-reports' - modules/enterprise
by John Sanda
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java | 33 ++++++++--
1 file changed, 27 insertions(+), 6 deletions(-)
New commits:
commit 86673a04746967a21499d6360f63a5fe74c9e2d8
Author: John Sanda <jsanda(a)redhat.com>
Date: Wed Mar 28 21:25:14 2012 -0400
Fixing missing title bars
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java
index 0747c28..8c1f72b 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/InventoryView.java
@@ -37,6 +37,7 @@ import org.rhq.enterprise.gui.coregui.client.PermissionsLoadedListener;
import org.rhq.enterprise.gui.coregui.client.PermissionsLoader;
import org.rhq.enterprise.gui.coregui.client.components.TitleBar;
import org.rhq.enterprise.gui.coregui.client.components.view.AbstractSectionedLeftNavigationView;
+import org.rhq.enterprise.gui.coregui.client.components.view.HasViewName;
import org.rhq.enterprise.gui.coregui.client.components.view.NavigationItem;
import org.rhq.enterprise.gui.coregui.client.components.view.NavigationSection;
import org.rhq.enterprise.gui.coregui.client.components.view.ViewFactory;
@@ -133,8 +134,7 @@ public class InventoryView extends AbstractSectionedLeftNavigationView {
}
private ResourceSearchView createResourceSearchView(ViewName viewName, Criteria initialCriteria) {
- return new ResourceSearchView(extendLocatorId(viewName.getName()), initialCriteria, viewName.getTitle(),
- viewName.getIcon().getIcon24x24Path());
+ return new ResourceSearchViewWrapper(viewName, initialCriteria, viewName.getIcon().getIcon24x24Path());
}
private NavigationSection buildResourcesSection() {
@@ -149,10 +149,10 @@ public class InventoryView extends AbstractSectionedLeftNavigationView {
NavigationItem allResourcesItem = new NavigationItem(PAGE_ALL_RESOURCES, new ViewFactory() {
public Canvas createView() {
- return new ResourceSearchView(extendLocatorId(PAGE_ALL_RESOURCES.getName()), null, PAGE_ALL_RESOURCES
- .getTitle(), ImageManager.getResourceLargeIcon(ResourceCategory.PLATFORM), ImageManager
- .getResourceLargeIcon(ResourceCategory.SERVER), ImageManager
- .getResourceLargeIcon(ResourceCategory.SERVICE));
+ return new ResourceSearchViewWrapper(PAGE_ALL_RESOURCES, null,
+ ImageManager.getResourceLargeIcon(ResourceCategory.PLATFORM),
+ ImageManager.getResourceLargeIcon(ResourceCategory.SERVER),
+ ImageManager.getResourceLargeIcon(ResourceCategory.SERVICE));
}
});
@@ -238,4 +238,25 @@ public class InventoryView extends AbstractSectionedLeftNavigationView {
return new NavigationSection(GROUPS_SECTION_VIEW_ID, allGroupsItem, dynagroupDefinitionsItem,
compatibleGroupsItem, mixedGroupsItem, problemGroupsItem);
}
+
+ private class ResourceSearchViewWrapper extends ResourceSearchView implements HasViewName {
+
+ private ViewName viewName;
+
+ public ResourceSearchViewWrapper(ViewName viewName, Criteria criteria, String... headerIcons) {
+ super(viewName.getName(), criteria, viewName.getTitle(), headerIcons);
+ this.viewName = viewName;
+ }
+
+ public ResourceSearchViewWrapper(ViewName viewName, Criteria criteria) {
+ super(viewName.getName(), criteria);
+ this.viewName = viewName;
+ }
+
+ @Override
+ public ViewName getViewName() {
+ return viewName;
+ }
+ }
+
}
12 years, 1 month
[rhq] 2 commits - modules/core modules/plugins
by ips
modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java | 18 +++------
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java | 19 ++++++++--
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java | 2 -
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java | 6 +--
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java | 15 ++++---
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java | 2 -
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java | 2 -
7 files changed, 36 insertions(+), 28 deletions(-)
New commits:
commit 35aadf4db3bd68be52fffed4006e10a0fae09cfd
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 21:44:24 2012 -0400
fix a couple compile errors and a regression in the code that determines the management bind address from the command line
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
index e0cf57e..4ca0a84 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AS7CommandLineOption.java
@@ -7,10 +7,14 @@ package org.rhq.modules.plugins.jbossas7;
*/
public class AS7CommandLineOption {
- private Character shortName;
+ private String shortName;
private String longName;
- public AS7CommandLineOption(Character shortName, String longName) {
+ public AS7CommandLineOption(char shortName, String longName) {
+ this(new String(new char[] {shortName}), longName);
+ }
+
+ public AS7CommandLineOption(String shortName, String longName) {
if ((shortName == null) && (longName == null)) {
throw new IllegalArgumentException("ShortName and longName cannot both be null.");
}
@@ -19,7 +23,8 @@ public class AS7CommandLineOption {
this.longName = longName;
}
- public Character getShortName() {
+
+ public String getShortName() {
return shortName;
}
@@ -27,4 +32,12 @@ public class AS7CommandLineOption {
return longName;
}
+ @Override
+ public String toString() {
+ return "AS7CommandLineOption{" +
+ "shortName='" + shortName + '\'' +
+ ", longName='" + longName + '\'' +
+ '}';
+ }
+
}
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
index 8641df1..c3214ed 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/AbstractBaseDiscovery.java
@@ -48,7 +48,7 @@ public class AbstractBaseDiscovery {
private static final String HOME_DIR_SYSPROP = "jboss.home.dir";
private static final String BIND_ADDRESS_MANAGEMENT_SYSPROP = "jboss.bind.address.management";
- private AS7CommandLineOption BIND_ADDRESS_MANAGEMENT_OPTION = new AS7CommandLineOption(null, "bmanagement");
+ private AS7CommandLineOption BIND_ADDRESS_MANAGEMENT_OPTION = new AS7CommandLineOption("bmanagement", null);
static final int DEFAULT_MGMT_PORT = 9990;
private static final String JBOSS_AS_PREFIX = "jboss-as-";
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
index f6dc975..67f70cd 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java
@@ -117,7 +117,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
pluginConfig.put(new PropertySimple("configDir", configDir));
pluginConfig.put(new PropertySimple("startScript", getMode().getStartScript()));
pluginConfig.put(new PropertySimple("domainHost", findHost(getHostXmlFile(process, configDir))));
- fillUserPassFromFile(pluginConfig, getMode(), homeDir.getPath());
+ fillUserPassFromFile(pluginConfig, getMode(), homeDir);
File logFile = getLogFile(getLogDir(process, baseDir));
initLogEventSourcesConfigProp(logFile.getPath(), pluginConfig);
HostPort managementHostPort = getManagementPortFromHostXml(commandLine);
@@ -316,8 +316,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
return (String) res.getResult();
}
- private void fillUserPassFromFile(Configuration config, AS7Mode mode, String baseDir) {
-
+ private void fillUserPassFromFile(Configuration config, AS7Mode mode, File baseDir) {
// String configDir = baseDir + File.separator + mode + File.separator + "configuration";
String realm = getManagementSecurityRealmFromHostXml();
String fileName = getSecurityPropertyFileFromHostXml(baseDir, mode, realm);
@@ -329,6 +328,7 @@ public abstract class BaseProcessDiscovery extends AbstractBaseDiscovery
+ "] or file is not readable");
return;
}
+ // TODO (ips): Can't we use Properties.load() to read the file?
BufferedReader br = null;
try {
FileReader fileReader = new FileReader(file);
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
index 68e407c..bdf8a66 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseServerComponent.java
@@ -55,7 +55,8 @@ import org.rhq.modules.plugins.jbossas7.json.ReadResource;
import org.rhq.modules.plugins.jbossas7.json.Result;
/**
- * Base component for functionality that is common to Standalone AS and HostControllers
+ * Base component for functionality that is common to Standalone Servers and Host Controllers.
+ *
* @author Heiko W. Rupp
*/
public class BaseServerComponent extends BaseComponent implements MeasurementFacet {
@@ -273,11 +274,12 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
return result;
}
- String homeDir = pluginConfig.getSimpleValue("homeDir", "");
- if (homeDir.isEmpty()) {
- result.setErrorMessage("No homeDir found, can not continue");
+ String homeDirString = pluginConfig.getSimpleValue("homeDir", "");
+ if (homeDirString.isEmpty()) {
+ result.setErrorMessage("No homeDir found - cannot continue.");
return result;
}
+ File homeDir = new File(homeDirString);
String configFile;
BaseProcessDiscovery processDiscovery;
@@ -318,8 +320,8 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
log.error(nsae.getMessage());
result.setErrorMessage(nsae.getMessage());
}
- result.setSimpleResult("User/Password set or updated");
- log.info("Installed management user [" + user + "].");
+ result.setSimpleResult("Management user [" + user + "] added or updated.");
+ log.info("Added or updated management user [" + user + "].");
context.getAvailabilityContext().requestAvailabilityCheck();
@@ -362,7 +364,6 @@ public class BaseServerComponent extends BaseComponent implements MeasurementFac
else if (!requestName.startsWith("_skm:")) { // handled below
leftovers.add(request);
}
-
}
// Now handle the skm
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
index a4a46df..225468f 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java
@@ -95,7 +95,7 @@ public class HostControllerDiscovery extends BaseProcessDiscovery {
@Override
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
- ProcessScanResult psr) {
+ ProcessScanResult psr) throws Exception {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
ProcessInfo process = psr.getProcessInfo();
Configuration pluginConfig = details.getPluginConfiguration();
diff --git a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
index 9102b21..4a80c60 100644
--- a/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
+++ b/modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java
@@ -107,7 +107,7 @@ public class StandaloneASDiscovery extends BaseProcessDiscovery {
@Override
protected DiscoveredResourceDetails buildResourceDetails(ResourceDiscoveryContext discoveryContext,
- ProcessScanResult psr) {
+ ProcessScanResult psr) throws Exception {
DiscoveredResourceDetails details = super.buildResourceDetails(discoveryContext, psr);
ProcessInfo process = psr.getProcessInfo();
Configuration pluginConfig = details.getPluginConfiguration();
commit e73c75134200da25d45abb25401bda5148a0c558
Author: Ian Springer <ian.springer(a)redhat.com>
Date: Wed Mar 28 21:29:26 2012 -0400
tone down some INFO logging to DEBUG; remove some dead code
diff --git a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java
index ce3eab7..67094b5 100644
--- a/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java
+++ b/modules/core/plugin-container/src/main/java/org/rhq/core/pc/inventory/AutoDiscoveryExecutor.java
@@ -60,7 +60,7 @@ import org.rhq.core.util.exception.ExceptionPackage;
import org.rhq.core.util.exception.Severity;
/**
- * Standard platform/server inventory detection execution. This is typically called in a non-blocking fashion and the
+ * Standard platform/server inventory detection execution. This is typically called in a non-blocking fashion, and the
* report is returned asynchronously to the server. It is available for direct execution via a Future when running in an
* embedded mode.
*
@@ -84,11 +84,6 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
this.configuration = configuration;
}
- public AutoDiscoveryExecutor() {
- autoDiscoveryRequest = new AutoDiscoveryRequest();
- autoDiscoveryRequest.getScanTypes().add(AutoDiscoveryScanType.Plugin);
- }
-
public void run() {
call();
}
@@ -167,7 +162,6 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
Set<ResourceType> serverTypes = pluginManager.getMetadataManager().getTypesForCategory(ResourceCategory.SERVER);
ResourceContainer platformContainer = inventoryManager.getResourceContainer(inventoryManager.getPlatform());
- ResourceComponent platformComponent = platformContainer.getResourceComponent();
Resource platformResource = platformContainer.getResource();
for (ResourceType serverType : serverTypes) {
@@ -195,7 +189,6 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
component, platformContainer, scanResults);
for (Resource discoveredServer : discoveredServers) {
- log.debug("Detected server " + discoveredServer);
Resource inventoriedResource = this.inventoryManager.mergeResourceFromDiscovery(discoveredServer,
platformResource);
@@ -237,8 +230,10 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
if ((queryResults != null) && (queryResults.size() > 0)) {
for (ProcessInfo autoDiscoveredProcess : queryResults) {
scanResults.add(new ProcessScanResult(processScan, autoDiscoveredProcess));
- log.info("Process scan auto-detected new server resource: scan=[" + processScan
- + "], discovered-process=[" + autoDiscoveredProcess + "]");
+ if (log.isDebugEnabled()) {
+ log.debug("Process scan auto-detected potential new server Resource: scan=[" + processScan
+ + "], discovered-process=[" + autoDiscoveredProcess + "]");
+ }
}
}
}
@@ -248,8 +243,7 @@ public class AutoDiscoveryExecutor implements Runnable, Callable<InventoryReport
private boolean verifyComponentCompatibility(ResourceDiscoveryComponent component,
ResourceComponent parentResourceComponent) throws PluginContainerException {
- Method discoveryCall = null;
-
+ Method discoveryCall;
try {
discoveryCall = component.getClass().getMethod("discoverResources", ResourceCategory.class);
} catch (NoSuchMethodException e) {
12 years, 1 month