Return-Path: X-Original-To: apmail-sling-commits-archive@www.apache.org Delivered-To: apmail-sling-commits-archive@www.apache.org Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by minotaur.apache.org (Postfix) with SMTP id 143C71009D for ; Mon, 12 Aug 2013 14:50:23 +0000 (UTC) Received: (qmail 70828 invoked by uid 500); 12 Aug 2013 14:50:22 -0000 Delivered-To: apmail-sling-commits-archive@sling.apache.org Received: (qmail 70155 invoked by uid 500); 12 Aug 2013 14:50:17 -0000 Mailing-List: contact commits-help@sling.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@sling.apache.org Delivered-To: mailing list commits@sling.apache.org Received: (qmail 70139 invoked by uid 99); 12 Aug 2013 14:50:15 -0000 Received: from athena.apache.org (HELO athena.apache.org) (140.211.11.136) by apache.org (qpsmtpd/0.29) with ESMTP; Mon, 12 Aug 2013 14:50:15 +0000 X-ASF-Spam-Status: No, hits=-2000.0 required=5.0 tests=ALL_TRUSTED X-Spam-Check-By: apache.org Received: from [140.211.11.4] (HELO eris.apache.org) (140.211.11.4) by apache.org (qpsmtpd/0.29) with ESMTP; Mon, 12 Aug 2013 14:50:12 +0000 Received: from eris.apache.org (localhost [127.0.0.1]) by eris.apache.org (Postfix) with ESMTP id A1B4D23888CD; Mon, 12 Aug 2013 14:49:51 +0000 (UTC) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: svn commit: r1513154 - in /sling/trunk/contrib/extensions/healthcheck: core/src/main/java/org/apache/sling/hc/api/ core/src/main/java/org/apache/sling/hc/impl/ core/src/main/java/org/apache/sling/hc/impl/healthchecks/ core/src/main/java/org/apache/slin... Date: Mon, 12 Aug 2013 14:49:50 -0000 To: commits@sling.apache.org From: bdelacretaz@apache.org X-Mailer: svnmailer-1.0.9 Message-Id: <20130812144951.A1B4D23888CD@eris.apache.org> X-Virus-Checked: Checked by ClamAV on apache.org Author: bdelacretaz Date: Mon Aug 12 14:49:50 2013 New Revision: 1513154 URL: http://svn.apache.org/r1513154 Log: SLING-2987 - refactor API, especially the Result model Added: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLogEntry.java (with props) sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/HealthCheckInfo.java Removed: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLog.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/api/ResultLogTest.java Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/HealthCheck.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/Result.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckMBean.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckWebconsolePlugin.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/DefaultLoginsHealthCheck.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxAttributeHealthCheck.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxScriptBinding.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/OsgiScriptBinding.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/ScriptableHealthCheck.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/SlingRequestStatusHealthCheck.java sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/SimpleConstraintChecker.java sling/trunk/contrib/extensions/healthcheck/core/src/main/resources/res/ui/healthcheck.css sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/api/ResultTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/DefaultLoginsHealthCheckTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/HealthCheckMBeanTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxAttributeHealthCheckTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxScriptBindingTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/OsgiScriptBindingTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/ScriptableHealthCheckTest.java sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/SimpleConstraintCheckerTest.java sling/trunk/contrib/extensions/healthcheck/it/src/test/java/org/apache/sling/hc/it/core/HealthCheckSelectorTest.java Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/HealthCheck.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/HealthCheck.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/HealthCheck.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/HealthCheck.java Mon Aug 12 14:49:50 2013 @@ -23,16 +23,12 @@ import java.util.Map; * return an execution Result */ public interface HealthCheck { - /** Execute this health check. - * @param log Any messages written to that log at or above the - * {@link ResultLog.MIN_LEVEL_TO_REPORT} level mean - * that the health check failed. - */ - public Result execute(ResultLog log); + /** Execute this health check and return a {@link Result} */ + public Result execute(); /** Additional (static) information about * this check. {@link Constants} defines - * some well-known property names. + * some well-known property names. */ public Map getInfo(); } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/Result.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/Result.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/Result.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/Result.java Mon Aug 12 14:49:50 2013 @@ -17,32 +17,84 @@ */ package org.apache.sling.hc.api; +import java.util.Iterator; +import java.util.LinkedList; import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** The result of executing a {@link HealthCheck} */ -public class Result { +public class Result implements Iterable { + + private final Logger logger; + private static final Logger CLASS_LOGGER = LoggerFactory.getLogger(Result.class); - private final HealthCheck healthCheck; - private final ResultLog log; + private final List logEntries = new LinkedList(); + private Status status = Status.OK; - public Result(HealthCheck hc, ResultLog log) { - healthCheck = hc; - this.log = log; + public enum Status { + OK, // no problem + WARN, // health check detected something wrong but not critical + CRITICAL, // health check detected a critical problem + HEALTH_CHECK_ERROR // health check did not execute properly + } + + /** Build a Result using the default logger */ + public Result() { + this(null); } - public HealthCheck getHealthCheck() { - return healthCheck; + /** Build a Result that logs to a specific logger */ + public Result(Logger logger) { + this.logger = logger != null ? logger : CLASS_LOGGER; } - public List getLogEntries() { - return log.getEntries(); + /** Add an entry to our log. Use the {@ResultLogEntry}.LT_* constants + * for well-known entry types. + * Adding an entry with a type where {@ResultLogEntry#isInformationalEntryType} returns + * false causes our status to be set to WARN, unless it was already set higher. + */ + public void log(String entryType, String message) { + if(logger.isDebugEnabled() && ResultLogEntry.LT_DEBUG.equals(entryType)) { + logger.debug(message); + } else if(logger.isInfoEnabled() && ResultLogEntry.LT_INFO.equals(entryType)) { + logger.info(message); + } else { + logger.warn(message); + } + logEntries.add(new ResultLogEntry(entryType, message)); + if(!ResultLogEntry.isInformationalEntryType(entryType) && status.ordinal() < Status.WARN.ordinal()) { + logger.warn("Setting Result status to WARN due to log entry of type {}", entryType); + setStatus(Status.WARN); + } } + /** Set this Result's status. Attempts to set it lower than the current + * status are ignored. + */ + public void setStatus(Status s) { + if(s.ordinal() > status.ordinal()) { + status = s; + } else { + logger.debug("setStatus({}) ignored as current status {} is higher", s, status); + } + } + + public Iterator iterator() { + return logEntries.iterator(); + } + + /** True if our status is OK - just to have a convenient way of + * checking that. + */ public boolean isOk() { - return log.getMaxLevel() != null && log.getMaxLevel().ordinal() < ResultLog.MIN_LEVEL_TO_REPORT.ordinal(); + return status.ordinal() == Status.OK.ordinal(); } - public ResultLog.Level getStatus() { - return isOk() ? ResultLog.Level.OK : log.getMaxLevel(); + /** Return our Status */ + public Status getStatus() { + return status; } -} + +} \ No newline at end of file Added: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLogEntry.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLogEntry.java?rev=1513154&view=auto ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLogEntry.java (added) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLogEntry.java Mon Aug 12 14:49:50 2013 @@ -0,0 +1,77 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The SF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.apache.sling.hc.api; + + + +/** A entry in the log of a {@link Result} */ +public class ResultLogEntry { + + private final String entryType; + private final String message; + + /** Standard log entry type DEBUG */ + public static final String LT_DEBUG = "DEBUG"; + + /** Standard log entry type INFO: general informational message */ + public static final String LT_INFO = "INFO"; + + /** Standard log entry type WARN: general warning message */ + public static final String LT_WARN = "WARN"; + + /** Standard log entry type SECURITY: security-related warning */ + public static final String LT_WARN_SECURITY = "SECURITY"; + + /** Standard log entry type: configuration-related warning */ + public static final String LT_WARN_CONFIG = "CONFIG"; + + /** Build a log entry. + * @param entryType The type of this log entry, this is a String instead of an Enum + * so that health checks can invent their own types if needed. + * For the usual entry types, use the LT_* constants of this class. + * By convention, any log entry that's not LT_DEBUG or LT_INFO causes + * the Result to move to the WARN result state, unless it already was set to a higher state. + * + * @param message The log message. + */ + ResultLogEntry(String entryType, String message) { + this.entryType = entryType; + this.message = message; + } + + public String getEntryType() { + return entryType; + } + + /** The log message */ + public String getMessage() { + return message; + } + + @Override + public String toString() { + return new StringBuilder(entryType).append(" ").append(message).toString(); + } + + /** True if the given entryType is one that does not cause Result to + * raise its state to WARN. + */ + public static boolean isInformationalEntryType(String entryType) { + return LT_DEBUG.equals(entryType) || LT_INFO.equals(entryType); + } +} Propchange: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/api/ResultLogEntry.java ------------------------------------------------------------------------------ svn:mime-type = text/plain Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckMBean.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckMBean.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckMBean.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckMBean.java Mon Aug 12 14:49:50 2013 @@ -19,6 +19,7 @@ package org.apache.sling.hc.impl; import java.io.Serializable; import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; @@ -44,7 +45,7 @@ import javax.management.openmbean.Tabula import org.apache.sling.hc.api.Constants; import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; +import org.apache.sling.hc.api.ResultLogEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -108,8 +109,7 @@ public class HealthCheckMBean implements throws AttributeNotFoundException, MBeanException, ReflectionException { // TODO cache the result of execution for a few seconds? - final ResultLog resultLog = new ResultLog(logger); - final Result result = healthCheck.execute(resultLog); + final Result result = healthCheck.execute(); if(HC_OK_ATTRIBUTE_NAME.equals(attribute)) { return result.isOk(); @@ -127,10 +127,10 @@ public class HealthCheckMBean implements private TabularData logData(Result er) { final TabularDataSupport result = new TabularDataSupport(LOG_TABLE_TYPE); int i=1; - for(ResultLog.Entry e : er.getLogEntries()) { + for(ResultLogEntry e : er) { final Map data = new HashMap(); data.put(INDEX_COLUMN, i++); - data.put(LEVEL_COLUMN, e.getLevel().toString()); + data.put(LEVEL_COLUMN, e.getEntryType()); data.put(MESSAGE_COLUMN, e.getMessage()); try { result.put(new CompositeDataSupport(LOG_ROW_TYPE, data)); Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckWebconsolePlugin.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckWebconsolePlugin.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckWebconsolePlugin.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/HealthCheckWebconsolePlugin.java Mon Aug 12 14:49:50 2013 @@ -38,9 +38,7 @@ import org.apache.sling.hc.api.Constants import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.HealthCheckSelector; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.sling.hc.api.ResultLogEntry; /** Webconsole plugin to execute health check services */ @Component(immediate=true) @@ -56,8 +54,6 @@ import org.slf4j.LoggerFactory; }) public class HealthCheckWebconsolePlugin extends HttpServlet { - private final Logger log = LoggerFactory.getLogger(getClass()); - public static final String TITLE = "Sling Health Check"; public static final String LABEL = "healthcheck"; public static final String CATEGORY = "Sling"; @@ -108,14 +104,13 @@ public class HealthCheckWebconsolePlugin int total = 0; int failed = 0; for(HealthCheck hc : checks) { - final ResultLog rl = new ResultLog(log); - final Result r = hc.execute(rl); + final Result r = hc.execute(); total++; if(!r.isOk()) { failed++; } if(!quiet || !r.isOk()) { - renderResult(resp, r, debug); + renderResult(resp, hc, r, debug); } } final WebConsoleHelper c = new WebConsoleHelper(resp.getWriter()); @@ -124,12 +119,12 @@ public class HealthCheckWebconsolePlugin } } - private void renderResult(HttpServletResponse resp, Result result, boolean debug) throws IOException { + private void renderResult(HttpServletResponse resp, HealthCheck hc, Result result, boolean debug) throws IOException { final WebConsoleHelper c = new WebConsoleHelper(resp.getWriter()); final StringBuilder status = new StringBuilder(); - status.append("Tags: ").append(result.getHealthCheck().getInfo().get(Constants.HC_TAGS)); - c.titleHtml(getDescription(result.getHealthCheck()), null); + status.append("Tags: ").append(hc.getInfo().get(Constants.HC_TAGS)); + c.titleHtml(getDescription(hc), null); c.tr(); c.tdContent(); @@ -137,20 +132,20 @@ public class HealthCheckWebconsolePlugin c.writer().print("
Result: "); - c.writer().print(result.isOk() ? "Ok" : "NOT OK"); + c.writer().print(result.getStatus().toString()); c.writer().print(""); c.closeTd(); c.closeTr(); c.tr(); c.tdContent(); - for(ResultLog.Entry e : result.getLogEntries()) { - if(!debug && e.getLevel().ordinal() <= ResultLog.Level.DEBUG.ordinal()) { + for(ResultLogEntry e : result) { + if(!debug && e.getEntryType().equals(ResultLogEntry.LT_DEBUG)) { continue; } final StringBuilder sb = new StringBuilder(); - sb.append("
"); - sb.append(e.getLevel().toString()) + sb.append("
"); + sb.append(e.getEntryType()) .append(" ") .append(ResponseUtil.escapeXml(e.getMessage())) .append("
"); Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/DefaultLoginsHealthCheck.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/DefaultLoginsHealthCheck.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/DefaultLoginsHealthCheck.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/DefaultLoginsHealthCheck.java Mon Aug 12 14:49:50 2013 @@ -18,7 +18,6 @@ package org.apache.sling.hc.impl.healthchecks; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -37,7 +36,8 @@ import org.apache.sling.commons.osgi.Pro import org.apache.sling.hc.api.Constants; import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; +import org.apache.sling.hc.api.ResultLogEntry; +import org.apache.sling.hc.util.HealthCheckInfo; import org.apache.sling.jcr.api.SlingRepository; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; @@ -54,7 +54,7 @@ import org.slf4j.LoggerFactory; public class DefaultLoginsHealthCheck implements HealthCheck { private final Logger log = LoggerFactory.getLogger(getClass()); - private final Map info = new HashMap(); + private Map info; @Property(cardinality=500) public static final String PROP_LOGINS = "logins"; @@ -74,26 +74,21 @@ public class DefaultLoginsHealthCheck im @Activate public void activate(ComponentContext ctx) { + info = new HealthCheckInfo(ctx.getProperties()); logins = Arrays.asList(PropertiesUtil.toStringArray(ctx.getProperties().get(PROP_LOGINS), new String[] {})); - - info.put(Constants.HC_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_NAME), "")); - info.put(Constants.HC_MBEAN_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_MBEAN_NAME), "")); - info.put(Constants.HC_TAGS, - Arrays.asList(PropertiesUtil.toStringArray(ctx.getProperties().get(Constants.HC_TAGS), new String[] {})).toString()); - log.info("Activated, logins={}", logins); } @Override - public Result execute(ResultLog log) { - final Result result = new Result(this, log); + public Result execute() { + final Result result = new Result(log); int checked=0; int failures=0; for(String login : logins) { final String [] parts = login.split(":"); if(parts.length != 2) { - log.warn("Expected login in the form username:password, got {}", login); + result.log(ResultLogEntry.LT_WARN, "Expected login in the form username:password, got " + login); continue; } checked++; @@ -105,12 +100,12 @@ public class DefaultLoginsHealthCheck im s = repository.login(creds); if(s != null) { failures++; - log.warn("Login as [{}] succeeded, was expecting it to fail", username); + result.log(ResultLogEntry.LT_WARN_SECURITY, "Login as [" + username + "] succeeded, was expecting it to fail"); } else { - log.debug("Login as [{}] didn't throw an Exception but returned null Session", username); + result.log(ResultLogEntry.LT_DEBUG, "Login as [" + username + "] didn't throw an Exception but returned null Session"); } } catch(RepositoryException re) { - log.debug("Login as [{}] failed, as expected", username); + result.log(ResultLogEntry.LT_DEBUG, "Login as [" + username + "] failed, as expected"); } finally { if(s != null) { s.logout(); @@ -119,11 +114,11 @@ public class DefaultLoginsHealthCheck im } if(checked==0) { - log.warn("Did not check any logins, configured logins={}", logins); + result.log(ResultLogEntry.LT_WARN, "Did not check any logins, configured logins=" + logins); } else if(failures != 0){ - log.warn("Checked {} logins, {} tests failed", checked, failures); + result.log(ResultLogEntry.LT_WARN_SECURITY, "Checked " + checked + " logins, " + failures + " tests failed"); } else { - log.debug("Checked {} logins, all tests successful", checked); + result.log(ResultLogEntry.LT_DEBUG, "Checked " + checked + " logins, all tests successful"); } return result; } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxAttributeHealthCheck.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxAttributeHealthCheck.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxAttributeHealthCheck.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxAttributeHealthCheck.java Mon Aug 12 14:49:50 2013 @@ -18,8 +18,6 @@ package org.apache.sling.hc.impl.healthchecks; import java.lang.management.ManagementFactory; -import java.util.Arrays; -import java.util.HashMap; import java.util.Map; import javax.management.MBeanServer; @@ -34,11 +32,13 @@ import org.apache.sling.commons.osgi.Pro import org.apache.sling.hc.api.Constants; import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; +import org.apache.sling.hc.api.ResultLogEntry; +import org.apache.sling.hc.util.HealthCheckInfo; import org.apache.sling.hc.util.SimpleConstraintChecker; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.helpers.MessageFormatter; /** {@link HealthCheck} that checks a single JMX attribute */ @Component( @@ -50,7 +50,7 @@ import org.slf4j.LoggerFactory; public class JmxAttributeHealthCheck implements HealthCheck { private final Logger log = LoggerFactory.getLogger(getClass()); - private final Map info = new HashMap(); + private Map info; private String mbeanName; private String attributeName; private String constraint; @@ -75,6 +75,7 @@ public class JmxAttributeHealthCheck imp @Activate public void activate(ComponentContext ctx) { + info = new HealthCheckInfo(ctx.getProperties()); mbeanName = PropertiesUtil.toString(ctx.getProperties().get(PROP_OBJECT_NAME), ""); attributeName = PropertiesUtil.toString(ctx.getProperties().get(PROP_ATTRIBUTE_NAME), ""); constraint = PropertiesUtil.toString(ctx.getProperties().get(PROP_CONSTRAINT), ""); @@ -82,19 +83,17 @@ public class JmxAttributeHealthCheck imp info.put(PROP_OBJECT_NAME, mbeanName); info.put(PROP_ATTRIBUTE_NAME, attributeName); info.put(PROP_CONSTRAINT, constraint); - info.put(Constants.HC_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_NAME), "")); - info.put(Constants.HC_MBEAN_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_MBEAN_NAME), "")); - info.put(Constants.HC_TAGS, - Arrays.asList(PropertiesUtil.toStringArray(ctx.getProperties().get(Constants.HC_TAGS), new String[] {})).toString()); log.info("Activated with HealthCheck name={}, objectName={}, attribute={}, constraint={}", new Object[] { info.get(Constants.HC_NAME), mbeanName, attributeName, constraint }); } @Override - public Result execute(ResultLog log) { - final Result result = new Result(this, log); - log.debug("Checking {} / {} with constraint {}", new Object[] { mbeanName, attributeName, constraint }); + public Result execute() { + final Result result = new Result(log); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format("Checking {} / {} with constraint {}", + new Object[] { mbeanName, attributeName, constraint }).getMessage()); try { final MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer(); final ObjectName objectName = new ObjectName(mbeanName); @@ -103,7 +102,7 @@ public class JmxAttributeHealthCheck imp } final Object value = jmxServer.getAttribute(objectName, attributeName); log.debug("{} {} returns {}", new Object[] { mbeanName, attributeName, value }); - new SimpleConstraintChecker().check(value, constraint, log); + new SimpleConstraintChecker().check(value, constraint, result); } catch(Exception e) { log.warn(e.toString(), e); } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxScriptBinding.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxScriptBinding.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxScriptBinding.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/JmxScriptBinding.java Mon Aug 12 14:49:50 2013 @@ -27,7 +27,9 @@ import javax.management.MalformedObjectN import javax.management.ObjectName; import javax.management.ReflectionException; -import org.slf4j.Logger; +import org.apache.sling.hc.api.Result; +import org.apache.sling.hc.api.ResultLogEntry; +import org.slf4j.helpers.MessageFormatter; /** The JmxBinding is meant to be bound as "jmx" global variables * in scripted rules, to allow for writing scripted expressions @@ -35,10 +37,10 @@ import org.slf4j.Logger; */ public class JmxScriptBinding { private MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer(); - private final Logger logger; + private final Result result; - public JmxScriptBinding(Logger logger) { - this.logger = logger; + public JmxScriptBinding(Result result) { + this.result = result; } public Object attribute(String objectNameString, String attributeName) @@ -46,12 +48,15 @@ public class JmxScriptBinding { final ObjectName name = new ObjectName(objectNameString); if(jmxServer.queryNames(name, null).size() == 0) { final String msg = "JMX object name not found: [" + objectNameString + "]"; - logger.warn(msg); + result.log(ResultLogEntry.LT_WARN, msg); throw new IllegalStateException(msg); } - logger.debug("Got JMX Object [{}]", name); + result.log(ResultLogEntry.LT_DEBUG, MessageFormatter.format("Got JMX Object [{}]", name).getMessage()); final Object value = jmxServer.getAttribute(name, attributeName); - logger.debug("JMX Object [{}] Attribute [{}] = [{}]", new Object[] { name, attributeName, value }); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format( + "JMX Object [{}] Attribute [{}] = [{}]", + new Object[] { name, attributeName, value }).getMessage()); return value; } } \ No newline at end of file Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/OsgiScriptBinding.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/OsgiScriptBinding.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/OsgiScriptBinding.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/OsgiScriptBinding.java Mon Aug 12 14:49:50 2013 @@ -17,21 +17,23 @@ */ package org.apache.sling.hc.impl.healthchecks; +import org.apache.sling.hc.api.Result; +import org.apache.sling.hc.api.ResultLogEntry; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; -import org.slf4j.Logger; +import org.slf4j.helpers.MessageFormatter; /** The OsgiBinding is meant to be bound as an "osgi" global variable * in scripted rules, to allow for checking some OSGi states in * a simple way */ public class OsgiScriptBinding { - private final Logger logger; + private final Result result; private final BundleContext bundleContext; - public OsgiScriptBinding(BundleContext ctx, Logger logger) { - this.logger = logger; + public OsgiScriptBinding(BundleContext ctx, Result result) { + this.result = result; this.bundleContext = ctx; } @@ -42,24 +44,27 @@ public class OsgiScriptBinding { count++; } } - logger.debug("inactiveBundlesCount={}", count); + result.log(ResultLogEntry.LT_DEBUG, MessageFormatter.format("inactiveBundlesCount={}", count).getMessage()); return count; } private boolean isActive(Bundle b) { - boolean result = true; + boolean active = true; if(!isFragment(b) && Bundle.ACTIVE != b.getState()) { - result = false; - logger.info("Bundle {} is not active, state={} ({})", - new Object[] { b.getSymbolicName(), b.getState(), b.getState()}); + active = false; + result.log(ResultLogEntry.LT_INFO, + MessageFormatter.format( + "Bundle {} is not active, state={} ({})", + new Object[] { b.getSymbolicName(), b.getState(), b.getState()}).getMessage()); } - return result; + return active; } private boolean isFragment(Bundle b) { final String header = (String) b.getHeaders().get( Constants.FRAGMENT_HOST ); if(header!= null && header.trim().length() > 0) { - logger.debug("{} is a fragment bundle, state won't be checked", b); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format("{} is a fragment bundle, state won't be checked", b).getMessage()); return true; } else { return false; Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/ScriptableHealthCheck.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/ScriptableHealthCheck.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/ScriptableHealthCheck.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/ScriptableHealthCheck.java Mon Aug 12 14:49:50 2013 @@ -17,8 +17,6 @@ */ package org.apache.sling.hc.impl.healthchecks; -import java.util.Arrays; -import java.util.HashMap; import java.util.Map; import javax.script.Bindings; @@ -35,11 +33,13 @@ import org.apache.sling.commons.osgi.Pro import org.apache.sling.hc.api.Constants; import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; +import org.apache.sling.hc.api.ResultLogEntry; +import org.apache.sling.hc.util.HealthCheckInfo; import org.osgi.framework.BundleContext; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.helpers.MessageFormatter; /** {@link HealthCheck} that checks a scriptable expression */ @Component( @@ -51,7 +51,7 @@ import org.slf4j.LoggerFactory; public class ScriptableHealthCheck implements HealthCheck { private final Logger log = LoggerFactory.getLogger(getClass()); - private final Map info = new HashMap(); + private Map info; private String expression; private String languageExtension; private BundleContext bundleContext; @@ -78,42 +78,50 @@ public class ScriptableHealthCheck imple @Activate public void activate(ComponentContext ctx) { + info = new HealthCheckInfo(ctx.getProperties()); bundleContext = ctx.getBundleContext(); expression = PropertiesUtil.toString(ctx.getProperties().get(PROP_EXPRESSION), ""); languageExtension = PropertiesUtil.toString(ctx.getProperties().get(PROP_LANGUAGE_EXTENSION), DEFAULT_LANGUAGE_EXTENSION); info.put(PROP_EXPRESSION, expression); info.put(PROP_LANGUAGE_EXTENSION, languageExtension); - info.put(Constants.HC_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_NAME), "")); - info.put(Constants.HC_MBEAN_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_MBEAN_NAME), "")); - info.put(Constants.HC_TAGS, - Arrays.asList(PropertiesUtil.toStringArray(ctx.getProperties().get(Constants.HC_TAGS), new String[] {})).toString()); log.info("Activated, name={}, languageExtension={}, expression={}", languageExtension, expression); } @Override - public Result execute(ResultLog log) { - final Result result = new Result(this, log); - log.debug("Checking expression [{}], language extension=[{}]", expression, languageExtension); + public Result execute() { + final Result result = new Result(log); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format( + "Checking expression [{}], language extension=[{}]", + expression, languageExtension).getMessage()); try { final ScriptEngine engine = scriptEngineManager.getEngineByExtension(languageExtension); if(engine == null) { - log.warn("No ScriptEngine available for extension {}", languageExtension); + result.log(ResultLogEntry.LT_WARN, + MessageFormatter.format( + "No ScriptEngine available for extension {}", + languageExtension).getMessage()); } else { // TODO pluggable Bindings? Reuse the Sling bindings providers? final Bindings b = engine.createBindings(); - b.put("jmx", new JmxScriptBinding(log)); - b.put("osgi", new OsgiScriptBinding(bundleContext, log)); + b.put("jmx", new JmxScriptBinding(result)); + b.put("osgi", new OsgiScriptBinding(bundleContext, result)); final Object value = engine.eval(expression, b); if(value!=null && "true".equals(value.toString())) { - log.debug("Expression [{}] evaluates to true as expected", expression); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format( + "Expression [{}] evaluates to true as expected", expression).getMessage()); } else { - log.warn("Expression [{}] does not evaluate to true, value={}", expression, value); + result.log(ResultLogEntry.LT_WARN, + MessageFormatter.format( + "Expression [{}] does not evaluate to true, value={}", + expression, value).getMessage()); } } } catch(Exception e) { - log.warn(e.toString(), e); + result.log(ResultLogEntry.LT_WARN, e.toString()); } return result; } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/SlingRequestStatusHealthCheck.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/SlingRequestStatusHealthCheck.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/SlingRequestStatusHealthCheck.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/impl/healthchecks/SlingRequestStatusHealthCheck.java Mon Aug 12 14:49:50 2013 @@ -18,7 +18,6 @@ package org.apache.sling.hc.impl.healthchecks; import java.util.Arrays; -import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; @@ -36,10 +35,12 @@ import org.apache.sling.engine.SlingRequ import org.apache.sling.hc.api.Constants; import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; +import org.apache.sling.hc.api.ResultLogEntry; +import org.apache.sling.hc.util.HealthCheckInfo; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.helpers.MessageFormatter; /** {@link HealthCheck} that checks the HTTP status of Sling requests */ @Component( @@ -51,7 +52,7 @@ import org.slf4j.LoggerFactory; public class SlingRequestStatusHealthCheck implements HealthCheck { private static final Logger log = LoggerFactory.getLogger(SlingRequestStatusHealthCheck.class); - private final Map info = new HashMap(); + private Map info; private String [] paths; static class PathSpec { @@ -94,19 +95,14 @@ public class SlingRequestStatusHealthChe @Activate public void activate(ComponentContext ctx) { + info = new HealthCheckInfo(ctx.getProperties()); paths = PropertiesUtil.toStringArray(ctx.getProperties().get(PROP_PATH), new String [] {}); - - info.put(Constants.HC_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_NAME), "")); - info.put(Constants.HC_MBEAN_NAME, PropertiesUtil.toString(ctx.getProperties().get(Constants.HC_MBEAN_NAME), "")); - info.put(Constants.HC_TAGS, - Arrays.asList(PropertiesUtil.toStringArray(ctx.getProperties().get(Constants.HC_TAGS), new String[] {})).toString()); - log.info("Activated, paths={}", Arrays.asList(paths)); } @Override - public Result execute(ResultLog log) { - final Result result = new Result(this, log); + public Result execute() { + final Result result = new Result(log); ResourceResolver resolver = null; int checked = 0; @@ -122,14 +118,18 @@ public class SlingRequestStatusHealthChe final int status = response.getStatus(); if(status != ps.status) { failed++; - log.warn("[{}] returns status {}, expected {}", new Object[] { ps.path, status, ps.status }); + result.log(ResultLogEntry.LT_WARN, + MessageFormatter.format( + "[{}] returns status {}, expected {}", new Object[] { ps.path, status, ps.status }).getMessage()); } else { - log.debug("[{}] returns status {} as expected", ps.path, status); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format( + "[{}] returns status {} as expected", ps.path, status).getMessage()); } checked++; } } catch(Exception e) { - log.warn("Exception while executing request", e); + result.log(ResultLogEntry.LT_WARN, "Exception while executing request: " + e.toString()); } finally { if(resolver != null) { resolver.close(); @@ -137,9 +137,11 @@ public class SlingRequestStatusHealthChe } if(checked == 0) { - log.warn("No paths checked, empty paths list?"); + result.log(ResultLogEntry.LT_WARN, "No paths checked, empty paths list?"); } else { - log.debug("{} paths checked, {} failures", checked, failed); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format( + "{} paths checked, {} failures", checked, failed).getMessage()); } return result; Added: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/HealthCheckInfo.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/HealthCheckInfo.java?rev=1513154&view=auto ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/HealthCheckInfo.java (added) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/HealthCheckInfo.java Mon Aug 12 14:49:50 2013 @@ -0,0 +1,42 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The SF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package org.apache.sling.hc.util; + +import java.util.Arrays; +import java.util.Dictionary; +import java.util.HashMap; + +import org.apache.sling.commons.osgi.PropertiesUtil; +import org.apache.sling.hc.api.Constants; + +// TODO move to services bundle + +/** Utility that copies useful HealthCheck service + * properties to a Map that can be used as the Result's + * info(). Copies all service properties that have names + * that start with the {#Constants.HC_PROP_PREFIX} */ +public class HealthCheckInfo extends HashMap { + private static final long serialVersionUID = 8661195387931574705L; + + public HealthCheckInfo(Dictionary serviceProperties) { + put(Constants.HC_NAME, PropertiesUtil.toString(serviceProperties.get(Constants.HC_NAME), "")); + put(Constants.HC_MBEAN_NAME, PropertiesUtil.toString(serviceProperties.get(Constants.HC_MBEAN_NAME), "")); + put(Constants.HC_TAGS, + Arrays.asList(PropertiesUtil.toStringArray(serviceProperties.get(Constants.HC_TAGS), new String[] {})).toString()); + } +} \ No newline at end of file Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/SimpleConstraintChecker.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/SimpleConstraintChecker.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/SimpleConstraintChecker.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/java/org/apache/sling/hc/util/SimpleConstraintChecker.java Mon Aug 12 14:49:50 2013 @@ -17,7 +17,9 @@ */ package org.apache.sling.hc.util; -import org.slf4j.Logger; +import org.apache.sling.hc.api.Result; +import org.apache.sling.hc.api.ResultLogEntry; +import org.slf4j.helpers.MessageFormatter; /** Simple check of numeric values against expressions * like < N, > N, between two values etc. @@ -27,8 +29,8 @@ public class SimpleConstraintChecker { public static final String CONTAINS = "contains"; - /** Check value against expression and report to logger */ - public void check(Object inputValue, String constraint, Logger logger) { + /** Check value against expression and report to result */ + public void check(Object inputValue, String constraint, Result result) { final String stringValue = inputValue == null ? "" : inputValue.toString(); @@ -62,13 +64,19 @@ public class SimpleConstraintChecker { matches = constraint.equals(stringValue); } } catch(NumberFormatException nfe) { - logger.warn("Invalid numeric value [{}] while evaluating {}", inputValue, constraint); + result.log(ResultLogEntry.LT_WARN, + MessageFormatter.format( + "Invalid numeric value [{}] while evaluating {}", inputValue, constraint).getMessage()); } if(matches) { - logger.debug("Value [{}] matches constraint [{}]", stringValue, constraint); + result.log(ResultLogEntry.LT_DEBUG, + MessageFormatter.format( + "Value [{}] matches constraint [{}]", stringValue, constraint).getMessage()); } else { - logger.warn("Value [{}] does not match constraint [{}]", stringValue, constraint); + result.log(ResultLogEntry.LT_WARN, + MessageFormatter.format( + "Value [{}] does not match constraint [{}]", stringValue, constraint).getMessage()); } } } \ No newline at end of file Modified: sling/trunk/contrib/extensions/healthcheck/core/src/main/resources/res/ui/healthcheck.css URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/main/resources/res/ui/healthcheck.css?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/main/resources/res/ui/healthcheck.css (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/main/resources/res/ui/healthcheck.css Mon Aug 12 14:49:50 2013 @@ -23,7 +23,10 @@ color:blue; } -.healthcheck .logWARN { +.healthcheck .logWARN, +.healthcheck .logSECURITY, +.healthcheck .logCONFIG +{ color:red; } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/api/ResultTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/api/ResultTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/api/ResultTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/api/ResultTest.java Mon Aug 12 14:49:50 2013 @@ -17,49 +17,98 @@ */ package org.apache.sling.hc.api; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.Before; +import java.util.Iterator; + import org.junit.Test; -import org.slf4j.LoggerFactory; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.slf4j.Logger; public class ResultTest { - private ResultLog resultLog; - private Result result; - @Before - public void setup() { - resultLog = new ResultLog(LoggerFactory.getLogger(getClass())); - result = new Result(null, resultLog); + @Test + public void testInitiallyOk() { + final Result result = new Result(); + assertFalse(result.iterator().hasNext()); + assertTrue(result.isOk()); } @Test - public void testInitiallyNotOk() { - assertFalse(result.isOk()); + public void testDebugLogNoChange() { + final Result result = new Result(); + result.log(ResultLogEntry.LT_DEBUG, "Some debug message"); + assertTrue(result.iterator().hasNext()); + assertTrue(result.isOk()); } @Test - public void testDebugOk() { - resultLog.debug("something"); + public void testInfoLogNoChange() { + final Result result = new Result(); + result.log(ResultLogEntry.LT_INFO, "Some info message"); + assertTrue(result.iterator().hasNext()); assertTrue(result.isOk()); } @Test - public void testInfoOk() { - resultLog.info("something"); - assertTrue(result.isOk()); + public void testOthersTypesSetStatusWarn() { + final String [] entryTypes = new String [] { + ResultLogEntry.LT_WARN, + ResultLogEntry.LT_WARN_CONFIG, + ResultLogEntry.LT_WARN_SECURITY, + "SomeNewLogEntryType" + System.currentTimeMillis() + }; + + for(String et : entryTypes) { + final Result result = new Result(); + result.log(et, "Some message"); + assertTrue(result.iterator().hasNext()); + assertTrue(result.getStatus().equals(Result.Status.WARN)); + } + } + + @Test + public void testNoStatusChangeIfAlreadyCritical() { + final Result result = new Result(); + result.setStatus(Result.Status.CRITICAL); + assertTrue(result.getStatus().equals(Result.Status.CRITICAL)); + result.log(ResultLogEntry.LT_WARN, "Some message"); + assertTrue(result.iterator().hasNext()); + assertTrue(result.getStatus().equals(Result.Status.CRITICAL)); + } + + @Test + public void testSuppliedLogger() { + final Logger myLogger = Mockito.mock(Logger.class); + final Result r = new Result(myLogger); + r.log("foo", "Some message"); + Mockito.verify(myLogger).warn(Matchers.anyString()); } @Test - public void testWarnNotOk() { - resultLog.warn("something"); - assertFalse(result.isOk()); + public void testLogEntries() { + final Result r = new Result(); + r.log("ONE", "M1"); + r.log("two", "M2"); + r.log("THREE", "M3"); + + final Iterator it = r.iterator(); + assertEquals("ONE", it.next().getEntryType()); + assertEquals("two", it.next().getEntryType()); + assertEquals("THREE", it.next().getEntryType()); + assertFalse(it.hasNext()); } @Test - public void testErrorNotOk() { - resultLog.error("something"); - assertFalse(result.isOk()); + public void testSetStatus() { + final Result r = new Result(); + assertEquals("Expecting initial OK status", Result.Status.OK, r.getStatus()); + r.setStatus(Result.Status.CRITICAL); + assertEquals("Expecting CRITICAL status after setting it", Result.Status.CRITICAL, r.getStatus()); + r.setStatus(Result.Status.WARN); + assertEquals("Still expecting CRITICAL status after setting it to WARN", Result.Status.CRITICAL, r.getStatus()); } } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/DefaultLoginsHealthCheckTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/DefaultLoginsHealthCheckTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/DefaultLoginsHealthCheckTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/DefaultLoginsHealthCheckTest.java Mon Aug 12 14:49:50 2013 @@ -28,7 +28,6 @@ import javax.jcr.Session; import javax.jcr.SimpleCredentials; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; import org.apache.sling.hc.impl.healthchecks.DefaultLoginsHealthCheck; import org.apache.sling.jcr.api.SlingRepository; import org.junit.Test; @@ -36,13 +35,9 @@ import org.mockito.Matchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class DefaultLoginsHealthCheckTest { - private final Logger logger = LoggerFactory.getLogger(getClass()); - private Result getTestResult(String login) throws Exception { final DefaultLoginsHealthCheck c = new DefaultLoginsHealthCheck(); setField(c, "logins", Arrays.asList(new String[] { login })); @@ -61,8 +56,7 @@ public class DefaultLoginsHealthCheckTes } }); - final ResultLog log = new ResultLog(logger); - return c.execute(log); + return c.execute(); } private void setField(Object o, String name, Object value) throws Exception { Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/HealthCheckMBeanTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/HealthCheckMBeanTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/HealthCheckMBeanTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/HealthCheckMBeanTest.java Mon Aug 12 14:49:50 2013 @@ -26,7 +26,7 @@ import javax.management.ObjectName; import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; +import org.apache.sling.hc.api.ResultLogEntry; import org.junit.Test; public class HealthCheckMBeanTest { @@ -43,12 +43,12 @@ public class HealthCheckMBeanTest { private HealthCheck testHealthCheck = new HealthCheck() { @Override - public Result execute(ResultLog log) { - final Result result = new Result(this, log); + public Result execute() { + final Result result = new Result(); if(resultOk) { - log.debug("Nothing to report, result ok"); + result.log(ResultLogEntry.LT_DEBUG, "Nothing to report, result ok"); } else { - log.warn("Result is not ok!"); + result.log(ResultLogEntry.LT_WARN, "Result is not ok!"); } return result; } Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxAttributeHealthCheckTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxAttributeHealthCheckTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxAttributeHealthCheckTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxAttributeHealthCheckTest.java Mon Aug 12 14:49:50 2013 @@ -17,24 +17,21 @@ */ package org.apache.sling.hc.impl; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertEquals; import java.util.Dictionary; import java.util.Hashtable; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; import org.apache.sling.hc.impl.healthchecks.JmxAttributeHealthCheck; import org.junit.Test; import org.mockito.Mockito; import org.osgi.service.component.ComponentContext; -import org.slf4j.LoggerFactory; public class JmxAttributeHealthCheckTest { static void assertJmxValue(String objectName, String attributeName, String constraint, boolean expected) { final JmxAttributeHealthCheck hc = new JmxAttributeHealthCheck(); - final ResultLog log = new ResultLog(LoggerFactory.getLogger(JmxAttributeHealthCheckTest.class)); final ComponentContext ctx = Mockito.mock(ComponentContext.class); final Dictionary props = new Hashtable(); @@ -44,10 +41,8 @@ public class JmxAttributeHealthCheckTest Mockito.when(ctx.getProperties()).thenReturn(props); hc.activate(ctx); - final Result r = hc.execute(log); - if(r.isOk() != expected) { - fail("HealthCheck result is " + r.isOk() + ", log=" + r.getLogEntries()); - } + final Result r = hc.execute(); + assertEquals("Expected result " + expected, expected, r.isOk()); } @Test Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxScriptBindingTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxScriptBindingTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxScriptBindingTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/JmxScriptBindingTest.java Mon Aug 12 14:49:50 2013 @@ -17,21 +17,25 @@ */ package org.apache.sling.hc.impl; -import org.apache.sling.hc.impl.healthchecks.JmxScriptBinding; -import org.junit.Test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; + +import org.apache.sling.hc.api.Result; +import org.apache.sling.hc.impl.healthchecks.JmxScriptBinding; +import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JmxScriptBindingTest { + private final Logger logger = LoggerFactory.getLogger(getClass()); @Test public void testJmxAttribute() throws Exception { - final JmxScriptBinding b = new JmxScriptBinding(logger); - final Object result = b.attribute("java.lang:type=ClassLoading", "LoadedClassCount"); - assertNotNull("Expecting non-null attribute value", result); - assertTrue("Expecting non-empty value", result.toString().length() > 0); + final Result r = new Result(logger); + final JmxScriptBinding b = new JmxScriptBinding(r); + final Object value= b.attribute("java.lang:type=ClassLoading", "LoadedClassCount"); + assertNotNull("Expecting non-null attribute value", value); + assertTrue("Expecting non-empty value", value.toString().length() > 0); } } \ No newline at end of file Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/OsgiScriptBindingTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/OsgiScriptBindingTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/OsgiScriptBindingTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/OsgiScriptBindingTest.java Mon Aug 12 14:49:50 2013 @@ -22,6 +22,7 @@ import static org.junit.Assert.assertEqu import java.util.Dictionary; import java.util.Hashtable; +import org.apache.sling.hc.api.Result; import org.apache.sling.hc.impl.healthchecks.OsgiScriptBinding; import org.junit.Test; import org.mockito.Mockito; @@ -59,7 +60,8 @@ public class OsgiScriptBindingTest { }; Mockito.when(ctx.getBundles()).thenReturn(bundles); - final OsgiScriptBinding b = new OsgiScriptBinding(ctx, logger); + final Result r = new Result(logger); + final OsgiScriptBinding b = new OsgiScriptBinding(ctx, r); assertEquals(1, b.inactiveBundlesCount()); } } \ No newline at end of file Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/ScriptableHealthCheckTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/ScriptableHealthCheckTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/ScriptableHealthCheckTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/ScriptableHealthCheckTest.java Mon Aug 12 14:49:50 2013 @@ -17,8 +17,8 @@ */ package org.apache.sling.hc.impl; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; import java.lang.reflect.Field; import java.util.Dictionary; @@ -28,24 +28,20 @@ import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; import org.apache.sling.hc.impl.healthchecks.ScriptableHealthCheck; import org.junit.Test; import org.mockito.Matchers; import org.mockito.Mockito; import org.osgi.service.component.ComponentContext; -import org.slf4j.LoggerFactory; public class ScriptableHealthCheckTest { private ScriptableHealthCheck hc; - private ResultLog log; private Dictionary props; private ComponentContext ctx; private void assertExpression(String expression, String languageExtension, boolean expected) throws Exception { hc = new ScriptableHealthCheck(); - log = new ResultLog(LoggerFactory.getLogger(getClass())); ctx = Mockito.mock(ComponentContext.class); props = new Hashtable(); @@ -63,10 +59,8 @@ public class ScriptableHealthCheckTest { } Mockito.when(ctx.getProperties()).thenReturn(props); hc.activate(ctx); - final Result r = hc.execute(log); - if(r.isOk() != expected) { - fail("HealthCheck result is " + r.isOk() + ", log=" + r.getLogEntries()); - } + final Result r = hc.execute(); + assertEquals("Expecting result " + expected, expected, r.isOk()); } @Test Modified: sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/SimpleConstraintCheckerTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/SimpleConstraintCheckerTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/SimpleConstraintCheckerTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/core/src/test/java/org/apache/sling/hc/impl/SimpleConstraintCheckerTest.java Mon Aug 12 14:49:50 2013 @@ -21,150 +21,146 @@ import static org.junit.Assert.assertFal import static org.junit.Assert.assertTrue; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; import org.apache.sling.hc.util.SimpleConstraintChecker; import org.junit.Before; import org.junit.Test; -import org.slf4j.LoggerFactory; public class SimpleConstraintCheckerTest { - private ResultLog resultLog; private Result result; private final SimpleConstraintChecker checker = new SimpleConstraintChecker(); @Before public void setup() { - resultLog = new ResultLog(LoggerFactory.getLogger(getClass())); - result = new Result(null, resultLog); + result = new Result(); } @Test public void testStringEquals() { final String s = "test_" + System.currentTimeMillis(); - checker.check(s, s, resultLog); + checker.check(s, s, result); assertTrue(result.isOk()); } @Test public void testStringNotEquals() { final String s = "test_" + System.currentTimeMillis(); - checker.check(s, "something else", resultLog); + checker.check(s, "something else", result); assertFalse(result.isOk()); } @Test public void testFiveEquals() { final String s = "5"; - checker.check(s, s, resultLog); + checker.check(s, s, result); assertTrue(result.isOk()); } @Test public void testIntTwelveEquals() { - checker.check(12, "12", resultLog); + checker.check(12, "12", result); assertTrue(result.isOk()); } @Test public void testIntTwelveGreaterThan() { - checker.check(12, "> 11", resultLog); + checker.check(12, "> 11", result); assertTrue(result.isOk()); } @Test public void testFiveNotEquals() { - checker.check("5", "foo", resultLog); + checker.check("5", "foo", result); assertFalse(result.isOk()); } @Test public void testNullNotEquals() { - checker.check(null, "foo", resultLog); + checker.check(null, "foo", result); assertFalse(result.isOk()); } @Test public void testNullNotGreater() { - checker.check(null, "> 2", resultLog); + checker.check(null, "> 2", result); assertFalse(result.isOk()); } @Test public void testGreaterThanTrue() { - checker.check("5", "> 2", resultLog); + checker.check("5", "> 2", result); assertTrue(result.isOk()); } @Test public void testGreaterThanFalse() { - checker.check("5", "> 12", resultLog); + checker.check("5", "> 12", result); assertFalse(result.isOk()); } @Test public void testLessThanTrue() { - checker.check("5", "< 12", resultLog); + checker.check("5", "< 12", result); assertTrue(result.isOk()); } @Test public void testLessThanFalse() { - checker.check("5", "< 2", resultLog); + checker.check("5", "< 2", result); assertFalse(result.isOk()); } @Test public void testBetweenA() { - checker.check("5", "between 2 and 6", resultLog); + checker.check("5", "between 2 and 6", result); assertTrue(result.isOk()); } @Test public void testBetweenB() { - checker.check("5", "between 12 and 16", resultLog); + checker.check("5", "between 12 and 16", result); assertFalse(result.isOk()); } @Test public void testBetweenC() { - checker.check(5L, "between 12 and 16", resultLog); + checker.check(5L, "between 12 and 16", result); assertFalse(result.isOk()); } @Test public void testBetweenD() { - checker.check(5L, "between 4 and 16", resultLog); + checker.check(5L, "between 4 and 16", result); assertTrue(result.isOk()); } @Test public void testBetweenE() { - checker.check(5L, "betWEEN 4 aND 16", resultLog); + checker.check(5L, "betWEEN 4 aND 16", result); assertTrue(result.isOk()); } @Test public void testNotAnInteger() { - checker.check("foo", "between 12 and 16", resultLog); + checker.check("foo", "between 12 and 16", result); assertFalse(result.isOk()); } @Test public void testContainsA() { - checker.check("This is a NICE STRING ok?", "contains NICE STRING", resultLog); + checker.check("This is a NICE STRING ok?", "contains NICE STRING", result); assertTrue(result.isOk()); } @Test public void testContainsB() { - checker.check("This is a NICE TOUCH ok?", "contains NICE STRING", resultLog); + checker.check("This is a NICE TOUCH ok?", "contains NICE STRING", result); assertFalse(result.isOk()); } @Test public void testContainsC() { - checker.check("This is a NICE TOUCH ok?", "contains NICE", resultLog); + checker.check("This is a NICE TOUCH ok?", "contains NICE", result); assertTrue(result.isOk()); } } Modified: sling/trunk/contrib/extensions/healthcheck/it/src/test/java/org/apache/sling/hc/it/core/HealthCheckSelectorTest.java URL: http://svn.apache.org/viewvc/sling/trunk/contrib/extensions/healthcheck/it/src/test/java/org/apache/sling/hc/it/core/HealthCheckSelectorTest.java?rev=1513154&r1=1513153&r2=1513154&view=diff ============================================================================== --- sling/trunk/contrib/extensions/healthcheck/it/src/test/java/org/apache/sling/hc/it/core/HealthCheckSelectorTest.java (original) +++ sling/trunk/contrib/extensions/healthcheck/it/src/test/java/org/apache/sling/hc/it/core/HealthCheckSelectorTest.java Mon Aug 12 14:49:50 2013 @@ -35,7 +35,6 @@ import org.apache.sling.hc.api.Constants import org.apache.sling.hc.api.HealthCheck; import org.apache.sling.hc.api.HealthCheckSelector; import org.apache.sling.hc.api.Result; -import org.apache.sling.hc.api.ResultLog; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -96,7 +95,7 @@ public class HealthCheckSelectorTest { } @Override - public Result execute(ResultLog log) { + public Result execute() { return null; }