[rhq] Branch 'feature/export-reports' - modules/enterprise
by John Sanda
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java | 382 +++++++++-
1 file changed, 365 insertions(+), 17 deletions(-)
New commits:
commit e6822818de09b43341a079a52151accf0dd643ce
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Mar 27 16:32:16 2012 -0400
[BZ 802544] First cut at implementing the alert condition text field
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 7904c01..3e851f0 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,30 +1,29 @@
package org.rhq.enterprise.server.rest.reporting;
-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.AlertPriority;
-import org.rhq.core.domain.criteria.AlertCriteria;
-import org.rhq.core.domain.util.PageList;
-import org.rhq.enterprise.server.alert.AlertManagerLocal;
-import org.rhq.enterprise.server.auth.SubjectManagerLocal;
-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 javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Request;
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 org.rhq.core.domain.alert.Alert;
+import org.rhq.core.domain.criteria.AlertCriteria;
+import org.rhq.core.domain.util.PageList;
+import org.rhq.enterprise.server.alert.AlertManagerLocal;
+import org.rhq.enterprise.server.auth.SubjectManagerLocal;
+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 static org.rhq.enterprise.server.rest.reporting.ReportHelper.cleanForCSV;
import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
@@ -81,7 +80,7 @@ public class RecentAlertHandler extends AbstractRestBean implements RecentAlertL
private String toCSV(Alert alert) {
return formatDateTime(alert.getCtime()) + "," +
cleanForCSV(alert.getAlertDefinition().getName()) + "," +
- "Condition Text" + "," +
+ getConditionText(alert) + ", " +
alert.getAlertDefinition().getPriority() + "," +
"Status"+ "," +
cleanForCSV(alert.getAlertDefinition().getResource().getName())+","+
@@ -92,6 +91,355 @@ public class RecentAlertHandler extends AbstractRestBean implements RecentAlertL
return "Creation Time,Name,Condition Text,Priority,Status,Resource,Ancestry";
}
+ private String getConditionText(Alert alert) {
+ Set<AlertConditionLog> conditionLogs = alert.getConditionLogs();
+ String conditionText = null;
+ String conditionValue;
+
+ if (conditionLogs.size() > 1) {
+
+ } else if (conditionLogs.size() == 1) {
+ AlertConditionLog conditionLog = conditionLogs.iterator().next();
+ AlertCondition condition = conditionLog.getCondition();
+ conditionText = formatCondition(condition);
+ conditionValue = conditionLog.getValue();
+ if (condition.getMeasurementDefinition() != null) {
+ try {
+// conditionValue = MeasurementConverterClient.format(Double.valueOf(conditionLog.getValue()),
+// condition.getMeasurementDefinition().getUnits(), true);
+ conditionValue = format(conditionLog.getValue(),
+ condition.getMeasurementDefinition().getUnits());
+ } catch (Exception e) {
+ // the condition log value was probably not a number (most likely a trait). Ignore this exception.
+ // even if any other errors occur trying to format the value, ignore this and just use the raw value string
+ }
+ }
+ } else {
+ conditionText = "No Conditions";
+ conditionValue = "--";
+ }
+
+ return conditionText;
+ }
+
+ private String formatCondition(AlertCondition condition) {
+ StringBuilder builder = new StringBuilder();
+ AlertConditionCategory category = condition.getCategory();
+ AlertConditionOperator operator;
+ double threshold;
+
+ switch (category) {
+ case AVAILABILITY:
+ builder.append("Availability [");
+ operator = AlertConditionOperator.valueOf(condition.getName().toUpperCase());
+ switch (operator) {
+ case AVAIL_GOES_DISABLED:
+ builder.append("Goes disabled");
+ break;
+ case AVAIL_GOES_DOWN:
+ builder.append("Goes down");
+ break;
+ case AVAIL_GOES_UNKNOWN:
+ builder.append("Goes unknown");
+ break;
+ case AVAIL_GOES_UP:
+ builder.append("Goes up");
+ break;
+ case AVAIL_GOES_NOT_UP:
+ builder.append("Goes not up");
+ break;
+ default:
+ builder.append("*ERROR*");
+ }
+ builder.append("]");
+ break;
+ case AVAIL_DURATION:
+ builder.append("Availability Duration [");
+ operator = AlertConditionOperator.valueOf(condition.getName().toUpperCase());
+ switch (operator) {
+ case AVAIL_DURATION_DOWN:
+ builder.append("Stays Down");
+ break;
+ case AVAIL_DURATION_NOT_UP:
+ builder.append("Stays Not Up");
+ break;
+ default:
+ builder.append("*ERROR*");
+ }
+ builder.append(" For ");
+
+ String value = String.valueOf(Integer.valueOf(condition.getOption()) / 60);
+ String formatted = format(value, MeasurementUnits.MINUTES);
+
+ builder.append(formatted).append("]");
+ break;
+ case THRESHOLD:
+ threshold = condition.getThreshold();
+ MeasurementUnits units = condition.getMeasurementDefinition().getUnits();
+ //String formatted = format(threshold, units, true);
+
+ if (condition.getOption() == null) {
+ builder.append("Metric Value Threshold [")
+ .append(condition.getName())
+ .append(" ")
+ .append(condition.getComparator())
+ .append(" ")
+ .append(threshold)
+ .append("]");
+ } else {
+ // this is a calltime threshold condition
+ builder.append("Call Time Value Threshold [");
+ if (condition.getMeasurementDefinition() != null) {
+ builder.append(condition.getMeasurementDefinition().getDisplayName()).append(" ");
+ }
+ builder.append(condition.getOption()) // MIN, MAX, AVG (never null)
+ .append(" ")
+ .append(condition.getComparator()) // <, >, =
+ .append(" ")
+ .append(threshold)
+ .append("]");
+ if (condition.getName() != null && condition.getName().length() > 0) {
+ builder.append(" with call destination matching '")
+ .append(condition.getName())
+ .append("'");
+ }
+ }
+ break;
+ case BASELINE:
+ threshold = condition.getThreshold();
+ builder.append("Metric Value Baseline [")
+ .append(condition.getName())
+ .append(" ")
+ .append(condition.getComparator())
+ .append(" ")
+ .append(threshold)
+ .append(" of ")
+ .append(condition.getOption())
+ .append("]");
+ break;
+ case CHANGE:
+ if (condition.getOption() == null) {
+ builder.append("Metric Value Change [")
+ .append(condition.getName())
+ .append(" ")
+ .append("]");
+ } else {
+ // this is a calltime change condition
+ threshold = condition.getThreshold();
+ builder.append("Call Time Value Changes [");
+ if (condition.getMeasurementDefinition() != null) {
+ builder.append(condition.getMeasurementDefinition().getDisplayName()).append(" ");
+ }
+ builder.append(condition.getOption()) // MIN, MAX, AVG (never null)
+ .append(" ")
+ .append(getCalltimeChangeComparator(condition.getComparator()))
+ .append(" by at least ")
+ .append(threshold)
+ .append("]");
+ if (condition.getName() != null && condition.getName().length() > 0) {
+ builder.append(" with call destination matching '")
+ .append(condition.getName())
+ .append("'");
+ }
+ }
+ break;
+ case TRAIT:
+ builder.append("Trait Change [")
+ .append(condition.getName())
+ .append("]");
+ break;
+ case CONTROL:
+ builder.append("Operation Execution [")
+ .append(condition.getName())
+ .append("] with result status [")
+ .append(condition.getOption())
+ .append("]");
+ break;
+ case RESOURCE_CONFIG:
+ builder.append("Resource Configuration Change");
+ break;
+ case EVENT:
+ builder.append("Event Detection [")
+ .append(condition.getName())
+ .append("]");
+ if (condition.getOption() != null && condition.getOption().length() > 0) {
+ builder.append(" with event source matching '")
+ .append(condition.getOption())
+ .append("'");
+ }
+ break;
+ case DRIFT:
+ String configNameRegex = condition.getName();
+ String pathNameRegex = condition.getOption();
+ if (configNameRegex == null || configNameRegex.length() == 0) {
+ if (pathNameRegex == null || pathNameRegex.length() == 0) {
+ // neither a config name regex nor path regex was specified
+ builder.append("Drift Detection");
+ } else {
+ // a path name regex was specified, but not a config name regex
+ builder.append("Drift Detection for files that match \"")
+ .append(pathNameRegex)
+ .append("\"");
+ }
+ } else {
+ if (pathNameRegex == null || pathNameRegex.length() == 0) {
+ // a config name regex was specified, but not a path name regex
+ builder.append("Drift Detection for drift definition [")
+ .append(configNameRegex)
+ .append("]");
+ } else {
+ // both a config name regex and a path regex was specified
+ builder.append("Drift Detection for files that match \"")
+ .append(pathNameRegex)
+ .append("\" and for drift detection [")
+ .append(configNameRegex)
+ .append("]");
+ }
+ }
+ break;
+ case RANGE:
+ String metricName = condition.getName();
+ MeasurementUnits metricUnits = condition.getMeasurementDefinition().getUnits();
+ double loValue = condition.getThreshold();
+ //String formattedLoValue = MeasurementConverterClient.format(loValue, units, true);
+ String formattedHiValue = condition.getOption();
+ try {
+ double hiValue = Double.parseDouble(formattedHiValue);
+ //formattedHiValue = MeasurementConverterClient.format(hiValue, units, true);
+ } catch (Exception e) {
+ formattedHiValue = "?[" + formattedHiValue + "]?"; // signify something is wrong with the value
+ }
+
+ // < means "inside the range", > means "outside the range" - exclusive
+ // <= means "inside the range", >= means "outside the range" - inclusive
+
+ if (condition.getComparator().equals("<")) {
+ // Metric Value Range: [{0}] between [{1}] and [{2}], exclusive
+ builder.append("Metric Value Range: [")
+ .append(metricName)
+ .append("] between ")
+ .append(loValue)
+ .append("] and [")
+ .append(formattedHiValue)
+ .append("], exclusive");
+ } else if (condition.getComparator().equals(">")) {
+ // Metric Value Range: [{0}] outside [{1}] and [{2}], exclusive
+ builder.append("Metric Value Range: [")
+ .append(metricName)
+ .append("] outside [")
+ .append(loValue)
+ .append("] and [")
+ .append(formattedHiValue)
+ .append("], exclusive");
+ } else if (condition.getComparator().equals("<=")) {
+ // Metric Value Range: [{0}] between [{1}] and [{2}], inclusive
+ builder.append("Metric Value Range: [")
+ .append(metricName)
+ .append("] between [")
+ .append(loValue)
+ .append("] and [")
+ .append(formattedHiValue)
+ .append("], inclusive");
+ } else if (condition.getComparator().equals(">=")) {
+ // Metric Value Range: [{0}] outside [{1}] and [{2}], inclusive
+ builder.append("Metric Value Range: [")
+ .append(metricName)
+ .append("] outside [")
+ .append(loValue)
+ .append("] and [")
+ .append(formattedHiValue)
+ .append("], inclusive");
+ } else {
+ builder.append("BAD COMPARATOR! Report this bug: " + condition.getComparator());
+ }
+ break;
+ default:
+ // Invalid condition category - please report this as a bug: {0}
+ builder.append("Invalid condition category - please report this as a bug: ")
+ .append(category.getName());
+ }
+ return builder.toString();
+ }
+
+ private String format(String value, MeasurementUnits targetUnits) {
+ if (targetUnits == null) {
+ return value;
+ } else {
+ return value + getMeasurementUnitAbbreviation(targetUnits);
+ }
+ }
+
+ private String getMeasurementUnitAbbreviation(MeasurementUnits units) {
+ switch (units) {
+ case NONE:
+ return "";
+ case PERCENTAGE:
+ return "%";
+ case BYTES:
+ return "B";
+ case KILOBYTES:
+ return "KB";
+ case MEGABYTES:
+ return "MB";
+ case GIGABYTES:
+ return "GB";
+ case TERABYTES:
+ return "TB";
+ case PETABYTES:
+ return "PB";
+ case BITS:
+ return "b";
+ case KILOBITS:
+ return "kb";
+ case MEGABITS:
+ return "Mb";
+ case GIGABITS:
+ return "Gb";
+ case TERABITS:
+ return "Tb";
+ case PETABITS:
+ return "Pb";
+ case EPOCH_MILLISECONDS:
+ return ""; // absolute time - no display
+ case EPOCH_SECONDS:
+ return ""; // absolute time - no display
+ case JIFFYS:
+ return "j";
+ case NANOSECONDS:
+ return "ns";
+ case MICROSECONDS:
+ return "us";
+ case MILLISECONDS:
+ return "ms";
+ case SECONDS:
+ return "s";
+ case MINUTES:
+ return "m";
+ case HOURS:
+ return "h";
+ case DAYS:
+ return "d";
+ case CELSIUS:
+ return "C";
+ case KELVIN:
+ return "K";
+ case FAHRENHEIGHT:
+ return "F";
+ default:
+ return units.toString();
+ }
+ }
+
+ private String getCalltimeChangeComparator(String comparator) {
+ if ("HI".equals(comparator)) {
+ return "Grows";
+ } else if ("LO".equals(comparator)) {
+ return "Shrinks";
+ } else { // CH
+ return "Changes";
+ }
+ }
+
};
}
12 years, 2 months
[rhq] etc/scripts
by ips
etc/scripts/jboss-as-spawn.sh | 101 +++++++++++++++++++++++++++++++++++-------
1 file changed, 85 insertions(+), 16 deletions(-)
New commits:
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
12 years, 2 months
[rhq] Branch 'feature/export-reports' - 2 commits - modules/enterprise
by mike thompson
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/ExportModalWindow.java | 46 ++++++---
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/operation/SubsystemOperationHistoryListView.java | 20 ----
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java | 50 +++++-----
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertLocal.java | 2
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java | 47 +++++----
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsLocal.java | 2
6 files changed, 89 insertions(+), 78 deletions(-)
New commits:
commit ba1af9b9c96452c2955016a5300b146f494011a6
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Tue Mar 27 10:46:21 2012 -0700
[BZ 800453] Export Csv Reports. Add filtering to Recent Operations and Recent Alerts.
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/ExportModalWindow.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/ExportModalWindow.java
index 0777dcc..f176120 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/ExportModalWindow.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/components/ExportModalWindow.java
@@ -38,15 +38,12 @@ import com.smartgwt.client.widgets.form.fields.SpacerItem;
import com.smartgwt.client.widgets.layout.HLayout;
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.operation.OperationRequestStatus;
import org.rhq.enterprise.gui.coregui.client.CoreGUI;
import org.rhq.enterprise.gui.coregui.client.IconEnum;
import org.rhq.enterprise.gui.coregui.client.Messages;
import org.rhq.enterprise.gui.coregui.client.PopupWindow;
import java.util.LinkedHashMap;
-import java.util.List;
import java.util.Set;
/**
@@ -75,11 +72,11 @@ public class ExportModalWindow {
/**
* For recent Alerts.
*/
- List<AlertPriority> alertPriorityList;
+ String[] alertPriorityFilters;
/**
* For Recent Operations.
*/
- List<OperationRequestStatus> operationRequestStatusList;
+ String[] operationRequestStatuses;
Set<Integer> resourceTypeIdsForExport;
@@ -105,15 +102,15 @@ public class ExportModalWindow {
return newExportDialog;
}
- public static ExportModalWindow createExportWindowForRecentAlerts(String reportUrl, List<AlertPriority> alertPriorityList) {
+ public static ExportModalWindow createExportWindowForRecentAlerts(String reportUrl, String[] alertPriorityList) {
ExportModalWindow newExportDialog = new ExportModalWindow(reportUrl);
- newExportDialog.setAlertPriorityList(alertPriorityList);
+ newExportDialog.setAlertPriorityFilters(alertPriorityList);
return newExportDialog;
}
- public static ExportModalWindow createExportWindowForRecentOperations(String reportUrl, List<OperationRequestStatus> operationRequestStatus) {
+ public static ExportModalWindow createExportWindowForRecentOperations(String reportUrl, String[] operationRequestStatuses ) {
ExportModalWindow newExportDialog = new ExportModalWindow(reportUrl);
- newExportDialog.setOperationRequestStatusList(operationRequestStatus);
+ newExportDialog.setOperationRequestStatusList(operationRequestStatuses);
return newExportDialog;
}
@@ -191,12 +188,12 @@ public class ExportModalWindow {
exportWindow.addItem(dialogLayout);
}
- public void setAlertPriorityList(List<AlertPriority> alertPriorityList) {
- this.alertPriorityList = alertPriorityList;
+ public void setAlertPriorityFilters(String[] alertPriorityFilters) {
+ this.alertPriorityFilters = alertPriorityFilters;
}
- public void setOperationRequestStatusList(List<OperationRequestStatus> operationRequestStatusList) {
- this.operationRequestStatusList = operationRequestStatusList;
+ public void setOperationRequestStatusList(String[] operationRequestStatuses) {
+ this.operationRequestStatuses = operationRequestStatuses;
}
public String calculateUrl(DynamicForm form) {
@@ -204,9 +201,28 @@ public class ExportModalWindow {
StringBuilder queryString = new StringBuilder();
if (showDetail) {
- queryString.append("?details").append(form.getValueAsString(DETAILS_FIELD));
+ queryString.append("details=").append(form.getValueAsString(DETAILS_FIELD));
}
- return URL.encode(BASE_URL + reportUrl + "." + format + queryString);
+ if(operationRequestStatuses != null){
+ StringBuilder operationRequestStatusBuffer = new StringBuilder();
+ for (String operationRequestStatus : operationRequestStatuses) {
+ operationRequestStatusBuffer.append(operationRequestStatus);
+ operationRequestStatusBuffer.append(",");
+ }
+
+ queryString.append("operationRequestStatus=").append(operationRequestStatusBuffer.toString());
+ }
+ if(alertPriorityFilters != null){
+ StringBuilder alertsPriorityBuffer = new StringBuilder();
+ for (String alertPriority : alertPriorityFilters) {
+ alertsPriorityBuffer.append(alertPriority);
+ alertsPriorityBuffer.append(",");
+ }
+ queryString.append("alertPriority=").append(alertsPriorityBuffer.toString());
+ }
+
+
+ return URL.encode(BASE_URL + reportUrl + "." + format + "?"+queryString);
}
public boolean isShowDetail(){
diff --git a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/operation/SubsystemOperationHistoryListView.java b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/operation/SubsystemOperationHistoryListView.java
index 1317885..f587c50 100644
--- a/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/operation/SubsystemOperationHistoryListView.java
+++ b/modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/report/operation/SubsystemOperationHistoryListView.java
@@ -21,14 +21,10 @@ package org.rhq.enterprise.gui.coregui.client.report.operation;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import org.rhq.core.domain.common.EntityContext;
-import org.rhq.core.domain.operation.OperationRequestStatus;
import org.rhq.enterprise.gui.coregui.client.components.ExportModalWindow;
import org.rhq.enterprise.gui.coregui.client.components.table.TableAction;
import org.rhq.enterprise.gui.coregui.client.operation.OperationHistoryView;
-import java.util.ArrayList;
-import java.util.List;
-
/**
* @author Ian Springer
* @author Jay Shaughnessy
@@ -57,21 +53,7 @@ public class SubsystemOperationHistoryListView extends OperationHistoryView {
@Override
public void executeAction(ListGridRecord[] selection, Object actionValue) {
- List<OperationRequestStatus> operationRequestStatusList = new ArrayList<OperationRequestStatus>(10);
- String[] operationalStatuses = statusFilter.getValues();
- for (String operationalStatus : operationalStatuses) {
- if(operationalStatus.equals(OperationRequestStatus.CANCELED.getDisplayName())){
- operationRequestStatusList.add(OperationRequestStatus.CANCELED);
- }else if(operationalStatus.equals(OperationRequestStatus.FAILURE.getDisplayName())){
- operationRequestStatusList.add(OperationRequestStatus.FAILURE);
- }else if(operationalStatus.equals(OperationRequestStatus.INPROGRESS.getDisplayName())){
- operationRequestStatusList.add(OperationRequestStatus.INPROGRESS);
- }else if(operationalStatus.equals(OperationRequestStatus.SUCCESS.getDisplayName())){
- operationRequestStatusList.add(OperationRequestStatus.SUCCESS);
- }
-
- }
- ExportModalWindow exportModalWindow = ExportModalWindow.createExportWindowForRecentOperations("recentOperations",operationRequestStatusList);
+ ExportModalWindow exportModalWindow = ExportModalWindow.createExportWindowForRecentOperations("recentOperations",statusFilter.getValues());
exportModalWindow.show();
refreshTableInfo();
}
commit decc58312b2b09598605b62f26217518691e5778
Author: Mike Thompson <mithomps(a)redhat.com>
Date: Tue Mar 27 11:09:49 2012 -0700
[BZ 800453] Export Csv Reports. Allow filtering on both Recent Alerts and Recent Operations. Rebase, Merge.
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 2b43369..7904c01 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,21 +1,9 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-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.AlertPriority;
import org.rhq.core.domain.criteria.AlertCriteria;
import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.server.alert.AlertManagerLocal;
@@ -25,6 +13,19 @@ 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.HttpHeaders;
+import javax.ws.rs.core.Request;
+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.ReportHelper.cleanForCSV;
import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
@@ -32,6 +33,8 @@ import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTi
@Stateless
public class RecentAlertHandler extends AbstractRestBean implements RecentAlertLocal {
+ private final Log log = LogFactory.getLog(RecentAlertHandler.class);
+
@EJB
private AlertManagerLocal alertManager;
@@ -40,16 +43,21 @@ public class RecentAlertHandler extends AbstractRestBean implements RecentAlertL
@Override
public StreamingOutput recentAlerts(
- @QueryParam("alertPriority") @DefaultValue("high") final String alertPriority,
- @Context UriInfo uriInfo,
- @Context Request request, @Context HttpHeaders headers) {
+ final String alertPriority,
+ UriInfo uriInfo,
+ Request request, HttpHeaders headers) {
return new StreamingOutput() {
@Override
public void write(OutputStream stream) throws IOException, WebApplicationException {
final AlertCriteria criteria = new AlertCriteria();
-// if(alertPriority != null){
-// criteria.addFilterPriorities(AlertPriority.valueOf(alertPriority.toUpperCase()));
-// }
+
+ List<AlertPriority> alertPriorityList = new ArrayList<AlertPriority>(10);
+ String alertPriorities[] = alertPriority.split(",");
+ for ( String alertPriorityValue : alertPriorities) {
+ log.info("Alert Priority Filter set for: " + alertPriorityValue);
+ alertPriorityList.add(AlertPriority.valueOf(alertPriorityValue.toUpperCase()));
+ }
+ criteria.addFilterPriorities(alertPriorityList.toArray(new AlertPriority[alertPriorityList.size()]));
CriteriaQueryExecutor<Alert, AlertCriteria> queryExecutor =
new CriteriaQueryExecutor<Alert, AlertCriteria>() {
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertLocal.java
index c07085a..2fc17bb 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertLocal.java
@@ -12,7 +12,7 @@ public interface RecentAlertLocal {
@Path("/")
@Produces({"text/csv", "application/xml"})
StreamingOutput recentAlerts(
- @QueryParam("alertPriority") @DefaultValue("High") String alertPriority,
+ @QueryParam("alertPriority") @DefaultValue("High,Med,Low") String alertPriority,
@Context UriInfo uriInfo,
@Context Request request,
@Context HttpHeaders headers);
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 53de6cc..6786e30 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,21 +1,9 @@
package org.rhq.enterprise.server.rest.reporting;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import javax.ejb.EJB;
-import javax.ejb.Stateless;
-import javax.interceptor.Interceptors;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Request;
-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;
import org.rhq.core.domain.util.PageList;
import org.rhq.enterprise.server.auth.SubjectManagerLocal;
@@ -25,6 +13,19 @@ 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.HttpHeaders;
+import javax.ws.rs.core.Request;
+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.ReportHelper.cleanForCSV;
import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTime;
@@ -32,6 +33,7 @@ import static org.rhq.enterprise.server.rest.reporting.ReportHelper.formatDateTi
@Stateless
public class RecentOperationsHandler extends AbstractRestBean implements RecentOperationsLocal {
+ private final Log log = LogFactory.getLog(RecentOperationsHandler.class);
@EJB
private OperationManagerLocal operationManager;
@@ -41,17 +43,20 @@ public class RecentOperationsHandler extends AbstractRestBean implements RecentO
@Override
public StreamingOutput recentOperations(
- @QueryParam("operationRequestStatus") @DefaultValue("failure")
final String operationRequestStatus,
- @Context UriInfo uriInfo, @Context Request request, @Context HttpHeaders headers) {
+ UriInfo uriInfo, Request request, HttpHeaders headers) {
return new StreamingOutput() {
@Override
public void write(OutputStream stream) throws IOException, WebApplicationException {
- //@todo: add ability to pass multiple operations
final ResourceOperationHistoryCriteria criteria = new ResourceOperationHistoryCriteria();
-// if(operationRequestStatus != null){
-// criteria.addFilterStatus(OperationRequestStatus.valueOf(operationRequestStatus.toUpperCase()));
-// }
+
+ List<OperationRequestStatus> operationRequestStatusList = new ArrayList<OperationRequestStatus>(10);
+ String statuses[] = operationRequestStatus.split(",");
+ for (String requestStatus : statuses) {
+ log.info("OperationRequestStatus Filter set for: " + requestStatus);
+ operationRequestStatusList.add(OperationRequestStatus.valueOf(requestStatus.toUpperCase()));
+ }
+ criteria.addFilterStatuses(operationRequestStatusList.toArray(new OperationRequestStatus[operationRequestStatusList.size()]));
CriteriaQueryExecutor<ResourceOperationHistory, ResourceOperationHistoryCriteria> queryExecutor =
new CriteriaQueryExecutor<ResourceOperationHistory, ResourceOperationHistoryCriteria>() {
diff --git a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsLocal.java b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsLocal.java
index 5e6c04d..814a2b6 100644
--- a/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsLocal.java
+++ b/modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsLocal.java
@@ -12,7 +12,7 @@ public interface RecentOperationsLocal {
@Path("/")
@Produces({"text/csv", "application/xml"})
StreamingOutput recentOperations(
- @QueryParam("operationRequestStatus") @DefaultValue("Failure") String operationStatus,
+ @QueryParam("operationRequestStatus") @DefaultValue("InProgress,Success,Failure,Cancelled") String operationRequestStatus,
@Context UriInfo uriInfo,
@Context Request request,
@Context HttpHeaders headers);
12 years, 2 months
[rhq] modules/plugins
by ips
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/BaseProcessDiscovery.java | 62 +-----
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/HostControllerDiscovery.java | 8
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/JBossProductType.java | 92 ++++++++++
modules/plugins/jboss-as-7/src/main/java/org/rhq/modules/plugins/jbossas7/StandaloneASDiscovery.java | 13 -
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 4
5 files changed, 120 insertions(+), 59 deletions(-)
New commits:
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"/>
12 years, 2 months
[rhq] 3 commits - modules/enterprise
by Jay Shaughnessy
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/detail/summary/AbstractActivityView.java | 59 +++++----
modules/enterprise/gui/coregui/src/main/java/org/rhq/enterprise/gui/coregui/client/inventory/resource/detail/ResourceDetailView.java | 2
7 files changed, 75 insertions(+), 113 deletions(-)
New commits:
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);
12 years, 2 months
[rhq] Branch 'feature/export-reports' - modules/enterprise
by John Sanda
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/AlertDefinitionHandler.java | 2 -
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ConfigurationHistoryHandler.java | 3 +
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/InventorySummaryHandler.java | 6 +--
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentAlertHandler.java | 2 -
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentDriftHandler.java | 2 -
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/RecentOperationsHandler.java | 2 -
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/ReportHelper.java | 20 ++++++++++
modules/enterprise/server/jar/src/main/java/org/rhq/enterprise/server/rest/reporting/SuspectMetricHandler.java | 16 +++++---
8 files changed, 39 insertions(+), 14 deletions(-)
New commits:
commit 14730b310f62d3a0cfb9ded103425cf0656b4673
Author: John Sanda <jsanda(a)redhat.com>
Date: Tue Mar 27 12:31:18 2012 -0400
[BZ 802544] Parse ancestry field so we display same value as UI
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 42c8a7f..8c9a8ef 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
@@ -80,7 +80,7 @@ public class AlertDefinitionHandler extends AbstractRestBean implements AlertDef
+ alertDefinition.getEnabled() + ","
+ alertDefinition.getPriority() + ","
+ cleanForCSV(getParentName(resource)) + ","
- + cleanForCSV(resource.getAncestry());
+ + cleanForCSV(ReportHelper.parseAncestry(resource.getAncestry()));
}
private String getParentName(Resource resource){
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 9a336c3..60547fa 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
@@ -71,9 +71,10 @@ public class ConfigurationHistoryHandler extends AbstractRestBean implements Con
+ formatDateTime(configurationUpdate.getCreatedTime())+","
+ formatDateTime(configurationUpdate.getModifiedTime())+","
+ configurationUpdate.getStatus()+","
- + cleanForCSV(configurationUpdate.getResource().getAncestry());
+ + cleanForCSV(ReportHelper.parseAncestry(configurationUpdate.getResource().getAncestry()));
//@todo: check dates, user, update-type
}
+
private String getHeader(){
return "Name,Version,Date Submitted,Date Completed,Status,Ancestry";
}
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 97281b7..d1d0d37 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
@@ -178,8 +178,8 @@ public class InventorySummaryHandler extends AbstractRestBean implements Invento
}
protected String toCSV(Resource resource) {
- return resource.getName() + "," + resource.getAncestry() + "," + resource.getDescription() + "," +
- resource.getResourceType().getName() + "," + resource.getVersion() + "," +
- resource.getCurrentAvailability().getAvailabilityType();
+ return resource.getName() + "," + ReportHelper.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 101fc34..2b43369 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
@@ -77,7 +77,7 @@ public class RecentAlertHandler extends AbstractRestBean implements RecentAlertL
alert.getAlertDefinition().getPriority() + "," +
"Status"+ "," +
cleanForCSV(alert.getAlertDefinition().getResource().getName())+","+
- cleanForCSV(alert.getAlertDefinition().getResource().getAncestry());
+ cleanForCSV(ReportHelper.parseAncestry(alert.getAlertDefinition().getResource().getAncestry()));
}
private String getHeader(){
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 ef28b05..5e3d71d 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
@@ -74,7 +74,7 @@ public class RecentDriftHandler extends AbstractRestBean implements RecentDriftL
drift.getDrift().getCategory() + "," +
drift.getDrift().getPath() + "," +
cleanForCSV(drift.getResource().getName()) +","+
- cleanForCSV(drift.getResource().getAncestry());
+ cleanForCSV(ReportHelper.parseAncestry(drift.getResource().getAncestry()));
}
private String getHeader(){
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 2890415..53de6cc 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
@@ -78,7 +78,7 @@ public class RecentOperationsHandler extends AbstractRestBean implements RecentO
operation.getSubjectName() + "," +
operation.getStatus() + "," +
cleanForCSV(operation.getResource().getName()) +","+
- cleanForCSV(operation.getResource().getAncestry());
+ cleanForCSV(ReportHelper.parseAncestry(operation.getResource().getAncestry()));
}
private String getHeader(){
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
index f0f4269..8b0b043 100644
--- 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
@@ -23,6 +23,8 @@ 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.
*/
@@ -65,4 +67,22 @@ public class ReportHelper {
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 f1b6fc2..607183f 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,7 +1,16 @@
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;
@@ -10,11 +19,6 @@ 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.*;
-
@Interceptors(SetCallerInterceptor.class)
@Stateless
public class SuspectMetricHandler extends AbstractRestBean implements SuspectMetricLocal {
@@ -49,7 +53,7 @@ public class SuspectMetricHandler extends AbstractRestBean implements SuspectMet
for (MeasurementOOBComposite oobComposite : comps) {
sb.append( oobComposite.getResourceName());
sb.append(",");
- sb.append( oobComposite.getResourceAncestry());
+ sb.append(ReportHelper.parseAncestry(oobComposite.getResourceAncestry()));
sb.append(",");
sb.append( oobComposite.getUnits()); // Metric
sb.append(",");
12 years, 2 months
[rhq] modules/core
by ips
modules/core/arquillian-integration/container/src/main/java/org/rhq/test/arquillian/impl/RhqAgentPluginContainer.java | 94 +++++++++-
1 file changed, 85 insertions(+), 9 deletions(-)
New commits:
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);
+ }
+ }
+
}
12 years, 2 months
[rhq] 3 commits - modules/core modules/plugins
by ips
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/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/plugin-test-util/src/main/java/org/rhq/core/plugin/testutil/AbstractAgentPluginTest.java | 1
modules/plugins/jboss-as-5/src/test/java/org/rhq/plugins/jbossas5/itest/ApplicationServerComponentTest.java | 14 -
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 118 +++++-----
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractJBossAS7PluginTest.java | 52 +++-
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/AbstractServerComponentTest.java | 15 -
modules/plugins/jboss-as-7/src/test/java/org/rhq/modules/plugins/jbossas7/itest/domain/DomainServerComponentTest.java | 2
modules/plugins/jboss-as-7/src/test/resources/log4j.xml | 5
12 files changed, 229 insertions(+), 93 deletions(-)
New commits:
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"
12 years, 2 months
[rhq] 4 commits - modules/plugins
by Simeon Pinder
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/ModClusterComponent.java | 146 +++-
modules/plugins/jboss-as-7/src/main/resources/META-INF/rhq-plugin.xml | 127 +++
3 files changed, 414 insertions(+), 199 deletions(-)
New commits:
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"
12 years, 2 months
[rhq] modules/plugins
by lkrejci
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
73 files changed, 2108 insertions(+), 2026 deletions(-)
New commits:
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;
}
12 years, 2 months